techprotrade commited on
Commit
ca8124b
·
verified ·
1 Parent(s): 8932888

Add loan-advisor-agent

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. loan-advisor-agent/.venv/Lib/site-packages/grpc/__init__.py +2347 -0
  3. loan-advisor-agent/.venv/Lib/site-packages/grpc/__pycache__/__init__.cpython-312.pyc +0 -0
  4. loan-advisor-agent/.venv/Lib/site-packages/grpc/__pycache__/_channel.cpython-312.pyc +0 -0
  5. loan-advisor-agent/.venv/Lib/site-packages/grpc/__pycache__/_common.cpython-312.pyc +0 -0
  6. loan-advisor-agent/.venv/Lib/site-packages/grpc/__pycache__/_compression.cpython-312.pyc +0 -0
  7. loan-advisor-agent/.venv/Lib/site-packages/grpc/__pycache__/_grpcio_metadata.cpython-312.pyc +0 -0
  8. loan-advisor-agent/.venv/Lib/site-packages/grpc/__pycache__/_observability.cpython-312.pyc +0 -0
  9. loan-advisor-agent/.venv/Lib/site-packages/grpc/__pycache__/_runtime_protos.cpython-312.pyc +0 -0
  10. loan-advisor-agent/.venv/Lib/site-packages/grpc/__pycache__/_simple_stubs.cpython-312.pyc +0 -0
  11. loan-advisor-agent/.venv/Lib/site-packages/grpc/__pycache__/_typing.cpython-312.pyc +0 -0
  12. loan-advisor-agent/.venv/Lib/site-packages/grpc/_auth.py +80 -0
  13. loan-advisor-agent/.venv/Lib/site-packages/grpc/_channel.py +2229 -0
  14. loan-advisor-agent/.venv/Lib/site-packages/grpc/_common.py +180 -0
  15. loan-advisor-agent/.venv/Lib/site-packages/grpc/_compression.py +71 -0
  16. loan-advisor-agent/.venv/Lib/site-packages/grpc/_cython/__init__.py +13 -0
  17. loan-advisor-agent/.venv/Lib/site-packages/grpc/_cython/__pycache__/__init__.cpython-312.pyc +0 -0
  18. loan-advisor-agent/.venv/Lib/site-packages/grpc/_cython/_credentials/roots.pem +0 -0
  19. loan-advisor-agent/.venv/Lib/site-packages/grpc/_cython/_cygrpc/__init__.py +13 -0
  20. loan-advisor-agent/.venv/Lib/site-packages/grpc/_cython/_cygrpc/private_key_signing/private_key_signer_py_wrapper.cc +100 -0
  21. loan-advisor-agent/.venv/Lib/site-packages/grpc/_cython/_cygrpc/private_key_signing/private_key_signer_py_wrapper.h +143 -0
  22. loan-advisor-agent/.venv/Lib/site-packages/grpc/_cython/cygrpc.cp312-win_amd64.pyd +3 -0
  23. loan-advisor-agent/.venv/Lib/site-packages/grpc/_grpcio_metadata.py +1 -0
  24. loan-advisor-agent/.venv/Lib/site-packages/grpc/_interceptor.py +809 -0
  25. loan-advisor-agent/.venv/Lib/site-packages/grpc/_observability.py +312 -0
  26. loan-advisor-agent/.venv/Lib/site-packages/grpc/_plugin_wrapping.py +136 -0
  27. loan-advisor-agent/.venv/Lib/site-packages/grpc/_runtime_protos.py +163 -0
  28. loan-advisor-agent/.venv/Lib/site-packages/grpc/_server.py +1515 -0
  29. loan-advisor-agent/.venv/Lib/site-packages/grpc/_simple_stubs.py +587 -0
  30. loan-advisor-agent/.venv/Lib/site-packages/grpc/_typing.py +96 -0
  31. loan-advisor-agent/.venv/Lib/site-packages/grpc/_utilities.py +220 -0
  32. loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/__init__.py +95 -0
  33. loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/__pycache__/__init__.cpython-312.pyc +0 -0
  34. loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/__pycache__/_base_call.cpython-312.pyc +0 -0
  35. loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/__pycache__/_base_channel.cpython-312.pyc +0 -0
  36. loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/__pycache__/_base_server.cpython-312.pyc +0 -0
  37. loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/__pycache__/_call.cpython-312.pyc +0 -0
  38. loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/__pycache__/_channel.cpython-312.pyc +0 -0
  39. loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/__pycache__/_interceptor.cpython-312.pyc +0 -0
  40. loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/__pycache__/_metadata.cpython-312.pyc +0 -0
  41. loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/__pycache__/_server.cpython-312.pyc +0 -0
  42. loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/__pycache__/_typing.cpython-312.pyc +0 -0
  43. loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/__pycache__/_utils.cpython-312.pyc +0 -0
  44. loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/_base_call.py +257 -0
  45. loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/_base_channel.py +364 -0
  46. loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/_base_server.py +387 -0
  47. loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/_call.py +759 -0
  48. loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/_channel.py +625 -0
  49. loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/_interceptor.py +1177 -0
  50. loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/_metadata.py +167 -0
.gitattributes CHANGED
@@ -429,3 +429,4 @@ loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/buck
429
  loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/models.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
430
  loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/types.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
431
  loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/descriptor_pb2.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
 
 
429
  loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/models.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
430
  loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/types.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
431
  loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/descriptor_pb2.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
432
+ loan-advisor-agent/.venv/Lib/site-packages/grpc/_cython/cygrpc.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
loan-advisor-agent/.venv/Lib/site-packages/grpc/__init__.py ADDED
@@ -0,0 +1,2347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
28
+ logging.getLogger(__name__).addHandler(logging.NullHandler())
29
+
30
+ try:
31
+ # pylint: disable=ungrouped-imports
32
+ from grpc._grpcio_metadata import __version__
33
+ except ImportError:
34
+ __version__ = "dev0"
35
+
36
+ ############################## Future Interface ###############################
37
+
38
+
39
+ class FutureTimeoutError(Exception):
40
+ """Indicates that a method call on a Future timed out."""
41
+
42
+
43
+ class FutureCancelledError(Exception):
44
+ """Indicates that the computation underlying a Future was cancelled."""
45
+
46
+
47
+ class 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
211
+ class 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
+
223
+ IDLE = (_cygrpc.ConnectivityState.idle, "idle")
224
+ CONNECTING = (_cygrpc.ConnectivityState.connecting, "connecting")
225
+ READY = (_cygrpc.ConnectivityState.ready, "ready")
226
+ TRANSIENT_FAILURE = (
227
+ _cygrpc.ConnectivityState.transient_failure,
228
+ "transient failure",
229
+ )
230
+ SHUTDOWN = (_cygrpc.ConnectivityState.shutdown, "shutdown")
231
+
232
+
233
+ @enum.unique
234
+ class StatusCode(enum.Enum):
235
+ """Mirrors grpc_status_code in the gRPC Core.
236
+
237
+ Attributes:
238
+ OK: Not an error; returned on success
239
+ CANCELLED: The operation was cancelled (typically by the caller).
240
+ UNKNOWN: Unknown error.
241
+ INVALID_ARGUMENT: Client specified an invalid argument.
242
+ DEADLINE_EXCEEDED: Deadline expired before operation could complete.
243
+ NOT_FOUND: Some requested entity (e.g., file or directory) was not found.
244
+ ALREADY_EXISTS: Some entity that we attempted to create (e.g., file or directory)
245
+ already exists.
246
+ PERMISSION_DENIED: The caller does not have permission to execute the specified
247
+ operation.
248
+ UNAUTHENTICATED: The request does not have valid authentication credentials for the
249
+ operation.
250
+ RESOURCE_EXHAUSTED: Some resource has been exhausted, perhaps a per-user quota, or
251
+ perhaps the entire file system is out of space.
252
+ FAILED_PRECONDITION: Operation was rejected because the system is not in a state
253
+ required for the operation's execution.
254
+ ABORTED: The operation was aborted, typically due to a concurrency issue
255
+ like sequencer check failures, transaction aborts, etc.
256
+ UNIMPLEMENTED: Operation is not implemented or not supported/enabled in this service.
257
+ INTERNAL: Internal errors. Means some invariants expected by underlying
258
+ system has been broken.
259
+ UNAVAILABLE: The service is currently unavailable.
260
+ DATA_LOSS: Unrecoverable data loss or corruption.
261
+ """
262
+
263
+ OK = (_cygrpc.StatusCode.ok, "ok")
264
+ CANCELLED = (_cygrpc.StatusCode.cancelled, "cancelled")
265
+ UNKNOWN = (_cygrpc.StatusCode.unknown, "unknown")
266
+ INVALID_ARGUMENT = (_cygrpc.StatusCode.invalid_argument, "invalid argument")
267
+ DEADLINE_EXCEEDED = (
268
+ _cygrpc.StatusCode.deadline_exceeded,
269
+ "deadline exceeded",
270
+ )
271
+ NOT_FOUND = (_cygrpc.StatusCode.not_found, "not found")
272
+ ALREADY_EXISTS = (_cygrpc.StatusCode.already_exists, "already exists")
273
+ PERMISSION_DENIED = (
274
+ _cygrpc.StatusCode.permission_denied,
275
+ "permission denied",
276
+ )
277
+ RESOURCE_EXHAUSTED = (
278
+ _cygrpc.StatusCode.resource_exhausted,
279
+ "resource exhausted",
280
+ )
281
+ FAILED_PRECONDITION = (
282
+ _cygrpc.StatusCode.failed_precondition,
283
+ "failed precondition",
284
+ )
285
+ ABORTED = (_cygrpc.StatusCode.aborted, "aborted")
286
+ OUT_OF_RANGE = (_cygrpc.StatusCode.out_of_range, "out of range")
287
+ UNIMPLEMENTED = (_cygrpc.StatusCode.unimplemented, "unimplemented")
288
+ INTERNAL = (_cygrpc.StatusCode.internal, "internal")
289
+ UNAVAILABLE = (_cygrpc.StatusCode.unavailable, "unavailable")
290
+ DATA_LOSS = (_cygrpc.StatusCode.data_loss, "data loss")
291
+ UNAUTHENTICATED = (_cygrpc.StatusCode.unauthenticated, "unauthenticated")
292
+
293
+
294
+ ############################# gRPC Status ################################
295
+
296
+
297
+ class Status(abc.ABC):
298
+ """Describes the status of an RPC.
299
+
300
+ This is an EXPERIMENTAL API.
301
+
302
+ Attributes:
303
+ code: A StatusCode object to be sent to the client.
304
+ details: A UTF-8-encodable string to be sent to the client upon
305
+ termination of the RPC.
306
+ trailing_metadata: The trailing :term:`metadata` in the RPC.
307
+ """
308
+
309
+
310
+ ############################# gRPC Exceptions ################################
311
+
312
+
313
+ class RpcError(Exception):
314
+ """Raised by the gRPC library to indicate non-OK-status RPC termination."""
315
+
316
+
317
+ ############################## Shared Context ################################
318
+
319
+
320
+ class RpcContext(abc.ABC):
321
+ """Provides RPC-related information and action."""
322
+
323
+ @abc.abstractmethod
324
+ def is_active(self):
325
+ """Describes whether the RPC is active or has terminated.
326
+
327
+ Returns:
328
+ bool:
329
+ True if RPC is active, False otherwise.
330
+ """
331
+ raise NotImplementedError()
332
+
333
+ @abc.abstractmethod
334
+ def time_remaining(self):
335
+ """Describes the length of allowed time remaining for the RPC.
336
+
337
+ Returns:
338
+ A nonnegative float indicating the length of allowed time in seconds
339
+ remaining for the RPC to complete before it is considered to have
340
+ timed out, or None if no deadline was specified for the RPC.
341
+ """
342
+ raise NotImplementedError()
343
+
344
+ @abc.abstractmethod
345
+ def cancel(self):
346
+ """Cancels the RPC.
347
+
348
+ Idempotent and has no effect if the RPC has already terminated.
349
+ """
350
+ raise NotImplementedError()
351
+
352
+ @abc.abstractmethod
353
+ def add_callback(self, callback):
354
+ """Registers a callback to be called on RPC termination.
355
+
356
+ Args:
357
+ callback: A no-parameter callable to be called on RPC termination.
358
+
359
+ Returns:
360
+ True if the callback was added and will be called later; False if
361
+ the callback was not added and will not be called (because the RPC
362
+ already terminated or some other reason).
363
+ """
364
+ raise NotImplementedError()
365
+
366
+
367
+ ######################### Invocation-Side Context ############################
368
+
369
+
370
+ class Call(RpcContext, metaclass=abc.ABCMeta):
371
+ """Invocation-side utility object for an RPC."""
372
+
373
+ @abc.abstractmethod
374
+ def initial_metadata(self):
375
+ """Accesses the initial metadata sent by the server.
376
+
377
+ This method blocks until the value is available.
378
+
379
+ Returns:
380
+ The initial :term:`metadata`.
381
+ """
382
+ raise NotImplementedError()
383
+
384
+ @abc.abstractmethod
385
+ def trailing_metadata(self):
386
+ """Accesses the trailing metadata sent by the server.
387
+
388
+ This method blocks until the value is available.
389
+
390
+ Returns:
391
+ The trailing :term:`metadata`.
392
+ """
393
+ raise NotImplementedError()
394
+
395
+ @abc.abstractmethod
396
+ def code(self):
397
+ """Accesses the status code sent by the server.
398
+
399
+ This method blocks until the value is available.
400
+
401
+ Returns:
402
+ The StatusCode value for the RPC.
403
+ """
404
+ raise NotImplementedError()
405
+
406
+ @abc.abstractmethod
407
+ def details(self):
408
+ """Accesses the details sent by the server.
409
+
410
+ This method blocks until the value is available.
411
+
412
+ Returns:
413
+ The details string of the RPC.
414
+ """
415
+ raise NotImplementedError()
416
+
417
+
418
+ ############## Invocation-Side Interceptor Interfaces & Classes ##############
419
+
420
+
421
+ class ClientCallDetails(abc.ABC):
422
+ """Describes an RPC to be invoked.
423
+
424
+ Attributes:
425
+ method: The method name of the RPC.
426
+ timeout: An optional duration of time in seconds to allow for the RPC.
427
+ metadata: Optional :term:`metadata` to be transmitted to
428
+ the service-side of the RPC.
429
+ credentials: An optional CallCredentials for the RPC.
430
+ wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
431
+ compression: An element of grpc.Compression, e.g.
432
+ grpc.Compression.Gzip.
433
+ """
434
+
435
+
436
+ class UnaryUnaryClientInterceptor(abc.ABC):
437
+ """Affords intercepting unary-unary invocations."""
438
+
439
+ @abc.abstractmethod
440
+ def intercept_unary_unary(self, continuation, client_call_details, request):
441
+ """Intercepts a unary-unary invocation asynchronously.
442
+
443
+ Args:
444
+ continuation: A function that proceeds with the invocation by
445
+ executing the next interceptor in chain or invoking the
446
+ actual RPC on the underlying Channel. It is the interceptor's
447
+ responsibility to call it if it decides to move the RPC forward.
448
+ The interceptor can use
449
+ `response_future = continuation(client_call_details, request)`
450
+ to continue with the RPC. `continuation` returns an object that is
451
+ both a Call for the RPC and a Future. In the event of RPC
452
+ completion, the return Call-Future's result value will be
453
+ the response message of the RPC. Should the event terminate
454
+ with non-OK status, the returned Call-Future's exception value
455
+ will be an RpcError.
456
+ client_call_details: A ClientCallDetails object describing the
457
+ outgoing RPC.
458
+ request: The request value for the RPC.
459
+
460
+ Returns:
461
+ An object that is both a Call for the RPC and a Future.
462
+ In the event of RPC completion, the return Call-Future's
463
+ result value will be the response message of the RPC.
464
+ Should the event terminate with non-OK status, the returned
465
+ Call-Future's exception value will be an RpcError.
466
+ """
467
+ raise NotImplementedError()
468
+
469
+
470
+ class UnaryStreamClientInterceptor(abc.ABC):
471
+ """Affords intercepting unary-stream invocations."""
472
+
473
+ @abc.abstractmethod
474
+ def intercept_unary_stream(
475
+ self, continuation, client_call_details, request
476
+ ):
477
+ """Intercepts a unary-stream invocation.
478
+
479
+ Args:
480
+ continuation: A function that proceeds with the invocation by
481
+ executing the next interceptor in chain or invoking the
482
+ actual RPC on the underlying Channel. It is the interceptor's
483
+ responsibility to call it if it decides to move the RPC forward.
484
+ The interceptor can use
485
+ `response_iterator = continuation(client_call_details, request)`
486
+ to continue with the RPC. `continuation` returns an object that is
487
+ both a Call for the RPC and an iterator for response values.
488
+ Drawing response values from the returned Call-iterator may
489
+ raise RpcError indicating termination of the RPC with non-OK
490
+ status.
491
+ client_call_details: A ClientCallDetails object describing the
492
+ outgoing RPC.
493
+ request: The request value for the RPC.
494
+
495
+ Returns:
496
+ An object that is both a Call for the RPC and an iterator of
497
+ response values. Drawing response values from the returned
498
+ Call-iterator may raise RpcError indicating termination of
499
+ the RPC with non-OK status. This object *should* also fulfill the
500
+ Future interface, though it may not.
501
+ """
502
+ raise NotImplementedError()
503
+
504
+
505
+ class StreamUnaryClientInterceptor(abc.ABC):
506
+ """Affords intercepting stream-unary invocations."""
507
+
508
+ @abc.abstractmethod
509
+ def intercept_stream_unary(
510
+ self, continuation, client_call_details, request_iterator
511
+ ):
512
+ """Intercepts a stream-unary invocation asynchronously.
513
+
514
+ Args:
515
+ continuation: A function that proceeds with the invocation by
516
+ executing the next interceptor in chain or invoking the
517
+ actual RPC on the underlying Channel. It is the interceptor's
518
+ responsibility to call it if it decides to move the RPC forward.
519
+ The interceptor can use
520
+ `response_future = continuation(client_call_details, request_iterator)`
521
+ to continue with the RPC. `continuation` returns an object that is
522
+ both a Call for the RPC and a Future. In the event of RPC completion,
523
+ the return Call-Future's result value will be the response message
524
+ of the RPC. Should the event terminate with non-OK status, the
525
+ returned Call-Future's exception value will be an RpcError.
526
+ client_call_details: A ClientCallDetails object describing the
527
+ outgoing RPC.
528
+ request_iterator: An iterator that yields request values for the RPC.
529
+
530
+ Returns:
531
+ An object that is both a Call for the RPC and a Future.
532
+ In the event of RPC completion, the return Call-Future's
533
+ result value will be the response message of the RPC.
534
+ Should the event terminate with non-OK status, the returned
535
+ Call-Future's exception value will be an RpcError.
536
+ """
537
+ raise NotImplementedError()
538
+
539
+
540
+ class StreamStreamClientInterceptor(abc.ABC):
541
+ """Affords intercepting stream-stream invocations."""
542
+
543
+ @abc.abstractmethod
544
+ def intercept_stream_stream(
545
+ self, continuation, client_call_details, request_iterator
546
+ ):
547
+ """Intercepts a stream-stream invocation.
548
+
549
+ Args:
550
+ continuation: A function that proceeds with the invocation by
551
+ executing the next interceptor in chain or invoking the
552
+ actual RPC on the underlying Channel. It is the interceptor's
553
+ responsibility to call it if it decides to move the RPC forward.
554
+ The interceptor can use
555
+ `response_iterator = continuation(client_call_details, request_iterator)`
556
+ to continue with the RPC. `continuation` returns an object that is
557
+ both a Call for the RPC and an iterator for response values.
558
+ Drawing response values from the returned Call-iterator may
559
+ raise RpcError indicating termination of the RPC with non-OK
560
+ status.
561
+ client_call_details: A ClientCallDetails object describing the
562
+ outgoing RPC.
563
+ request_iterator: An iterator that yields request values for the RPC.
564
+
565
+ Returns:
566
+ An object that is both a Call for the RPC and an iterator of
567
+ response values. Drawing response values from the returned
568
+ Call-iterator may raise RpcError indicating termination of
569
+ the RPC with non-OK status. This object *should* also fulfill the
570
+ Future interface, though it may not.
571
+ """
572
+ raise NotImplementedError()
573
+
574
+
575
+ ############ Authentication & Authorization Interfaces & Classes #############
576
+
577
+
578
+ class ChannelCredentials(object):
579
+ """An encapsulation of the data required to create a secure Channel.
580
+
581
+ This class has no supported interface - it exists to define the type of its
582
+ instances and its instances exist to be passed to other functions. For
583
+ example, ssl_channel_credentials returns an instance of this class and
584
+ secure_channel requires an instance of this class.
585
+ """
586
+
587
+ def __init__(self, credentials):
588
+ self._credentials = credentials
589
+
590
+
591
+ class CallCredentials(object):
592
+ """An encapsulation of the data required to assert an identity over a call.
593
+
594
+ A CallCredentials has to be used with secure Channel, otherwise the
595
+ metadata will not be transmitted to the server.
596
+
597
+ A CallCredentials may be composed with ChannelCredentials to always assert
598
+ identity for every call over that Channel.
599
+
600
+ This class has no supported interface - it exists to define the type of its
601
+ instances and its instances exist to be passed to other functions.
602
+ """
603
+
604
+ def __init__(self, credentials):
605
+ self._credentials = credentials
606
+
607
+
608
+ class AuthMetadataContext(abc.ABC):
609
+ """Provides information to call credentials metadata plugins.
610
+
611
+ Attributes:
612
+ service_url: A string URL of the service being called into.
613
+ method_name: A string of the fully qualified method name being called.
614
+ """
615
+
616
+
617
+ class AuthMetadataPluginCallback(abc.ABC):
618
+ """Callback object received by a metadata plugin."""
619
+
620
+ def __call__(self, metadata, error):
621
+ """Passes to the gRPC runtime authentication metadata for an RPC.
622
+
623
+ Args:
624
+ metadata: The :term:`metadata` used to construct the CallCredentials.
625
+ error: An Exception to indicate error or None to indicate success.
626
+ """
627
+ raise NotImplementedError()
628
+
629
+
630
+ class AuthMetadataPlugin(abc.ABC):
631
+ """A specification for custom authentication."""
632
+
633
+ def __call__(self, context, callback):
634
+ """Implements authentication by passing metadata to a callback.
635
+
636
+ This method will be invoked asynchronously in a separate thread.
637
+
638
+ Args:
639
+ context: An AuthMetadataContext providing information on the RPC that
640
+ the plugin is being called to authenticate.
641
+ callback: An AuthMetadataPluginCallback to be invoked either
642
+ synchronously or asynchronously.
643
+ """
644
+ raise NotImplementedError()
645
+
646
+
647
+ class ServerCredentials(object):
648
+ """An encapsulation of the data required to open a secure port on a Server.
649
+
650
+ This class has no supported interface - it exists to define the type of its
651
+ instances and its instances exist to be passed to other functions.
652
+ """
653
+
654
+ def __init__(self, credentials):
655
+ self._credentials = credentials
656
+
657
+
658
+ class ServerCertificateConfiguration(object):
659
+ """A certificate configuration for use with an SSL-enabled Server.
660
+
661
+ Instances of this class can be returned in the certificate configuration
662
+ fetching callback.
663
+
664
+ This class has no supported interface -- it exists to define the
665
+ type of its instances and its instances exist to be passed to
666
+ other functions.
667
+ """
668
+
669
+ def __init__(self, certificate_configuration):
670
+ self._certificate_configuration = certificate_configuration
671
+
672
+
673
+ ######################## Multi-Callable Interfaces ###########################
674
+
675
+
676
+ class UnaryUnaryMultiCallable(abc.ABC):
677
+ """Affords invoking a unary-unary RPC from client-side."""
678
+
679
+ @abc.abstractmethod
680
+ def __call__(
681
+ self,
682
+ request,
683
+ timeout=None,
684
+ metadata=None,
685
+ credentials=None,
686
+ wait_for_ready=None,
687
+ compression=None,
688
+ ):
689
+ """Synchronously invokes the underlying RPC.
690
+
691
+ Args:
692
+ request: The request value for the RPC.
693
+ timeout: An optional duration of time in seconds to allow
694
+ for the RPC.
695
+ metadata: Optional :term:`metadata` to be transmitted to the
696
+ service-side of the RPC.
697
+ credentials: An optional CallCredentials for the RPC. Only valid for
698
+ secure Channel.
699
+ wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
700
+ compression: An element of grpc.Compression, e.g.
701
+ grpc.Compression.Gzip.
702
+
703
+ Returns:
704
+ The response value for the RPC.
705
+
706
+ Raises:
707
+ RpcError: Indicating that the RPC terminated with non-OK status. The
708
+ raised RpcError will also be a Call for the RPC affording the RPC's
709
+ metadata, status code, and details.
710
+ """
711
+ raise NotImplementedError()
712
+
713
+ @abc.abstractmethod
714
+ def with_call(
715
+ self,
716
+ request,
717
+ timeout=None,
718
+ metadata=None,
719
+ credentials=None,
720
+ wait_for_ready=None,
721
+ compression=None,
722
+ ):
723
+ """Synchronously invokes the underlying RPC.
724
+
725
+ Args:
726
+ request: The request value for the RPC.
727
+ timeout: An optional durating of time in seconds to allow for
728
+ the RPC.
729
+ metadata: Optional :term:`metadata` to be transmitted to the
730
+ service-side of the RPC.
731
+ credentials: An optional CallCredentials for the RPC. Only valid for
732
+ secure Channel.
733
+ wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
734
+ compression: An element of grpc.Compression, e.g.
735
+ grpc.Compression.Gzip.
736
+
737
+ Returns:
738
+ The response value for the RPC and a Call value for the RPC.
739
+
740
+ Raises:
741
+ RpcError: Indicating that the RPC terminated with non-OK status. The
742
+ raised RpcError will also be a Call for the RPC affording the RPC's
743
+ metadata, status code, and details.
744
+ """
745
+ raise NotImplementedError()
746
+
747
+ @abc.abstractmethod
748
+ def future(
749
+ self,
750
+ request,
751
+ timeout=None,
752
+ metadata=None,
753
+ credentials=None,
754
+ wait_for_ready=None,
755
+ compression=None,
756
+ ):
757
+ """Asynchronously invokes the underlying RPC.
758
+
759
+ Args:
760
+ request: The request value for the RPC.
761
+ timeout: An optional duration of time in seconds to allow for
762
+ the RPC.
763
+ metadata: Optional :term:`metadata` to be transmitted to the
764
+ service-side of the RPC.
765
+ credentials: An optional CallCredentials for the RPC. Only valid for
766
+ secure Channel.
767
+ wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
768
+ compression: An element of grpc.Compression, e.g.
769
+ grpc.Compression.Gzip.
770
+
771
+ Returns:
772
+ An object that is both a Call for the RPC and a Future.
773
+ In the event of RPC completion, the return Call-Future's result
774
+ value will be the response message of the RPC.
775
+ Should the event terminate with non-OK status,
776
+ the returned Call-Future's exception value will be an RpcError.
777
+ """
778
+ raise NotImplementedError()
779
+
780
+
781
+ class UnaryStreamMultiCallable(abc.ABC):
782
+ """Affords invoking a unary-stream RPC from client-side."""
783
+
784
+ @abc.abstractmethod
785
+ def __call__(
786
+ self,
787
+ request,
788
+ timeout=None,
789
+ metadata=None,
790
+ credentials=None,
791
+ wait_for_ready=None,
792
+ compression=None,
793
+ ):
794
+ """Invokes the underlying RPC.
795
+
796
+ Args:
797
+ request: The request value for the RPC.
798
+ timeout: An optional duration of time in seconds to allow for
799
+ the RPC. If None, the timeout is considered infinite.
800
+ metadata: An optional :term:`metadata` to be transmitted to the
801
+ service-side of the RPC.
802
+ credentials: An optional CallCredentials for the RPC. Only valid for
803
+ secure Channel.
804
+ wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
805
+ compression: An element of grpc.Compression, e.g.
806
+ grpc.Compression.Gzip.
807
+
808
+ Returns:
809
+ An object that is a Call for the RPC, an iterator of response
810
+ values, and a Future for the RPC. Drawing response values from the
811
+ returned Call-iterator may raise RpcError indicating termination of
812
+ the RPC with non-OK status.
813
+ """
814
+ raise NotImplementedError()
815
+
816
+
817
+ class StreamUnaryMultiCallable(abc.ABC):
818
+ """Affords invoking a stream-unary RPC from client-side."""
819
+
820
+ @abc.abstractmethod
821
+ def __call__(
822
+ self,
823
+ request_iterator,
824
+ timeout=None,
825
+ metadata=None,
826
+ credentials=None,
827
+ wait_for_ready=None,
828
+ compression=None,
829
+ ):
830
+ """Synchronously invokes the underlying RPC.
831
+
832
+ Args:
833
+ request_iterator: An iterator that yields request values for
834
+ the RPC.
835
+ timeout: An optional duration of time in seconds to allow for
836
+ the RPC. If None, the timeout is considered infinite.
837
+ metadata: Optional :term:`metadata` to be transmitted to the
838
+ service-side of the RPC.
839
+ credentials: An optional CallCredentials for the RPC. Only valid for
840
+ secure Channel.
841
+ wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
842
+ compression: An element of grpc.Compression, e.g.
843
+ grpc.Compression.Gzip.
844
+
845
+ Returns:
846
+ The response value for the RPC.
847
+
848
+ Raises:
849
+ RpcError: Indicating that the RPC terminated with non-OK status. The
850
+ raised RpcError will also implement grpc.Call, affording methods
851
+ such as metadata, code, and details.
852
+ """
853
+ raise NotImplementedError()
854
+
855
+ @abc.abstractmethod
856
+ def with_call(
857
+ self,
858
+ request_iterator,
859
+ timeout=None,
860
+ metadata=None,
861
+ credentials=None,
862
+ wait_for_ready=None,
863
+ compression=None,
864
+ ):
865
+ """Synchronously invokes the underlying RPC on the client.
866
+
867
+ Args:
868
+ request_iterator: An iterator that yields request values for
869
+ the RPC.
870
+ timeout: An optional duration of time in seconds to allow for
871
+ the RPC. If None, the timeout is considered infinite.
872
+ metadata: Optional :term:`metadata` to be transmitted to the
873
+ service-side of the RPC.
874
+ credentials: An optional CallCredentials for the RPC. Only valid for
875
+ secure Channel.
876
+ wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
877
+ compression: An element of grpc.Compression, e.g.
878
+ grpc.Compression.Gzip.
879
+
880
+ Returns:
881
+ The response value for the RPC and a Call object for the RPC.
882
+
883
+ Raises:
884
+ RpcError: Indicating that the RPC terminated with non-OK status. The
885
+ raised RpcError will also be a Call for the RPC affording the RPC's
886
+ metadata, status code, and details.
887
+ """
888
+ raise NotImplementedError()
889
+
890
+ @abc.abstractmethod
891
+ def future(
892
+ self,
893
+ request_iterator,
894
+ timeout=None,
895
+ metadata=None,
896
+ credentials=None,
897
+ wait_for_ready=None,
898
+ compression=None,
899
+ ):
900
+ """Asynchronously invokes the underlying RPC on the client.
901
+
902
+ Args:
903
+ request_iterator: An iterator that yields request values for the RPC.
904
+ timeout: An optional duration of time in seconds to allow for
905
+ the RPC. If None, the timeout is considered infinite.
906
+ metadata: Optional :term:`metadata` to be transmitted to the
907
+ service-side of the RPC.
908
+ credentials: An optional CallCredentials for the RPC. Only valid for
909
+ secure Channel.
910
+ wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
911
+ compression: An element of grpc.Compression, e.g.
912
+ grpc.Compression.Gzip.
913
+
914
+ Returns:
915
+ An object that is both a Call for the RPC and a Future.
916
+ In the event of RPC completion, the return Call-Future's result value
917
+ will be the response message of the RPC. Should the event terminate
918
+ with non-OK status, the returned Call-Future's exception value will
919
+ be an RpcError.
920
+ """
921
+ raise NotImplementedError()
922
+
923
+
924
+ class StreamStreamMultiCallable(abc.ABC):
925
+ """Affords invoking a stream-stream RPC on client-side."""
926
+
927
+ @abc.abstractmethod
928
+ def __call__(
929
+ self,
930
+ request_iterator,
931
+ timeout=None,
932
+ metadata=None,
933
+ credentials=None,
934
+ wait_for_ready=None,
935
+ compression=None,
936
+ ):
937
+ """Invokes the underlying RPC on the client.
938
+
939
+ Args:
940
+ request_iterator: An iterator that yields request values for the RPC.
941
+ timeout: An optional duration of time in seconds to allow for
942
+ the RPC. If not specified, the timeout is considered infinite.
943
+ metadata: Optional :term:`metadata` to be transmitted to the
944
+ service-side of the RPC.
945
+ credentials: An optional CallCredentials for the RPC. Only valid for
946
+ secure Channel.
947
+ wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
948
+ compression: An element of grpc.Compression, e.g.
949
+ grpc.Compression.Gzip.
950
+
951
+ Returns:
952
+ An object that is a Call for the RPC, an iterator of response
953
+ values, and a Future for the RPC. Drawing response values from the
954
+ returned Call-iterator may raise RpcError indicating termination of
955
+ the RPC with non-OK status.
956
+ """
957
+ raise NotImplementedError()
958
+
959
+
960
+ ############################# Channel Interface ##############################
961
+
962
+
963
+ class Channel(abc.ABC):
964
+ """Affords RPC invocation via generic methods on client-side.
965
+
966
+ Channel objects implement the Context Manager type, although they need not
967
+ support being entered and exited multiple times.
968
+ """
969
+
970
+ @abc.abstractmethod
971
+ def subscribe(self, callback, try_to_connect=False):
972
+ """Subscribe to this Channel's connectivity state machine.
973
+
974
+ A Channel may be in any of the states described by ChannelConnectivity.
975
+ This method allows application to monitor the state transitions.
976
+ The typical use case is to debug or gain better visibility into gRPC
977
+ runtime's state.
978
+
979
+ Args:
980
+ callback: A callable to be invoked with ChannelConnectivity argument.
981
+ ChannelConnectivity describes current state of the channel.
982
+ The callable will be invoked immediately upon subscription
983
+ and again for every change to ChannelConnectivity until it
984
+ is unsubscribed or this Channel object goes out of scope.
985
+ try_to_connect: A boolean indicating whether or not this Channel
986
+ should attempt to connect immediately. If set to False, gRPC
987
+ runtime decides when to connect.
988
+ """
989
+ raise NotImplementedError()
990
+
991
+ @abc.abstractmethod
992
+ def unsubscribe(self, callback):
993
+ """Unsubscribes a subscribed callback from this Channel's connectivity.
994
+
995
+ Args:
996
+ callback: A callable previously registered with this Channel from
997
+ having been passed to its "subscribe" method.
998
+ """
999
+ raise NotImplementedError()
1000
+
1001
+ @abc.abstractmethod
1002
+ def unary_unary(
1003
+ self,
1004
+ method,
1005
+ request_serializer=None,
1006
+ response_deserializer=None,
1007
+ _registered_method=False,
1008
+ ):
1009
+ """Creates a UnaryUnaryMultiCallable for a unary-unary method.
1010
+
1011
+ Args:
1012
+ method: The name of the RPC method.
1013
+ request_serializer: Optional :term:`serializer` for serializing the request
1014
+ message. Request goes unserialized in case None is passed.
1015
+ response_deserializer: Optional :term:`deserializer` for deserializing the
1016
+ response message. Response goes undeserialized in case None
1017
+ is passed.
1018
+ _registered_method: Implementation Private. A bool representing whether the method
1019
+ is registered.
1020
+
1021
+ Returns:
1022
+ A UnaryUnaryMultiCallable value for the named unary-unary method.
1023
+ """
1024
+ raise NotImplementedError()
1025
+
1026
+ @abc.abstractmethod
1027
+ def unary_stream(
1028
+ self,
1029
+ method,
1030
+ request_serializer=None,
1031
+ response_deserializer=None,
1032
+ _registered_method=False,
1033
+ ):
1034
+ """Creates a UnaryStreamMultiCallable for a unary-stream method.
1035
+
1036
+ Args:
1037
+ method: The name of the RPC method.
1038
+ request_serializer: Optional :term:`serializer` for serializing the request
1039
+ message. Request goes unserialized in case None is passed.
1040
+ response_deserializer: Optional :term:`deserializer` for deserializing the
1041
+ response message. Response goes undeserialized in case None is
1042
+ passed.
1043
+ _registered_method: Implementation Private. A bool representing whether the method
1044
+ is registered.
1045
+
1046
+ Returns:
1047
+ A UnaryStreamMultiCallable value for the name unary-stream method.
1048
+ """
1049
+ raise NotImplementedError()
1050
+
1051
+ @abc.abstractmethod
1052
+ def stream_unary(
1053
+ self,
1054
+ method,
1055
+ request_serializer=None,
1056
+ response_deserializer=None,
1057
+ _registered_method=False,
1058
+ ):
1059
+ """Creates a StreamUnaryMultiCallable for a stream-unary method.
1060
+
1061
+ Args:
1062
+ method: The name of the RPC method.
1063
+ request_serializer: Optional :term:`serializer` for serializing the request
1064
+ message. Request goes unserialized in case None is passed.
1065
+ response_deserializer: Optional :term:`deserializer` for deserializing the
1066
+ response message. Response goes undeserialized in case None is
1067
+ passed.
1068
+ _registered_method: Implementation Private. A bool representing whether the method
1069
+ is registered.
1070
+
1071
+ Returns:
1072
+ A StreamUnaryMultiCallable value for the named stream-unary method.
1073
+ """
1074
+ raise NotImplementedError()
1075
+
1076
+ @abc.abstractmethod
1077
+ def stream_stream(
1078
+ self,
1079
+ method,
1080
+ request_serializer=None,
1081
+ response_deserializer=None,
1082
+ _registered_method=False,
1083
+ ):
1084
+ """Creates a StreamStreamMultiCallable for a stream-stream method.
1085
+
1086
+ Args:
1087
+ method: The name of the RPC method.
1088
+ request_serializer: Optional :term:`serializer` for serializing the request
1089
+ message. Request goes unserialized in case None is passed.
1090
+ response_deserializer: Optional :term:`deserializer` for deserializing the
1091
+ response message. Response goes undeserialized in case None
1092
+ is passed.
1093
+ _registered_method: Implementation Private. A bool representing whether the method
1094
+ is registered.
1095
+
1096
+ Returns:
1097
+ A StreamStreamMultiCallable value for the named stream-stream method.
1098
+ """
1099
+ raise NotImplementedError()
1100
+
1101
+ @abc.abstractmethod
1102
+ def close(self):
1103
+ """Closes this Channel and releases all resources held by it.
1104
+
1105
+ Closing the Channel will immediately terminate all RPCs active with the
1106
+ Channel and it is not valid to invoke new RPCs with the Channel.
1107
+
1108
+ This method is idempotent.
1109
+ """
1110
+ raise NotImplementedError()
1111
+
1112
+ def __enter__(self):
1113
+ """Enters the runtime context related to the channel object."""
1114
+ raise NotImplementedError()
1115
+
1116
+ def __exit__(self, exc_type, exc_val, exc_tb):
1117
+ """Exits the runtime context related to the channel object."""
1118
+ raise NotImplementedError()
1119
+
1120
+
1121
+ ########################## Service-Side Context ##############################
1122
+
1123
+
1124
+ class ServicerContext(RpcContext, metaclass=abc.ABCMeta):
1125
+ """A context object passed to method implementations."""
1126
+
1127
+ @abc.abstractmethod
1128
+ def invocation_metadata(self):
1129
+ """Accesses the metadata sent by the client.
1130
+
1131
+ Returns:
1132
+ The invocation :term:`metadata`.
1133
+ """
1134
+ raise NotImplementedError()
1135
+
1136
+ @abc.abstractmethod
1137
+ def peer(self):
1138
+ """Identifies the peer that invoked the RPC being serviced.
1139
+
1140
+ Returns:
1141
+ A string identifying the peer that invoked the RPC being serviced.
1142
+ The string format is determined by gRPC runtime.
1143
+ """
1144
+ raise NotImplementedError()
1145
+
1146
+ @abc.abstractmethod
1147
+ def peer_identities(self):
1148
+ """Gets one or more peer identity(s).
1149
+
1150
+ Equivalent to
1151
+ servicer_context.auth_context().get(servicer_context.peer_identity_key())
1152
+
1153
+ Returns:
1154
+ An iterable of the identities, or None if the call is not
1155
+ authenticated. Each identity is returned as a raw bytes type.
1156
+ """
1157
+ raise NotImplementedError()
1158
+
1159
+ @abc.abstractmethod
1160
+ def peer_identity_key(self):
1161
+ """The auth property used to identify the peer.
1162
+
1163
+ For example, "x509_common_name" or "x509_subject_alternative_name" are
1164
+ used to identify an SSL peer.
1165
+
1166
+ Returns:
1167
+ The auth property (string) that indicates the
1168
+ peer identity, or None if the call is not authenticated.
1169
+ """
1170
+ raise NotImplementedError()
1171
+
1172
+ @abc.abstractmethod
1173
+ def auth_context(self):
1174
+ """Gets the auth context for the call.
1175
+
1176
+ Returns:
1177
+ A map of strings to an iterable of bytes for each auth property.
1178
+ """
1179
+ raise NotImplementedError()
1180
+
1181
+ def set_compression(self, compression):
1182
+ """Set the compression algorithm to be used for the entire call.
1183
+
1184
+ Args:
1185
+ compression: An element of grpc.Compression, e.g.
1186
+ grpc.Compression.Gzip.
1187
+ """
1188
+ raise NotImplementedError()
1189
+
1190
+ @abc.abstractmethod
1191
+ def send_initial_metadata(self, initial_metadata):
1192
+ """Sends the initial metadata value to the client.
1193
+
1194
+ This method need not be called by implementations if they have no
1195
+ metadata to add to what the gRPC runtime will transmit.
1196
+
1197
+ Args:
1198
+ initial_metadata: The initial :term:`metadata`.
1199
+ """
1200
+ raise NotImplementedError()
1201
+
1202
+ @abc.abstractmethod
1203
+ def set_trailing_metadata(self, trailing_metadata):
1204
+ """Sets the trailing metadata for the RPC.
1205
+
1206
+ Sets the trailing metadata to be sent upon completion of the RPC.
1207
+
1208
+ If this method is invoked multiple times throughout the lifetime of an
1209
+ RPC, the value supplied in the final invocation will be the value sent
1210
+ over the wire.
1211
+
1212
+ This method need not be called by implementations if they have no
1213
+ metadata to add to what the gRPC runtime will transmit.
1214
+
1215
+ Args:
1216
+ trailing_metadata: The trailing :term:`metadata`.
1217
+ """
1218
+ raise NotImplementedError()
1219
+
1220
+ def trailing_metadata(self):
1221
+ """Access value to be used as trailing metadata upon RPC completion.
1222
+
1223
+ This is an EXPERIMENTAL API.
1224
+
1225
+ Returns:
1226
+ The trailing :term:`metadata` for the RPC.
1227
+ """
1228
+ raise NotImplementedError()
1229
+
1230
+ @abc.abstractmethod
1231
+ def abort(self, code, details):
1232
+ """Raises an exception to terminate the RPC with a non-OK status.
1233
+
1234
+ The code and details passed as arguments will supersede any existing
1235
+ ones.
1236
+
1237
+ Args:
1238
+ code: A StatusCode object to be sent to the client.
1239
+ It must not be StatusCode.OK.
1240
+ details: A UTF-8-encodable string to be sent to the client upon
1241
+ termination of the RPC.
1242
+
1243
+ Raises:
1244
+ Exception: An exception is always raised to signal the abortion the
1245
+ RPC to the gRPC runtime.
1246
+ """
1247
+ raise NotImplementedError()
1248
+
1249
+ @abc.abstractmethod
1250
+ def abort_with_status(self, status):
1251
+ """Raises an exception to terminate the RPC with a non-OK status.
1252
+
1253
+ The status passed as argument will supersede any existing status code,
1254
+ status message and trailing metadata.
1255
+
1256
+ This is an EXPERIMENTAL API.
1257
+
1258
+ Args:
1259
+ status: A grpc.Status object. The status code in it must not be
1260
+ StatusCode.OK.
1261
+
1262
+ Raises:
1263
+ Exception: An exception is always raised to signal the abortion the
1264
+ RPC to the gRPC runtime.
1265
+ """
1266
+ raise NotImplementedError()
1267
+
1268
+ @abc.abstractmethod
1269
+ def set_code(self, code):
1270
+ """Sets the value to be used as status code upon RPC completion.
1271
+
1272
+ This method need not be called by method implementations if they wish
1273
+ the gRPC runtime to determine the status code of the RPC.
1274
+
1275
+ Args:
1276
+ code: A StatusCode object to be sent to the client.
1277
+ """
1278
+ raise NotImplementedError()
1279
+
1280
+ @abc.abstractmethod
1281
+ def set_details(self, details):
1282
+ """Sets the value to be used as detail string upon RPC completion.
1283
+
1284
+ This method need not be called by method implementations if they have
1285
+ no details to transmit.
1286
+
1287
+ Args:
1288
+ details: A UTF-8-encodable string to be sent to the client upon
1289
+ termination of the RPC.
1290
+ """
1291
+ raise NotImplementedError()
1292
+
1293
+ def code(self):
1294
+ """Accesses the value to be used as status code upon RPC completion.
1295
+
1296
+ This is an EXPERIMENTAL API.
1297
+
1298
+ Returns:
1299
+ The StatusCode value for the RPC.
1300
+ """
1301
+ raise NotImplementedError()
1302
+
1303
+ def details(self):
1304
+ """Accesses the value to be used as detail string upon RPC completion.
1305
+
1306
+ This is an EXPERIMENTAL API.
1307
+
1308
+ Returns:
1309
+ The details string of the RPC.
1310
+ """
1311
+ raise NotImplementedError()
1312
+
1313
+ def disable_next_message_compression(self):
1314
+ """Disables compression for the next response message.
1315
+
1316
+ This method will override any compression configuration set during
1317
+ server creation or set on the call.
1318
+ """
1319
+ raise NotImplementedError()
1320
+
1321
+
1322
+ ##################### Service-Side Handler Interfaces ########################
1323
+
1324
+
1325
+ class RpcMethodHandler(abc.ABC):
1326
+ """An implementation of a single RPC method.
1327
+
1328
+ Attributes:
1329
+ request_streaming: Whether the RPC supports exactly one request message
1330
+ or any arbitrary number of request messages.
1331
+ response_streaming: Whether the RPC supports exactly one response message
1332
+ or any arbitrary number of response messages.
1333
+ request_deserializer: A callable :term:`deserializer` that accepts a byte string and
1334
+ returns an object suitable to be passed to this object's business
1335
+ logic, or None to indicate that this object's business logic should be
1336
+ passed the raw request bytes.
1337
+ response_serializer: A callable :term:`serializer` that accepts an object produced
1338
+ by this object's business logic and returns a byte string, or None to
1339
+ indicate that the byte strings produced by this object's business logic
1340
+ should be transmitted on the wire as they are.
1341
+ unary_unary: This object's application-specific business logic as a
1342
+ callable value that takes a request value and a ServicerContext object
1343
+ and returns a response value. Only non-None if both request_streaming
1344
+ and response_streaming are False.
1345
+ unary_stream: This object's application-specific business logic as a
1346
+ callable value that takes a request value and a ServicerContext object
1347
+ and returns an iterator of response values. Only non-None if
1348
+ request_streaming is False and response_streaming is True.
1349
+ stream_unary: This object's application-specific business logic as a
1350
+ callable value that takes an iterator of request values and a
1351
+ ServicerContext object and returns a response value. Only non-None if
1352
+ request_streaming is True and response_streaming is False.
1353
+ stream_stream: This object's application-specific business logic as a
1354
+ callable value that takes an iterator of request values and a
1355
+ ServicerContext object and returns an iterator of response values.
1356
+ Only non-None if request_streaming and response_streaming are both
1357
+ True.
1358
+ """
1359
+
1360
+
1361
+ class HandlerCallDetails(abc.ABC):
1362
+ """Describes an RPC that has just arrived for service.
1363
+
1364
+ Attributes:
1365
+ method: The method name of the RPC.
1366
+ invocation_metadata: The :term:`metadata` sent by the client.
1367
+ """
1368
+
1369
+
1370
+ class GenericRpcHandler(abc.ABC):
1371
+ """An implementation of arbitrarily many RPC methods."""
1372
+
1373
+ @abc.abstractmethod
1374
+ def service(self, handler_call_details):
1375
+ """Returns the handler for servicing the RPC.
1376
+
1377
+ Args:
1378
+ handler_call_details: A HandlerCallDetails describing the RPC.
1379
+
1380
+ Returns:
1381
+ An RpcMethodHandler with which the RPC may be serviced if the
1382
+ implementation chooses to service this RPC, or None otherwise.
1383
+ """
1384
+ raise NotImplementedError()
1385
+
1386
+
1387
+ class ServiceRpcHandler(GenericRpcHandler, metaclass=abc.ABCMeta):
1388
+ """An implementation of RPC methods belonging to a service.
1389
+
1390
+ A service handles RPC methods with structured names of the form
1391
+ '/Service.Name/Service.Method', where 'Service.Name' is the value
1392
+ returned by service_name(), and 'Service.Method' is the method
1393
+ name. A service can have multiple method names, but only a single
1394
+ service name.
1395
+ """
1396
+
1397
+ @abc.abstractmethod
1398
+ def service_name(self):
1399
+ """Returns this service's name.
1400
+
1401
+ Returns:
1402
+ The service name.
1403
+ """
1404
+ raise NotImplementedError()
1405
+
1406
+
1407
+ #################### Service-Side Interceptor Interfaces #####################
1408
+
1409
+
1410
+ class ServerInterceptor(abc.ABC):
1411
+ """Affords intercepting incoming RPCs on the service-side."""
1412
+
1413
+ @abc.abstractmethod
1414
+ def intercept_service(self, continuation, handler_call_details):
1415
+ """Intercepts incoming RPCs before handing them over to a handler.
1416
+
1417
+ State can be passed from an interceptor to downstream interceptors
1418
+ via contextvars. The first interceptor is called from an empty
1419
+ contextvars.Context, and the same Context is used for downstream
1420
+ interceptors and for the final handler call. Note that there are no
1421
+ guarantees that interceptors and handlers will be called from the
1422
+ same thread.
1423
+
1424
+ Args:
1425
+ continuation: A function that takes a HandlerCallDetails and
1426
+ proceeds to invoke the next interceptor in the chain, if any,
1427
+ or the RPC handler lookup logic, with the call details passed
1428
+ as an argument, and returns an RpcMethodHandler instance if
1429
+ the RPC is considered serviced, or None otherwise.
1430
+ handler_call_details: A HandlerCallDetails describing the RPC.
1431
+
1432
+ Returns:
1433
+ An RpcMethodHandler with which the RPC may be serviced if the
1434
+ interceptor chooses to service this RPC, or None otherwise.
1435
+ """
1436
+ raise NotImplementedError()
1437
+
1438
+
1439
+ ############################# Server Interface ###############################
1440
+
1441
+
1442
+ class Server(abc.ABC):
1443
+ """Services RPCs."""
1444
+
1445
+ @abc.abstractmethod
1446
+ def add_generic_rpc_handlers(self, generic_rpc_handlers):
1447
+ """Registers GenericRpcHandlers with this Server.
1448
+
1449
+ This method is only safe to call before the server is started.
1450
+
1451
+ Args:
1452
+ generic_rpc_handlers: An iterable of GenericRpcHandlers that will be
1453
+ used to service RPCs.
1454
+ """
1455
+ raise NotImplementedError()
1456
+
1457
+ def add_registered_method_handlers( # noqa: B027
1458
+ self, service_name, method_handlers
1459
+ ):
1460
+ """Registers GenericRpcHandlers with this Server.
1461
+
1462
+ This method is only safe to call before the server is started.
1463
+
1464
+ If the same method have both generic and registered handler,
1465
+ registered handler will take precedence.
1466
+
1467
+ Args:
1468
+ service_name: The service name.
1469
+ method_handlers: A dictionary that maps method names to corresponding
1470
+ RpcMethodHandler.
1471
+ """
1472
+
1473
+ @abc.abstractmethod
1474
+ def add_insecure_port(self, address):
1475
+ """Opens an insecure port for accepting RPCs.
1476
+
1477
+ This method may only be called before starting the server.
1478
+
1479
+ Args:
1480
+ address: The address for which to open a port. If the port is 0,
1481
+ or not specified in the address, then gRPC runtime will choose a port.
1482
+
1483
+ Returns:
1484
+ An integer port on which server will accept RPC requests.
1485
+ """
1486
+ raise NotImplementedError()
1487
+
1488
+ @abc.abstractmethod
1489
+ def add_secure_port(self, address, server_credentials):
1490
+ """Opens a secure port for accepting RPCs.
1491
+
1492
+ This method may only be called before starting the server.
1493
+
1494
+ Args:
1495
+ address: The address for which to open a port.
1496
+ if the port is 0, or not specified in the address, then gRPC
1497
+ runtime will choose a port.
1498
+ server_credentials: A ServerCredentials object.
1499
+
1500
+ Returns:
1501
+ An integer port on which server will accept RPC requests.
1502
+ """
1503
+ raise NotImplementedError()
1504
+
1505
+ @abc.abstractmethod
1506
+ def start(self):
1507
+ """Starts this Server.
1508
+
1509
+ This method may only be called once. (i.e. it is not idempotent).
1510
+ """
1511
+ raise NotImplementedError()
1512
+
1513
+ @abc.abstractmethod
1514
+ def stop(self, grace):
1515
+ """Stops this Server.
1516
+
1517
+ This method immediately stop service of new RPCs in all cases.
1518
+
1519
+ If a grace period is specified, this method waits until all active
1520
+ RPCs are finished or until the grace period is reached. RPCs that haven't
1521
+ been terminated within the grace period are aborted.
1522
+ If a grace period is not specified (by passing None for `grace`),
1523
+ all existing RPCs are aborted immediately and this method
1524
+ blocks until the last RPC handler terminates.
1525
+
1526
+ This method is idempotent and may be called at any time.
1527
+ Passing a smaller grace value in a subsequent call will have
1528
+ the effect of stopping the Server sooner (passing None will
1529
+ have the effect of stopping the server immediately). Passing
1530
+ a larger grace value in a subsequent call *will not* have the
1531
+ effect of stopping the server later (i.e. the most restrictive
1532
+ grace value is used).
1533
+
1534
+ Args:
1535
+ grace: A duration of time in seconds or None.
1536
+
1537
+ Returns:
1538
+ A threading.Event that will be set when this Server has completely
1539
+ stopped, i.e. when running RPCs either complete or are aborted and
1540
+ all handlers have terminated.
1541
+ """
1542
+ raise NotImplementedError()
1543
+
1544
+ def wait_for_termination(self, timeout=None):
1545
+ """Block current thread until the server stops.
1546
+
1547
+ This is an EXPERIMENTAL API.
1548
+
1549
+ The wait will not consume computational resources during blocking, and
1550
+ it will block until one of the two following conditions are met:
1551
+
1552
+ 1) The server is stopped or terminated;
1553
+ 2) A timeout occurs if timeout is not `None`.
1554
+
1555
+ The timeout argument works in the same way as `threading.Event.wait()`.
1556
+ https://docs.python.org/3/library/threading.html#threading.Event.wait
1557
+
1558
+ Args:
1559
+ timeout: A floating point number specifying a timeout for the
1560
+ operation in seconds.
1561
+
1562
+ Returns:
1563
+ A bool indicates if the operation times out.
1564
+ """
1565
+ raise NotImplementedError()
1566
+
1567
+
1568
+ ################################# Functions ################################
1569
+
1570
+
1571
+ def unary_unary_rpc_method_handler(
1572
+ behavior, request_deserializer=None, response_serializer=None
1573
+ ):
1574
+ """Creates an RpcMethodHandler for a unary-unary RPC method.
1575
+
1576
+ Args:
1577
+ behavior: The implementation of an RPC that accepts one request
1578
+ and returns one response.
1579
+ request_deserializer: An optional :term:`deserializer` for request deserialization.
1580
+ response_serializer: An optional :term:`serializer` for response serialization.
1581
+
1582
+ Returns:
1583
+ An RpcMethodHandler object that is typically used by grpc.Server.
1584
+ """
1585
+ from grpc import _utilities # pylint: disable=cyclic-import
1586
+
1587
+ return _utilities.RpcMethodHandler(
1588
+ False,
1589
+ False,
1590
+ request_deserializer,
1591
+ response_serializer,
1592
+ behavior,
1593
+ None,
1594
+ None,
1595
+ None,
1596
+ )
1597
+
1598
+
1599
+ def unary_stream_rpc_method_handler(
1600
+ behavior, request_deserializer=None, response_serializer=None
1601
+ ):
1602
+ """Creates an RpcMethodHandler for a unary-stream RPC method.
1603
+
1604
+ Args:
1605
+ behavior: The implementation of an RPC that accepts one request
1606
+ and returns an iterator of response values.
1607
+ request_deserializer: An optional :term:`deserializer` for request deserialization.
1608
+ response_serializer: An optional :term:`serializer` for response serialization.
1609
+
1610
+ Returns:
1611
+ An RpcMethodHandler object that is typically used by grpc.Server.
1612
+ """
1613
+ from grpc import _utilities # pylint: disable=cyclic-import
1614
+
1615
+ return _utilities.RpcMethodHandler(
1616
+ False,
1617
+ True,
1618
+ request_deserializer,
1619
+ response_serializer,
1620
+ None,
1621
+ behavior,
1622
+ None,
1623
+ None,
1624
+ )
1625
+
1626
+
1627
+ def stream_unary_rpc_method_handler(
1628
+ behavior, request_deserializer=None, response_serializer=None
1629
+ ):
1630
+ """Creates an RpcMethodHandler for a stream-unary RPC method.
1631
+
1632
+ Args:
1633
+ behavior: The implementation of an RPC that accepts an iterator of
1634
+ request values and returns a single response value.
1635
+ request_deserializer: An optional :term:`deserializer` for request deserialization.
1636
+ response_serializer: An optional :term:`serializer` for response serialization.
1637
+
1638
+ Returns:
1639
+ An RpcMethodHandler object that is typically used by grpc.Server.
1640
+ """
1641
+ from grpc import _utilities # pylint: disable=cyclic-import
1642
+
1643
+ return _utilities.RpcMethodHandler(
1644
+ True,
1645
+ False,
1646
+ request_deserializer,
1647
+ response_serializer,
1648
+ None,
1649
+ None,
1650
+ behavior,
1651
+ None,
1652
+ )
1653
+
1654
+
1655
+ def stream_stream_rpc_method_handler(
1656
+ behavior, request_deserializer=None, response_serializer=None
1657
+ ):
1658
+ """Creates an RpcMethodHandler for a stream-stream RPC method.
1659
+
1660
+ Args:
1661
+ behavior: The implementation of an RPC that accepts an iterator of
1662
+ request values and returns an iterator of response values.
1663
+ request_deserializer: An optional :term:`deserializer` for request deserialization.
1664
+ response_serializer: An optional :term:`serializer` for response serialization.
1665
+
1666
+ Returns:
1667
+ An RpcMethodHandler object that is typically used by grpc.Server.
1668
+ """
1669
+ from grpc import _utilities # pylint: disable=cyclic-import
1670
+
1671
+ return _utilities.RpcMethodHandler(
1672
+ True,
1673
+ True,
1674
+ request_deserializer,
1675
+ response_serializer,
1676
+ None,
1677
+ None,
1678
+ None,
1679
+ behavior,
1680
+ )
1681
+
1682
+
1683
+ def method_handlers_generic_handler(service, method_handlers):
1684
+ """Creates a GenericRpcHandler from RpcMethodHandlers.
1685
+
1686
+ Args:
1687
+ service: The name of the service that is implemented by the
1688
+ method_handlers.
1689
+ method_handlers: A dictionary that maps method names to corresponding
1690
+ RpcMethodHandler.
1691
+
1692
+ Returns:
1693
+ A GenericRpcHandler. This is typically added to the grpc.Server object
1694
+ with add_generic_rpc_handlers() before starting the server.
1695
+ """
1696
+ from grpc import _utilities # pylint: disable=cyclic-import
1697
+
1698
+ return _utilities.DictionaryGenericHandler(service, method_handlers)
1699
+
1700
+
1701
+ def ssl_channel_credentials(
1702
+ root_certificates=None, private_key=None, certificate_chain=None
1703
+ ):
1704
+ """Creates a ChannelCredentials for use with an SSL-enabled Channel.
1705
+
1706
+ Args:
1707
+ root_certificates: The PEM-encoded root certificates as a byte string,
1708
+ or None to retrieve them from a default location chosen by gRPC
1709
+ runtime.
1710
+ private_key: The PEM-encoded private key as a byte string, or None if no
1711
+ private key should be used.
1712
+ certificate_chain: The PEM-encoded certificate chain as a byte string
1713
+ to use or None if no certificate chain should be used.
1714
+
1715
+ Returns:
1716
+ A ChannelCredentials for use with an SSL-enabled Channel.
1717
+ """
1718
+ return ChannelCredentials(
1719
+ _cygrpc.SSLChannelCredentials(
1720
+ root_certificates, private_key, certificate_chain
1721
+ )
1722
+ )
1723
+
1724
+
1725
+ def xds_channel_credentials(fallback_credentials=None):
1726
+ """Creates a ChannelCredentials for use with xDS. This is an EXPERIMENTAL
1727
+ API.
1728
+
1729
+ Args:
1730
+ fallback_credentials: Credentials to use in case it is not possible to
1731
+ establish a secure connection via xDS. If no fallback_credentials
1732
+ argument is supplied, a default SSLChannelCredentials is used.
1733
+ """
1734
+ fallback_credentials = (
1735
+ ssl_channel_credentials()
1736
+ if fallback_credentials is None
1737
+ else fallback_credentials
1738
+ )
1739
+ return ChannelCredentials(
1740
+ _cygrpc.XDSChannelCredentials(fallback_credentials._credentials)
1741
+ )
1742
+
1743
+
1744
+ def metadata_call_credentials(metadata_plugin, name=None):
1745
+ """Construct CallCredentials from an AuthMetadataPlugin.
1746
+
1747
+ Args:
1748
+ metadata_plugin: An AuthMetadataPlugin to use for authentication.
1749
+ name: An optional name for the plugin.
1750
+
1751
+ Returns:
1752
+ A CallCredentials.
1753
+ """
1754
+ from grpc import _plugin_wrapping # pylint: disable=cyclic-import
1755
+
1756
+ return _plugin_wrapping.metadata_plugin_call_credentials(
1757
+ metadata_plugin, name
1758
+ )
1759
+
1760
+
1761
+ def access_token_call_credentials(access_token):
1762
+ """Construct CallCredentials from an access token.
1763
+
1764
+ Args:
1765
+ access_token: A string to place directly in the http request
1766
+ authorization header, for example
1767
+ "authorization: Bearer <access_token>".
1768
+
1769
+ Returns:
1770
+ A CallCredentials.
1771
+ """
1772
+ from grpc import _auth # pylint: disable=cyclic-import
1773
+ from grpc import _plugin_wrapping # pylint: disable=cyclic-import
1774
+
1775
+ return _plugin_wrapping.metadata_plugin_call_credentials(
1776
+ _auth.AccessTokenAuthMetadataPlugin(access_token), None
1777
+ )
1778
+
1779
+
1780
+ def composite_call_credentials(*call_credentials):
1781
+ """Compose multiple CallCredentials to make a new CallCredentials.
1782
+
1783
+ Args:
1784
+ *call_credentials: At least two CallCredentials objects.
1785
+
1786
+ Returns:
1787
+ A CallCredentials object composed of the given CallCredentials objects.
1788
+ """
1789
+ return CallCredentials(
1790
+ _cygrpc.CompositeCallCredentials(
1791
+ tuple(
1792
+ single_call_credentials._credentials
1793
+ for single_call_credentials in call_credentials
1794
+ )
1795
+ )
1796
+ )
1797
+
1798
+
1799
+ def composite_channel_credentials(channel_credentials, *call_credentials):
1800
+ """Compose a ChannelCredentials and one or more CallCredentials objects.
1801
+
1802
+ Args:
1803
+ channel_credentials: A ChannelCredentials object.
1804
+ *call_credentials: One or more CallCredentials objects.
1805
+
1806
+ Returns:
1807
+ A ChannelCredentials composed of the given ChannelCredentials and
1808
+ CallCredentials objects.
1809
+ """
1810
+ return ChannelCredentials(
1811
+ _cygrpc.CompositeChannelCredentials(
1812
+ tuple(
1813
+ single_call_credentials._credentials
1814
+ for single_call_credentials in call_credentials
1815
+ ),
1816
+ channel_credentials._credentials,
1817
+ )
1818
+ )
1819
+
1820
+
1821
+ def ssl_server_credentials(
1822
+ private_key_certificate_chain_pairs,
1823
+ root_certificates=None,
1824
+ require_client_auth=False,
1825
+ ):
1826
+ """Creates a ServerCredentials for use with an SSL-enabled Server.
1827
+
1828
+ Args:
1829
+ private_key_certificate_chain_pairs: A list of pairs of the form
1830
+ [PEM-encoded private key, PEM-encoded certificate chain].
1831
+ root_certificates: An optional byte string of PEM-encoded client root
1832
+ certificates that the server will use to verify client authentication.
1833
+ If omitted, require_client_auth must also be False.
1834
+ require_client_auth: A boolean indicating whether or not to require
1835
+ clients to be authenticated. May only be True if root_certificates
1836
+ is not None.
1837
+
1838
+ Returns:
1839
+ A ServerCredentials for use with an SSL-enabled Server. Typically, this
1840
+ object is an argument to add_secure_port() method during server setup.
1841
+ """
1842
+ if not private_key_certificate_chain_pairs:
1843
+ error_msg = (
1844
+ "At least one private key-certificate chain pair is required!"
1845
+ )
1846
+ raise ValueError(error_msg)
1847
+ if require_client_auth and root_certificates is None:
1848
+ error_msg = "Illegal to require client auth without providing root certificates!"
1849
+ raise ValueError(error_msg)
1850
+ return ServerCredentials(
1851
+ _cygrpc.server_credentials_ssl(
1852
+ root_certificates,
1853
+ [
1854
+ _cygrpc.SslPemKeyCertPair(key, pem)
1855
+ for key, pem in private_key_certificate_chain_pairs
1856
+ ],
1857
+ require_client_auth,
1858
+ )
1859
+ )
1860
+
1861
+
1862
+ def xds_server_credentials(fallback_credentials):
1863
+ """Creates a ServerCredentials for use with xDS. This is an EXPERIMENTAL
1864
+ API.
1865
+
1866
+ Args:
1867
+ fallback_credentials: Credentials to use in case it is not possible to
1868
+ establish a secure connection via xDS. No default value is provided.
1869
+ """
1870
+ return ServerCredentials(
1871
+ _cygrpc.xds_server_credentials(fallback_credentials._credentials)
1872
+ )
1873
+
1874
+
1875
+ def insecure_server_credentials():
1876
+ """Creates a credentials object directing the server to use no credentials.
1877
+ This is an EXPERIMENTAL API.
1878
+
1879
+ This object cannot be used directly in a call to `add_secure_port`.
1880
+ Instead, it should be used to construct other credentials objects, e.g.
1881
+ with xds_server_credentials.
1882
+ """
1883
+ return ServerCredentials(_cygrpc.insecure_server_credentials())
1884
+
1885
+
1886
+ def ssl_server_certificate_configuration(
1887
+ private_key_certificate_chain_pairs, root_certificates=None
1888
+ ):
1889
+ """Creates a ServerCertificateConfiguration for use with a Server.
1890
+
1891
+ Args:
1892
+ private_key_certificate_chain_pairs: A collection of pairs of
1893
+ the form [PEM-encoded private key, PEM-encoded certificate
1894
+ chain].
1895
+ root_certificates: An optional byte string of PEM-encoded client root
1896
+ certificates that the server will use to verify client authentication.
1897
+
1898
+ Returns:
1899
+ A ServerCertificateConfiguration that can be returned in the certificate
1900
+ configuration fetching callback.
1901
+ """
1902
+ if private_key_certificate_chain_pairs:
1903
+ return ServerCertificateConfiguration(
1904
+ _cygrpc.server_certificate_config_ssl(
1905
+ root_certificates,
1906
+ [
1907
+ _cygrpc.SslPemKeyCertPair(key, pem)
1908
+ for key, pem in private_key_certificate_chain_pairs
1909
+ ],
1910
+ )
1911
+ )
1912
+ error_msg = "At least one private key-certificate chain pair is required!"
1913
+ raise ValueError(error_msg)
1914
+
1915
+
1916
+ def dynamic_ssl_server_credentials(
1917
+ initial_certificate_configuration,
1918
+ certificate_configuration_fetcher,
1919
+ require_client_authentication=False,
1920
+ ):
1921
+ """Creates a ServerCredentials for use with an SSL-enabled Server.
1922
+
1923
+ Args:
1924
+ initial_certificate_configuration (ServerCertificateConfiguration): The
1925
+ certificate configuration with which the server will be initialized.
1926
+ certificate_configuration_fetcher (callable): A callable that takes no
1927
+ arguments and should return a ServerCertificateConfiguration to
1928
+ replace the server's current certificate, or None for no change
1929
+ (i.e., the server will continue its current certificate
1930
+ config). The library will call this callback on *every* new
1931
+ client connection before starting the TLS handshake with the
1932
+ client, thus allowing the user application to optionally
1933
+ return a new ServerCertificateConfiguration that the server will then
1934
+ use for the handshake.
1935
+ require_client_authentication: A boolean indicating whether or not to
1936
+ require clients to be authenticated.
1937
+
1938
+ Returns:
1939
+ A ServerCredentials.
1940
+ """
1941
+ return ServerCredentials(
1942
+ _cygrpc.server_credentials_ssl_dynamic_cert_config(
1943
+ initial_certificate_configuration,
1944
+ certificate_configuration_fetcher,
1945
+ require_client_authentication,
1946
+ )
1947
+ )
1948
+
1949
+
1950
+ @enum.unique
1951
+ class LocalConnectionType(enum.Enum):
1952
+ """Types of local connection for local credential creation.
1953
+
1954
+ Attributes:
1955
+ UDS: Unix domain socket connections
1956
+ LOCAL_TCP: Local TCP connections.
1957
+ """
1958
+
1959
+ UDS = _cygrpc.LocalConnectionType.uds
1960
+ LOCAL_TCP = _cygrpc.LocalConnectionType.local_tcp
1961
+
1962
+
1963
+ def local_channel_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
1964
+ """Creates a local ChannelCredentials used for local connections.
1965
+
1966
+ This is an EXPERIMENTAL API.
1967
+
1968
+ Local credentials are used by local TCP endpoints (e.g. localhost:10000)
1969
+ also UDS connections.
1970
+
1971
+ The connections created by local channel credentials are not
1972
+ encrypted, but will be checked if they are local or not.
1973
+ The UDS connections are considered secure by providing peer authentication
1974
+ and data confidentiality while TCP connections are considered insecure.
1975
+
1976
+ It is allowed to transmit call credentials over connections created by
1977
+ local channel credentials.
1978
+
1979
+ Local channel credentials are useful for 1) eliminating insecure_channel usage;
1980
+ 2) enable unit testing for call credentials without setting up secrets.
1981
+
1982
+ Args:
1983
+ local_connect_type: Local connection type (either
1984
+ grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
1985
+
1986
+ Returns:
1987
+ A ChannelCredentials for use with a local Channel
1988
+ """
1989
+ return ChannelCredentials(
1990
+ _cygrpc.channel_credentials_local(local_connect_type.value)
1991
+ )
1992
+
1993
+
1994
+ def local_server_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
1995
+ """Creates a local ServerCredentials used for local connections.
1996
+
1997
+ This is an EXPERIMENTAL API.
1998
+
1999
+ Local credentials are used by local TCP endpoints (e.g. localhost:10000)
2000
+ also UDS connections.
2001
+
2002
+ The connections created by local server credentials are not
2003
+ encrypted, but will be checked if they are local or not.
2004
+ The UDS connections are considered secure by providing peer authentication
2005
+ and data confidentiality while TCP connections are considered insecure.
2006
+
2007
+ It is allowed to transmit call credentials over connections created by local
2008
+ server credentials.
2009
+
2010
+ Local server credentials are useful for 1) eliminating insecure_channel usage;
2011
+ 2) enable unit testing for call credentials without setting up secrets.
2012
+
2013
+ Args:
2014
+ local_connect_type: Local connection type (either
2015
+ grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
2016
+
2017
+ Returns:
2018
+ A ServerCredentials for use with a local Server
2019
+ """
2020
+ return ServerCredentials(
2021
+ _cygrpc.server_credentials_local(local_connect_type.value)
2022
+ )
2023
+
2024
+
2025
+ def alts_channel_credentials(service_accounts=None):
2026
+ """Creates a ChannelCredentials for use with an ALTS-enabled Channel.
2027
+
2028
+ This is an EXPERIMENTAL API.
2029
+ ALTS credentials API can only be used in GCP environment as it relies on
2030
+ handshaker service being available. For more info about ALTS see
2031
+ https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
2032
+
2033
+ Args:
2034
+ service_accounts: A list of server identities accepted by the client.
2035
+ If target service accounts are provided and none of them matches the
2036
+ peer identity of the server, handshake will fail. The arg can be empty
2037
+ if the client does not have any information about trusted server
2038
+ identity.
2039
+
2040
+ Returns:
2041
+ A ChannelCredentials for use with an ALTS-enabled Channel
2042
+ """
2043
+ return ChannelCredentials(
2044
+ _cygrpc.channel_credentials_alts(service_accounts or [])
2045
+ )
2046
+
2047
+
2048
+ def alts_server_credentials():
2049
+ """Creates a ServerCredentials for use with an ALTS-enabled connection.
2050
+
2051
+ This is an EXPERIMENTAL API.
2052
+ ALTS credentials API can only be used in GCP environment as it relies on
2053
+ handshaker service being available. For more info about ALTS see
2054
+ https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
2055
+
2056
+ Returns:
2057
+ A ServerCredentials for use with an ALTS-enabled Server
2058
+ """
2059
+ return ServerCredentials(_cygrpc.server_credentials_alts())
2060
+
2061
+
2062
+ def compute_engine_channel_credentials(call_credentials):
2063
+ """Creates a compute engine channel credential.
2064
+
2065
+ This credential can only be used in a GCP environment as it relies on
2066
+ a handshaker service. For more info about ALTS, see
2067
+ https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
2068
+
2069
+ This channel credential is expected to be used as part of a composite
2070
+ credential in conjunction with a call credentials that authenticates the
2071
+ VM's default service account. If used with any other sort of call
2072
+ credential, the connection may suddenly and unexpectedly begin failing RPCs.
2073
+ """
2074
+ return ChannelCredentials(
2075
+ _cygrpc.channel_credentials_compute_engine(
2076
+ call_credentials._credentials
2077
+ )
2078
+ )
2079
+
2080
+
2081
+ def channel_ready_future(channel):
2082
+ """Creates a Future that tracks when a Channel is ready.
2083
+
2084
+ Cancelling the Future does not affect the channel's state machine.
2085
+ It merely decouples the Future from channel state machine.
2086
+
2087
+ Args:
2088
+ channel: A Channel object.
2089
+
2090
+ Returns:
2091
+ A Future object that matures when the channel connectivity is
2092
+ ChannelConnectivity.READY.
2093
+ """
2094
+ from grpc import _utilities # pylint: disable=cyclic-import
2095
+
2096
+ return _utilities.channel_ready_future(channel)
2097
+
2098
+
2099
+ def insecure_channel(target, options=None, compression=None):
2100
+ """Creates an insecure Channel to a server.
2101
+
2102
+ The returned Channel is thread-safe.
2103
+
2104
+ Args:
2105
+ target: The server address
2106
+ options: An optional list of key-value pairs (:term:`channel_arguments`
2107
+ in gRPC Core runtime) to configure the channel.
2108
+ compression: An optional value indicating the compression method to be
2109
+ used over the lifetime of the channel.
2110
+
2111
+ Returns:
2112
+ A Channel.
2113
+ """
2114
+ from grpc import _channel # pylint: disable=cyclic-import
2115
+
2116
+ return _channel.Channel(
2117
+ target, () if options is None else options, None, compression
2118
+ )
2119
+
2120
+
2121
+ def secure_channel(target, credentials, options=None, compression=None):
2122
+ """Creates a secure Channel to a server.
2123
+
2124
+ The returned Channel is thread-safe.
2125
+
2126
+ Args:
2127
+ target: The server address.
2128
+ credentials: A ChannelCredentials instance.
2129
+ options: An optional list of key-value pairs (:term:`channel_arguments`
2130
+ in gRPC Core runtime) to configure the channel.
2131
+ compression: An optional value indicating the compression method to be
2132
+ used over the lifetime of the channel.
2133
+
2134
+ Returns:
2135
+ A Channel.
2136
+ """
2137
+ from grpc import _channel # pylint: disable=cyclic-import
2138
+ from grpc.experimental import _insecure_channel_credentials
2139
+
2140
+ if credentials._credentials is _insecure_channel_credentials:
2141
+ raise ValueError(
2142
+ "secure_channel cannot be called with insecure credentials."
2143
+ + " Call insecure_channel instead."
2144
+ )
2145
+ return _channel.Channel(
2146
+ target,
2147
+ () if options is None else options,
2148
+ credentials._credentials,
2149
+ compression,
2150
+ )
2151
+
2152
+
2153
+ def intercept_channel(channel, *interceptors):
2154
+ """Intercepts a channel through a set of interceptors.
2155
+
2156
+ Args:
2157
+ channel: A Channel.
2158
+ interceptors: Zero or more objects of type
2159
+ UnaryUnaryClientInterceptor,
2160
+ UnaryStreamClientInterceptor,
2161
+ StreamUnaryClientInterceptor, or
2162
+ StreamStreamClientInterceptor.
2163
+ Interceptors are given control in the order they are listed.
2164
+
2165
+ Returns:
2166
+ A Channel that intercepts each invocation via the provided interceptors.
2167
+
2168
+ Raises:
2169
+ TypeError: If interceptor does not derive from any of
2170
+ UnaryUnaryClientInterceptor,
2171
+ UnaryStreamClientInterceptor,
2172
+ StreamUnaryClientInterceptor, or
2173
+ StreamStreamClientInterceptor.
2174
+ """
2175
+ from grpc import _interceptor # pylint: disable=cyclic-import
2176
+
2177
+ return _interceptor.intercept_channel(channel, *interceptors)
2178
+
2179
+
2180
+ def server(
2181
+ thread_pool,
2182
+ handlers=None,
2183
+ interceptors=None,
2184
+ options=None,
2185
+ maximum_concurrent_rpcs=None,
2186
+ compression=None,
2187
+ xds=False,
2188
+ ):
2189
+ """Creates a Server with which RPCs can be serviced.
2190
+
2191
+ Args:
2192
+ thread_pool: A futures.ThreadPoolExecutor to be used by the Server
2193
+ to execute RPC handlers.
2194
+ handlers: An optional list of GenericRpcHandlers used for executing RPCs.
2195
+ More handlers may be added by calling add_generic_rpc_handlers any time
2196
+ before the server is started.
2197
+ interceptors: An optional list of ServerInterceptor objects that observe
2198
+ and optionally manipulate the incoming RPCs before handing them over to
2199
+ handlers. The interceptors are given control in the order they are
2200
+ specified. This is an EXPERIMENTAL API.
2201
+ options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC runtime)
2202
+ to configure the channel.
2203
+ maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server
2204
+ will service before returning RESOURCE_EXHAUSTED status, or None to
2205
+ indicate no limit.
2206
+ compression: An element of grpc.Compression, e.g.
2207
+ grpc.Compression.Gzip. This compression algorithm will be used for the
2208
+ lifetime of the server unless overridden.
2209
+ xds: If set to true, retrieves server configuration via xDS. This is an
2210
+ EXPERIMENTAL option.
2211
+
2212
+ Returns:
2213
+ A Server object.
2214
+ """
2215
+ from grpc import _server # pylint: disable=cyclic-import
2216
+
2217
+ return _server.create_server(
2218
+ thread_pool,
2219
+ () if handlers is None else handlers,
2220
+ () if interceptors is None else interceptors,
2221
+ () if options is None else options,
2222
+ maximum_concurrent_rpcs,
2223
+ compression,
2224
+ xds,
2225
+ )
2226
+
2227
+
2228
+ @contextlib.contextmanager
2229
+ def _create_servicer_context(rpc_event, state, request_deserializer):
2230
+ from grpc import _server # pylint: disable=cyclic-import
2231
+
2232
+ context = _server._Context(rpc_event, state, request_deserializer)
2233
+ yield context
2234
+ context._finalize_state() # pylint: disable=protected-access
2235
+
2236
+
2237
+ @enum.unique
2238
+ class Compression(enum.IntEnum):
2239
+ """Indicates the compression method to be used for an RPC.
2240
+
2241
+ Attributes:
2242
+ NoCompression: Do not use compression algorithm.
2243
+ Deflate: Use "Deflate" compression algorithm.
2244
+ Gzip: Use "Gzip" compression algorithm.
2245
+ """
2246
+
2247
+ NoCompression = _compression.NoCompression
2248
+ Deflate = _compression.Deflate
2249
+ Gzip = _compression.Gzip
2250
+
2251
+
2252
+ ################################### __all__ #################################
2253
+
2254
+ __all__ = (
2255
+ "AuthMetadataContext",
2256
+ "AuthMetadataPlugin",
2257
+ "AuthMetadataPluginCallback",
2258
+ "Call",
2259
+ "CallCredentials",
2260
+ "Channel",
2261
+ "ChannelConnectivity",
2262
+ "ChannelCredentials",
2263
+ "ClientCallDetails",
2264
+ "Compression",
2265
+ "Future",
2266
+ "FutureCancelledError",
2267
+ "FutureTimeoutError",
2268
+ "GenericRpcHandler",
2269
+ "HandlerCallDetails",
2270
+ "LocalConnectionType",
2271
+ "RpcContext",
2272
+ "RpcError",
2273
+ "RpcMethodHandler",
2274
+ "Server",
2275
+ "ServerCertificateConfiguration",
2276
+ "ServerCredentials",
2277
+ "ServerInterceptor",
2278
+ "ServiceRpcHandler",
2279
+ "ServicerContext",
2280
+ "Status",
2281
+ "StatusCode",
2282
+ "StreamStreamClientInterceptor",
2283
+ "StreamStreamMultiCallable",
2284
+ "StreamUnaryClientInterceptor",
2285
+ "StreamUnaryMultiCallable",
2286
+ "UnaryStreamClientInterceptor",
2287
+ "UnaryStreamMultiCallable",
2288
+ "UnaryUnaryClientInterceptor",
2289
+ "UnaryUnaryMultiCallable",
2290
+ "access_token_call_credentials",
2291
+ "alts_channel_credentials",
2292
+ "alts_server_credentials",
2293
+ "channel_ready_future",
2294
+ "composite_call_credentials",
2295
+ "composite_channel_credentials",
2296
+ "compute_engine_channel_credentials",
2297
+ "dynamic_ssl_server_credentials",
2298
+ "insecure_channel",
2299
+ "insecure_server_credentials",
2300
+ "intercept_channel",
2301
+ "local_channel_credentials",
2302
+ "local_server_credentials",
2303
+ "metadata_call_credentials",
2304
+ "method_handlers_generic_handler",
2305
+ "protos",
2306
+ "protos_and_services",
2307
+ "secure_channel",
2308
+ "server",
2309
+ "services",
2310
+ "ssl_channel_credentials",
2311
+ "ssl_server_certificate_configuration",
2312
+ "ssl_server_credentials",
2313
+ "stream_stream_rpc_method_handler",
2314
+ "stream_unary_rpc_method_handler",
2315
+ "unary_stream_rpc_method_handler",
2316
+ "unary_unary_rpc_method_handler",
2317
+ "xds_channel_credentials",
2318
+ "xds_server_credentials",
2319
+ )
2320
+
2321
+ ############################### Extension Shims ################################
2322
+
2323
+ # Here to maintain backwards compatibility; avoid using these in new code!
2324
+ try:
2325
+ import grpc_tools
2326
+
2327
+ sys.modules.update({"grpc.tools": grpc_tools})
2328
+ except ImportError:
2329
+ pass
2330
+ try:
2331
+ import grpc_health
2332
+
2333
+ sys.modules.update({"grpc.health": grpc_health})
2334
+ except ImportError:
2335
+ pass
2336
+ try:
2337
+ import grpc_reflection
2338
+
2339
+ sys.modules.update({"grpc.reflection": grpc_reflection})
2340
+ except ImportError:
2341
+ pass
2342
+
2343
+ # Prevents import order issue in the case of renamed path.
2344
+ if sys.version_info >= (3, 6) and __name__ == "grpc":
2345
+ from grpc import aio # pylint: disable=ungrouped-imports
2346
+
2347
+ sys.modules.update({"grpc.aio": aio})
loan-advisor-agent/.venv/Lib/site-packages/grpc/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (91.4 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/grpc/__pycache__/_channel.cpython-312.pyc ADDED
Binary file (98.1 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/grpc/__pycache__/_common.cpython-312.pyc ADDED
Binary file (9.18 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/grpc/__pycache__/_compression.cpython-312.pyc ADDED
Binary file (1.97 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/grpc/__pycache__/_grpcio_metadata.cpython-312.pyc ADDED
Binary file (216 Bytes). View file
 
loan-advisor-agent/.venv/Lib/site-packages/grpc/__pycache__/_observability.cpython-312.pyc ADDED
Binary file (12.8 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/grpc/__pycache__/_runtime_protos.cpython-312.pyc ADDED
Binary file (6.04 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/grpc/__pycache__/_simple_stubs.cpython-312.pyc ADDED
Binary file (25.2 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/grpc/__pycache__/_typing.cpython-312.pyc ADDED
Binary file (2.27 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/grpc/_auth.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 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
+ """GRPCAuthMetadataPlugins for standard authentication."""
15
+
16
+ import inspect
17
+ from typing import Any, Optional
18
+
19
+ import grpc
20
+
21
+
22
+ def _sign_request(
23
+ callback: grpc.AuthMetadataPluginCallback,
24
+ token: Optional[str],
25
+ error: Optional[Exception],
26
+ ):
27
+ metadata = (("authorization", "Bearer {}".format(token)),)
28
+ callback(metadata, error)
29
+
30
+
31
+ class GoogleCallCredentials(grpc.AuthMetadataPlugin):
32
+ """Metadata wrapper for GoogleCredentials from the oauth2client library."""
33
+
34
+ _is_jwt: bool
35
+ _credentials: Any
36
+
37
+ # TODO(xuanwn): Give credentials an actual type.
38
+ def __init__(self, credentials: Any):
39
+ self._credentials = credentials
40
+ # Hack to determine if these are JWT creds and we need to pass # noqa: FIX004
41
+ # additional_claims when getting a token
42
+ self._is_jwt = (
43
+ "additional_claims"
44
+ in inspect.getfullargspec(credentials.get_access_token).args
45
+ )
46
+
47
+ def __call__(
48
+ self,
49
+ context: grpc.AuthMetadataContext,
50
+ callback: grpc.AuthMetadataPluginCallback,
51
+ ):
52
+ try:
53
+ if self._is_jwt:
54
+ access_token = self._credentials.get_access_token(
55
+ additional_claims={
56
+ "aud": context.service_url # pytype: disable=attribute-error
57
+ }
58
+ ).access_token
59
+ else:
60
+ access_token = self._credentials.get_access_token().access_token
61
+ except Exception as exception: # pylint: disable=broad-except
62
+ _sign_request(callback, None, exception)
63
+ else:
64
+ _sign_request(callback, access_token, None)
65
+
66
+
67
+ class AccessTokenAuthMetadataPlugin(grpc.AuthMetadataPlugin):
68
+ """Metadata wrapper for raw access token credentials."""
69
+
70
+ _access_token: str
71
+
72
+ def __init__(self, access_token: str):
73
+ self._access_token = access_token
74
+
75
+ def __call__(
76
+ self,
77
+ context: grpc.AuthMetadataContext,
78
+ callback: grpc.AuthMetadataPluginCallback,
79
+ ):
80
+ _sign_request(callback, self._access_token, None)
loan-advisor-agent/.venv/Lib/site-packages/grpc/_channel.py ADDED
@@ -0,0 +1,2229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 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
+ """Invocation-side implementation of gRPC Python."""
15
+
16
+ import copy
17
+ import functools
18
+ import logging
19
+ import os
20
+ import sys
21
+ import threading
22
+ import time
23
+ import types
24
+ from typing import (
25
+ Any,
26
+ Callable,
27
+ Dict,
28
+ Iterator,
29
+ List,
30
+ Optional,
31
+ Sequence,
32
+ Set,
33
+ Tuple,
34
+ Union,
35
+ )
36
+
37
+ import grpc
38
+ from grpc import _common
39
+ from grpc import _compression
40
+ from grpc import _grpcio_metadata
41
+ from grpc import _observability
42
+ from grpc._cython import cygrpc
43
+ from grpc._typing import ChannelArgumentType
44
+ from grpc._typing import DeserializingFunction
45
+ from grpc._typing import IntegratedCallFactory
46
+ from grpc._typing import MetadataType
47
+ from grpc._typing import NullaryCallbackType
48
+ from grpc._typing import ResponseType
49
+ from grpc._typing import SerializingFunction
50
+ from grpc._typing import UserTag
51
+ import grpc.experimental
52
+
53
+ _LOGGER = logging.getLogger(__name__)
54
+
55
+ _USER_AGENT = "grpc-python/{}".format(_grpcio_metadata.__version__)
56
+
57
+ _EMPTY_FLAGS = 0
58
+
59
+ # NOTE(rbellevi): No guarantees are given about the maintenance of this
60
+ # environment variable.
61
+ _DEFAULT_SINGLE_THREADED_UNARY_STREAM = (
62
+ os.getenv("GRPC_SINGLE_THREADED_UNARY_STREAM") is not None
63
+ )
64
+
65
+ _UNARY_UNARY_INITIAL_DUE = (
66
+ cygrpc.OperationType.send_initial_metadata,
67
+ cygrpc.OperationType.send_message,
68
+ cygrpc.OperationType.send_close_from_client,
69
+ cygrpc.OperationType.receive_initial_metadata,
70
+ cygrpc.OperationType.receive_message,
71
+ cygrpc.OperationType.receive_status_on_client,
72
+ )
73
+ _UNARY_STREAM_INITIAL_DUE = (
74
+ cygrpc.OperationType.send_initial_metadata,
75
+ cygrpc.OperationType.send_message,
76
+ cygrpc.OperationType.send_close_from_client,
77
+ cygrpc.OperationType.receive_initial_metadata,
78
+ cygrpc.OperationType.receive_status_on_client,
79
+ )
80
+ _STREAM_UNARY_INITIAL_DUE = (
81
+ cygrpc.OperationType.send_initial_metadata,
82
+ cygrpc.OperationType.receive_initial_metadata,
83
+ cygrpc.OperationType.receive_message,
84
+ cygrpc.OperationType.receive_status_on_client,
85
+ )
86
+ _STREAM_STREAM_INITIAL_DUE = (
87
+ cygrpc.OperationType.send_initial_metadata,
88
+ cygrpc.OperationType.receive_initial_metadata,
89
+ cygrpc.OperationType.receive_status_on_client,
90
+ )
91
+
92
+ _CHANNEL_SUBSCRIPTION_CALLBACK_ERROR_LOG_MESSAGE = (
93
+ "Exception calling channel subscription callback!"
94
+ )
95
+
96
+ _OK_RENDEZVOUS_REPR_FORMAT = (
97
+ '<{} of RPC that terminated with:\n\tstatus = {}\n\tdetails = "{}"\n>'
98
+ )
99
+
100
+ _NON_OK_RENDEZVOUS_REPR_FORMAT = (
101
+ "<{} of RPC that terminated with:\n"
102
+ "\tstatus = {}\n"
103
+ '\tdetails = "{}"\n'
104
+ '\tdebug_error_string = "{}"\n'
105
+ ">"
106
+ )
107
+
108
+
109
+ def _deadline(timeout: Optional[float]) -> Optional[float]:
110
+ return None if timeout is None else time.time() + timeout
111
+
112
+
113
+ def _unknown_code_details(
114
+ unknown_cygrpc_code: Optional[grpc.StatusCode], details: Optional[str]
115
+ ) -> str:
116
+ return 'Server sent unknown code {} and details "{}"'.format(
117
+ unknown_cygrpc_code, details
118
+ )
119
+
120
+
121
+ class _RPCState(object):
122
+ condition: threading.Condition
123
+ due: Set[cygrpc.OperationType]
124
+ initial_metadata: Optional[MetadataType]
125
+ response: Any
126
+ trailing_metadata: Optional[MetadataType]
127
+ code: Optional[grpc.StatusCode]
128
+ details: Optional[str]
129
+ debug_error_string: Optional[str]
130
+ cancelled: bool
131
+ callbacks: List[NullaryCallbackType]
132
+ fork_epoch: Optional[int]
133
+ rpc_start_time: Optional[float] # In relative seconds
134
+ rpc_end_time: Optional[float] # In relative seconds
135
+ method: Optional[str]
136
+ target: Optional[str]
137
+
138
+ def __init__(
139
+ self,
140
+ due: Sequence[cygrpc.OperationType],
141
+ initial_metadata: Optional[MetadataType],
142
+ trailing_metadata: Optional[MetadataType],
143
+ code: Optional[grpc.StatusCode],
144
+ details: Optional[str],
145
+ ):
146
+ # `condition` guards all members of _RPCState. `notify_all` is called on
147
+ # `condition` when the state of the RPC has changed.
148
+ self.condition = threading.Condition()
149
+
150
+ # The cygrpc.OperationType objects representing events due from the RPC's
151
+ # completion queue. If an operation is in `due`, it is guaranteed that
152
+ # `operate()` has been called on a corresponding operation. But the
153
+ # converse is not true. That is, in the case of failed `operate()`
154
+ # calls, there may briefly be events in `due` that do not correspond to
155
+ # operations submitted to Core.
156
+ self.due = set(due)
157
+ self.initial_metadata = initial_metadata
158
+ self.response = None
159
+ self.trailing_metadata = trailing_metadata
160
+ self.code = code
161
+ self.details = details
162
+ self.debug_error_string = None
163
+ # The following three fields are used for observability.
164
+ # Updates to those fields do not trigger self.condition.
165
+ self.rpc_start_time = None
166
+ self.rpc_end_time = None
167
+ self.method = None
168
+ self.target = None
169
+
170
+ # The semantics of grpc.Future.cancel and grpc.Future.cancelled are
171
+ # slightly wonky, so they have to be tracked separately from the rest of the
172
+ # result of the RPC. This field tracks whether cancellation was requested
173
+ # prior to termination of the RPC.
174
+ self.cancelled = False
175
+ self.callbacks = []
176
+ self.fork_epoch = cygrpc.get_fork_epoch()
177
+
178
+ def reset_postfork_child(self):
179
+ self.condition = threading.Condition()
180
+
181
+
182
+ def _abort(state: _RPCState, code: grpc.StatusCode, details: str) -> None:
183
+ if state.code is None:
184
+ state.code = code
185
+ state.details = details
186
+ if state.initial_metadata is None:
187
+ state.initial_metadata = ()
188
+ state.trailing_metadata = ()
189
+
190
+
191
+ def _handle_event(
192
+ event: cygrpc.BaseEvent,
193
+ state: _RPCState,
194
+ response_deserializer: Optional[DeserializingFunction],
195
+ ) -> List[NullaryCallbackType]:
196
+ callbacks = []
197
+ for batch_operation in event.batch_operations:
198
+ operation_type = batch_operation.type()
199
+ state.due.remove(operation_type)
200
+ if operation_type == cygrpc.OperationType.receive_initial_metadata:
201
+ state.initial_metadata = batch_operation.initial_metadata()
202
+ elif operation_type == cygrpc.OperationType.receive_message:
203
+ serialized_response = batch_operation.message()
204
+ if serialized_response is not None:
205
+ response = _common.deserialize(
206
+ serialized_response, response_deserializer
207
+ )
208
+ if response is None:
209
+ details = "Exception deserializing response!"
210
+ _abort(state, grpc.StatusCode.INTERNAL, details)
211
+ else:
212
+ state.response = response
213
+ elif operation_type == cygrpc.OperationType.receive_status_on_client:
214
+ state.trailing_metadata = batch_operation.trailing_metadata()
215
+ if state.code is None:
216
+ code = _common.CYGRPC_STATUS_CODE_TO_STATUS_CODE.get(
217
+ batch_operation.code()
218
+ )
219
+ if code is None:
220
+ state.code = grpc.StatusCode.UNKNOWN
221
+ state.details = _unknown_code_details(
222
+ code, batch_operation.details()
223
+ )
224
+ else:
225
+ state.code = code
226
+ state.details = batch_operation.details()
227
+ state.debug_error_string = batch_operation.error_string()
228
+ state.rpc_end_time = time.perf_counter()
229
+ _observability.maybe_record_rpc_latency(state)
230
+ callbacks.extend(state.callbacks)
231
+ state.callbacks = None
232
+ return callbacks
233
+
234
+
235
+ def _event_handler(
236
+ state: _RPCState, response_deserializer: Optional[DeserializingFunction]
237
+ ) -> UserTag:
238
+ def handle_event(event):
239
+ with state.condition:
240
+ callbacks = _handle_event(event, state, response_deserializer)
241
+ state.condition.notify_all()
242
+ done = not state.due
243
+ for callback in callbacks:
244
+ try:
245
+ callback()
246
+ except Exception as e: # pylint: disable=broad-except
247
+ # NOTE(rbellevi): We suppress but log errors here so as not to
248
+ # kill the channel spin thread.
249
+ _LOGGER.error(
250
+ "Exception in callback %s: %s", repr(callback.func), repr(e)
251
+ )
252
+ return done and state.fork_epoch >= cygrpc.get_fork_epoch()
253
+
254
+ return handle_event
255
+
256
+
257
+ # TODO(xuanwn): Create a base class for IntegratedCall and SegregatedCall.
258
+ # pylint: disable=too-many-statements
259
+ def _consume_request_iterator(
260
+ request_iterator: Iterator,
261
+ state: _RPCState,
262
+ call: Union[cygrpc.IntegratedCall, cygrpc.SegregatedCall],
263
+ request_serializer: SerializingFunction,
264
+ event_handler: Optional[UserTag],
265
+ ) -> None:
266
+ """Consume a request supplied by the user."""
267
+
268
+ def consume_request_iterator(): # pylint: disable=too-many-branches
269
+ # Iterate over the request iterator until it is exhausted or an error
270
+ # condition is encountered.
271
+ while True:
272
+ return_from_user_request_generator_invoked = False
273
+ try:
274
+ # The thread may die in user-code. Do not block fork for this.
275
+ cygrpc.enter_user_request_generator()
276
+ request = next(request_iterator)
277
+ except StopIteration:
278
+ break
279
+ except Exception: # pylint: disable=broad-except
280
+ cygrpc.return_from_user_request_generator()
281
+ return_from_user_request_generator_invoked = True
282
+ code = grpc.StatusCode.UNKNOWN
283
+ details = "Exception iterating requests!"
284
+ _LOGGER.exception(details)
285
+ call.cancel(
286
+ _common.STATUS_CODE_TO_CYGRPC_STATUS_CODE[code], details
287
+ )
288
+ _abort(state, code, details)
289
+ return
290
+ finally:
291
+ if not return_from_user_request_generator_invoked:
292
+ cygrpc.return_from_user_request_generator()
293
+ serialized_request = _common.serialize(request, request_serializer)
294
+ with state.condition:
295
+ if state.code is None and not state.cancelled:
296
+ if serialized_request is None:
297
+ code = grpc.StatusCode.INTERNAL
298
+ details = "Exception serializing request!"
299
+ call.cancel(
300
+ _common.STATUS_CODE_TO_CYGRPC_STATUS_CODE[code],
301
+ details,
302
+ )
303
+ _abort(state, code, details)
304
+ return
305
+ state.due.add(cygrpc.OperationType.send_message)
306
+ operations = (
307
+ cygrpc.SendMessageOperation(
308
+ serialized_request, _EMPTY_FLAGS
309
+ ),
310
+ )
311
+ operating = call.operate(operations, event_handler)
312
+ if not operating:
313
+ state.due.remove(cygrpc.OperationType.send_message)
314
+ return
315
+
316
+ def _done():
317
+ return (
318
+ state.code is not None
319
+ or cygrpc.OperationType.send_message
320
+ not in state.due
321
+ )
322
+
323
+ _common.wait(
324
+ state.condition.wait,
325
+ _done,
326
+ spin_cb=functools.partial(
327
+ cygrpc.block_if_fork_in_progress, state
328
+ ),
329
+ )
330
+ if state.code is not None:
331
+ return
332
+ else:
333
+ return
334
+ with state.condition:
335
+ if state.code is None:
336
+ state.due.add(cygrpc.OperationType.send_close_from_client)
337
+ operations = (
338
+ cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS),
339
+ )
340
+ operating = call.operate(operations, event_handler)
341
+ if not operating:
342
+ state.due.remove(
343
+ cygrpc.OperationType.send_close_from_client
344
+ )
345
+
346
+ consumption_thread = cygrpc.ForkManagedThread(
347
+ target=consume_request_iterator
348
+ )
349
+ consumption_thread.setDaemon(True)
350
+ consumption_thread.start()
351
+
352
+
353
+ def _rpc_state_string(class_name: str, rpc_state: _RPCState) -> str:
354
+ """Calculates error string for RPC."""
355
+ with rpc_state.condition:
356
+ if rpc_state.code is None:
357
+ return "<{} object>".format(class_name)
358
+ if rpc_state.code is grpc.StatusCode.OK:
359
+ return _OK_RENDEZVOUS_REPR_FORMAT.format(
360
+ class_name, rpc_state.code, rpc_state.details
361
+ )
362
+ return _NON_OK_RENDEZVOUS_REPR_FORMAT.format(
363
+ class_name,
364
+ rpc_state.code,
365
+ rpc_state.details,
366
+ rpc_state.debug_error_string,
367
+ )
368
+
369
+
370
+ class _InactiveRpcError(grpc.RpcError, grpc.Call, grpc.Future):
371
+ """An RPC error not tied to the execution of a particular RPC.
372
+
373
+ The RPC represented by the state object must not be in-progress or
374
+ cancelled.
375
+
376
+ Attributes:
377
+ _state: An instance of _RPCState.
378
+ """
379
+
380
+ _state: _RPCState
381
+
382
+ def __init__(self, state: _RPCState):
383
+ with state.condition:
384
+ self._state = _RPCState(
385
+ (),
386
+ copy.deepcopy(state.initial_metadata),
387
+ copy.deepcopy(state.trailing_metadata),
388
+ state.code,
389
+ copy.deepcopy(state.details),
390
+ )
391
+ self._state.response = copy.copy(state.response)
392
+ self._state.debug_error_string = copy.copy(state.debug_error_string)
393
+
394
+ def initial_metadata(self) -> Optional[MetadataType]:
395
+ return self._state.initial_metadata
396
+
397
+ def trailing_metadata(self) -> Optional[MetadataType]:
398
+ return self._state.trailing_metadata
399
+
400
+ def code(self) -> Optional[grpc.StatusCode]:
401
+ return self._state.code
402
+
403
+ def details(self) -> Optional[str]:
404
+ return _common.decode(self._state.details)
405
+
406
+ def debug_error_string(self) -> Optional[str]:
407
+ return _common.decode(self._state.debug_error_string)
408
+
409
+ def _repr(self) -> str:
410
+ return _rpc_state_string(self.__class__.__name__, self._state)
411
+
412
+ def __repr__(self) -> str:
413
+ return self._repr()
414
+
415
+ def __str__(self) -> str:
416
+ return self._repr()
417
+
418
+ def cancel(self) -> bool:
419
+ """See grpc.Future.cancel."""
420
+ return False
421
+
422
+ def cancelled(self) -> bool:
423
+ """See grpc.Future.cancelled."""
424
+ return False
425
+
426
+ def running(self) -> bool:
427
+ """See grpc.Future.running."""
428
+ return False
429
+
430
+ def done(self) -> bool:
431
+ """See grpc.Future.done."""
432
+ return True
433
+
434
+ def result(
435
+ self, timeout: Optional[float] = None
436
+ ) -> Any: # pylint: disable=unused-argument
437
+ """See grpc.Future.result."""
438
+ raise self
439
+
440
+ def exception(
441
+ self, timeout: Optional[float] = None # pylint: disable=unused-argument
442
+ ) -> Optional[Exception]:
443
+ """See grpc.Future.exception."""
444
+ return self
445
+
446
+ def traceback(
447
+ self, timeout: Optional[float] = None # pylint: disable=unused-argument
448
+ ) -> Optional[types.TracebackType]:
449
+ """See grpc.Future.traceback."""
450
+ try:
451
+ raise self
452
+ except grpc.RpcError:
453
+ return sys.exc_info()[2]
454
+
455
+ def add_done_callback(
456
+ self,
457
+ fn: Callable[[grpc.Future], None],
458
+ timeout: Optional[float] = None, # pylint: disable=unused-argument
459
+ ) -> None:
460
+ """See grpc.Future.add_done_callback."""
461
+ fn(self)
462
+
463
+
464
+ class _Rendezvous(grpc.RpcError, grpc.RpcContext):
465
+ """An RPC iterator.
466
+
467
+ Attributes:
468
+ _state: An instance of _RPCState.
469
+ _call: An instance of SegregatedCall or IntegratedCall.
470
+ In either case, the _call object is expected to have operate, cancel,
471
+ and next_event methods.
472
+ _response_deserializer: A callable taking bytes and return a Python
473
+ object.
474
+ _deadline: A float representing the deadline of the RPC in seconds. Or
475
+ possibly None, to represent an RPC with no deadline at all.
476
+ """
477
+
478
+ _state: _RPCState
479
+ _call: Union[cygrpc.SegregatedCall, cygrpc.IntegratedCall]
480
+ _response_deserializer: Optional[DeserializingFunction]
481
+ _deadline: Optional[float]
482
+
483
+ def __init__(
484
+ self,
485
+ state: _RPCState,
486
+ call: Union[cygrpc.SegregatedCall, cygrpc.IntegratedCall],
487
+ response_deserializer: Optional[DeserializingFunction],
488
+ deadline: Optional[float],
489
+ ):
490
+ super(_Rendezvous, self).__init__()
491
+ self._state = state
492
+ self._call = call
493
+ self._response_deserializer = response_deserializer
494
+ self._deadline = deadline
495
+
496
+ def is_active(self) -> bool:
497
+ """See grpc.RpcContext.is_active"""
498
+ with self._state.condition:
499
+ return self._state.code is None
500
+
501
+ def time_remaining(self) -> Optional[float]:
502
+ """See grpc.RpcContext.time_remaining"""
503
+ with self._state.condition:
504
+ if self._deadline is None:
505
+ return None
506
+ return max(self._deadline - time.time(), 0)
507
+
508
+ def cancel(self) -> bool:
509
+ """See grpc.RpcContext.cancel"""
510
+ with self._state.condition:
511
+ if self._state.code is None:
512
+ code = grpc.StatusCode.CANCELLED
513
+ details = "Locally cancelled by application!"
514
+ self._call.cancel(
515
+ _common.STATUS_CODE_TO_CYGRPC_STATUS_CODE[code], details
516
+ )
517
+ self._state.cancelled = True
518
+ _abort(self._state, code, details)
519
+ self._state.condition.notify_all()
520
+ return True
521
+ return False
522
+
523
+ def add_callback(self, callback: NullaryCallbackType) -> bool:
524
+ """See grpc.RpcContext.add_callback"""
525
+ with self._state.condition:
526
+ if self._state.callbacks is None:
527
+ return False
528
+ self._state.callbacks.append(callback)
529
+ return True
530
+
531
+ def __iter__(self):
532
+ return self
533
+
534
+ def next(self):
535
+ return self._next()
536
+
537
+ def __next__(self):
538
+ return self._next()
539
+
540
+ def _next(self):
541
+ raise NotImplementedError()
542
+
543
+ def debug_error_string(self) -> Optional[str]:
544
+ raise NotImplementedError()
545
+
546
+ def _repr(self) -> str:
547
+ return _rpc_state_string(self.__class__.__name__, self._state)
548
+
549
+ def __repr__(self) -> str:
550
+ return self._repr()
551
+
552
+ def __str__(self) -> str:
553
+ return self._repr()
554
+
555
+ def __del__(self) -> None:
556
+ with self._state.condition:
557
+ if self._state.code is None:
558
+ self._state.code = grpc.StatusCode.CANCELLED
559
+ self._state.details = "Cancelled upon garbage collection!"
560
+ self._state.cancelled = True
561
+ self._call.cancel(
562
+ _common.STATUS_CODE_TO_CYGRPC_STATUS_CODE[self._state.code],
563
+ self._state.details,
564
+ )
565
+ self._state.condition.notify_all()
566
+
567
+
568
+ class _SingleThreadedRendezvous(
569
+ _Rendezvous, grpc.Call, grpc.Future
570
+ ): # pylint: disable=too-many-ancestors
571
+ """An RPC iterator operating entirely on a single thread.
572
+
573
+ The __next__ method of _SingleThreadedRendezvous does not depend on the
574
+ existence of any other thread, including the "channel spin thread".
575
+ However, this means that its interface is entirely synchronous. So this
576
+ class cannot completely fulfill the grpc.Future interface. The result,
577
+ exception, and traceback methods will never block and will instead raise
578
+ an exception if calling the method would result in blocking.
579
+
580
+ This means that these methods are safe to call from add_done_callback
581
+ handlers.
582
+ """
583
+
584
+ _state: _RPCState
585
+
586
+ def _is_complete(self) -> bool:
587
+ return self._state.code is not None
588
+
589
+ def cancelled(self) -> bool:
590
+ with self._state.condition:
591
+ return self._state.cancelled
592
+
593
+ def running(self) -> bool:
594
+ with self._state.condition:
595
+ return self._state.code is None
596
+
597
+ def done(self) -> bool:
598
+ with self._state.condition:
599
+ return self._state.code is not None
600
+
601
+ def result(self, timeout: Optional[float] = None) -> Any:
602
+ """Returns the result of the computation or raises its exception.
603
+
604
+ This method will never block. Instead, it will raise an exception
605
+ if calling this method would otherwise result in blocking.
606
+
607
+ Since this method will never block, any `timeout` argument passed will
608
+ be ignored.
609
+ """
610
+ del timeout
611
+ with self._state.condition:
612
+ if not self._is_complete():
613
+ error_msg = (
614
+ "_SingleThreadedRendezvous only supports "
615
+ "result() when the RPC is complete."
616
+ )
617
+ raise grpc.experimental.UsageError(error_msg)
618
+ if self._state.code is grpc.StatusCode.OK:
619
+ return self._state.response
620
+ if self._state.cancelled:
621
+ raise grpc.FutureCancelledError()
622
+ raise self
623
+
624
+ def exception(self, timeout: Optional[float] = None) -> Optional[Exception]:
625
+ """Return the exception raised by the computation.
626
+
627
+ This method will never block. Instead, it will raise an exception
628
+ if calling this method would otherwise result in blocking.
629
+
630
+ Since this method will never block, any `timeout` argument passed will
631
+ be ignored.
632
+ """
633
+ del timeout
634
+ with self._state.condition:
635
+ if not self._is_complete():
636
+ error_msg = (
637
+ "_SingleThreadedRendezvous only supports "
638
+ "exception() when the RPC is complete."
639
+ )
640
+ raise grpc.experimental.UsageError(error_msg)
641
+ if self._state.code is grpc.StatusCode.OK:
642
+ return None
643
+ if self._state.cancelled:
644
+ raise grpc.FutureCancelledError()
645
+ return self
646
+
647
+ def traceback(
648
+ self, timeout: Optional[float] = None
649
+ ) -> Optional[types.TracebackType]:
650
+ """Access the traceback of the exception raised by the computation.
651
+
652
+ This method will never block. Instead, it will raise an exception
653
+ if calling this method would otherwise result in blocking.
654
+
655
+ Since this method will never block, any `timeout` argument passed will
656
+ be ignored.
657
+ """
658
+ del timeout
659
+ with self._state.condition:
660
+ if not self._is_complete():
661
+ msg = (
662
+ "_SingleThreadedRendezvous only supports "
663
+ "traceback() when the RPC is complete."
664
+ )
665
+ raise grpc.experimental.UsageError(msg)
666
+ if self._state.code is grpc.StatusCode.OK:
667
+ return None
668
+ if self._state.cancelled:
669
+ raise grpc.FutureCancelledError()
670
+ try:
671
+ raise self
672
+ except grpc.RpcError:
673
+ return sys.exc_info()[2]
674
+
675
+ def add_done_callback(self, fn: Callable[[grpc.Future], None]) -> None:
676
+ with self._state.condition:
677
+ if self._state.code is None:
678
+ self._state.callbacks.append(functools.partial(fn, self))
679
+ return
680
+
681
+ fn(self)
682
+
683
+ def initial_metadata(self) -> Optional[MetadataType]:
684
+ """See grpc.Call.initial_metadata"""
685
+ with self._state.condition:
686
+ # NOTE(gnossen): Based on our initial call batch, we are guaranteed
687
+ # to receive initial metadata before any messages.
688
+ while self._state.initial_metadata is None:
689
+ self._consume_next_event()
690
+ return self._state.initial_metadata
691
+
692
+ def trailing_metadata(self) -> Optional[MetadataType]:
693
+ """See grpc.Call.trailing_metadata"""
694
+ with self._state.condition:
695
+ if self._state.trailing_metadata is None:
696
+ error_msg = (
697
+ "Cannot get trailing metadata until RPC is completed."
698
+ )
699
+ raise grpc.experimental.UsageError(error_msg)
700
+ return self._state.trailing_metadata
701
+
702
+ def code(self) -> Optional[grpc.StatusCode]:
703
+ """See grpc.Call.code"""
704
+ with self._state.condition:
705
+ if self._state.code is None:
706
+ error_msg = "Cannot get code until RPC is completed."
707
+ raise grpc.experimental.UsageError(error_msg)
708
+ return self._state.code
709
+
710
+ def details(self) -> Optional[str]:
711
+ """See grpc.Call.details"""
712
+ with self._state.condition:
713
+ if self._state.details is None:
714
+ error_msg = "Cannot get details until RPC is completed."
715
+ raise grpc.experimental.UsageError(error_msg)
716
+ return _common.decode(self._state.details)
717
+
718
+ def _consume_next_event(self) -> Optional[cygrpc.BaseEvent]:
719
+ event = self._call.next_event()
720
+ with self._state.condition:
721
+ callbacks = _handle_event(
722
+ event, self._state, self._response_deserializer
723
+ )
724
+ for callback in callbacks:
725
+ # NOTE(gnossen): We intentionally allow exceptions to bubble up
726
+ # to the user when running on a single thread.
727
+ callback()
728
+ return event
729
+
730
+ def _next_response(self) -> Any:
731
+ while True:
732
+ self._consume_next_event()
733
+ with self._state.condition:
734
+ if self._state.response is not None:
735
+ response = self._state.response
736
+ self._state.response = None
737
+ return response
738
+ if cygrpc.OperationType.receive_message not in self._state.due:
739
+ if self._state.code is grpc.StatusCode.OK:
740
+ raise StopIteration()
741
+ if self._state.code is not None:
742
+ raise self
743
+
744
+ def _next(self) -> Any:
745
+ with self._state.condition:
746
+ if self._state.code is None:
747
+ # We tentatively add the operation as expected and remove
748
+ # it if the enqueue operation fails. This allows us to guarantee that
749
+ # if an event has been submitted to the core completion queue,
750
+ # it is in `due`. If we waited until after a successful
751
+ # enqueue operation then a signal could interrupt this
752
+ # thread between the enqueue operation and the addition of the
753
+ # operation to `due`. This would cause an exception on the
754
+ # channel spin thread when the operation completes and no
755
+ # corresponding operation would be present in state.due.
756
+ # Note that, since `condition` is held through this block, there is
757
+ # no data race on `due`.
758
+ self._state.due.add(cygrpc.OperationType.receive_message)
759
+ operating = self._call.operate(
760
+ (cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),), None
761
+ )
762
+ if not operating:
763
+ self._state.due.remove(cygrpc.OperationType.receive_message)
764
+ elif self._state.code is grpc.StatusCode.OK:
765
+ raise StopIteration()
766
+ else:
767
+ raise self
768
+ return self._next_response()
769
+
770
+ def debug_error_string(self) -> Optional[str]:
771
+ with self._state.condition:
772
+ if self._state.debug_error_string is None:
773
+ error_msg = (
774
+ "Cannot get debug error string until RPC is completed."
775
+ )
776
+ raise grpc.experimental.UsageError(error_msg)
777
+ return _common.decode(self._state.debug_error_string)
778
+
779
+
780
+ class _MultiThreadedRendezvous(
781
+ _Rendezvous, grpc.Call, grpc.Future
782
+ ): # pylint: disable=too-many-ancestors
783
+ """An RPC iterator that depends on a channel spin thread.
784
+
785
+ This iterator relies upon a per-channel thread running in the background,
786
+ dequeueing events from the completion queue, and notifying threads waiting
787
+ on the threading.Condition object in the _RPCState object.
788
+
789
+ This extra thread allows _MultiThreadedRendezvous to fulfill the grpc.Future interface
790
+ and to mediate a bidirection streaming RPC.
791
+ """
792
+
793
+ _state: _RPCState
794
+
795
+ def initial_metadata(self) -> Optional[MetadataType]:
796
+ """See grpc.Call.initial_metadata"""
797
+ with self._state.condition:
798
+
799
+ def _done():
800
+ return self._state.initial_metadata is not None
801
+
802
+ _common.wait(self._state.condition.wait, _done)
803
+ return self._state.initial_metadata
804
+
805
+ def trailing_metadata(self) -> Optional[MetadataType]:
806
+ """See grpc.Call.trailing_metadata"""
807
+ with self._state.condition:
808
+
809
+ def _done():
810
+ return self._state.trailing_metadata is not None
811
+
812
+ _common.wait(self._state.condition.wait, _done)
813
+ return self._state.trailing_metadata
814
+
815
+ def code(self) -> Optional[grpc.StatusCode]:
816
+ """See grpc.Call.code"""
817
+ with self._state.condition:
818
+
819
+ def _done():
820
+ return self._state.code is not None
821
+
822
+ _common.wait(self._state.condition.wait, _done)
823
+ return self._state.code
824
+
825
+ def details(self) -> Optional[str]:
826
+ """See grpc.Call.details"""
827
+ with self._state.condition:
828
+
829
+ def _done():
830
+ return self._state.details is not None
831
+
832
+ _common.wait(self._state.condition.wait, _done)
833
+ return _common.decode(self._state.details)
834
+
835
+ def debug_error_string(self) -> Optional[str]:
836
+ with self._state.condition:
837
+
838
+ def _done():
839
+ return self._state.debug_error_string is not None
840
+
841
+ _common.wait(self._state.condition.wait, _done)
842
+ return _common.decode(self._state.debug_error_string)
843
+
844
+ def cancelled(self) -> bool:
845
+ with self._state.condition:
846
+ return self._state.cancelled
847
+
848
+ def running(self) -> bool:
849
+ with self._state.condition:
850
+ return self._state.code is None
851
+
852
+ def done(self) -> bool:
853
+ with self._state.condition:
854
+ return self._state.code is not None
855
+
856
+ def _is_complete(self) -> bool:
857
+ return self._state.code is not None
858
+
859
+ def result(self, timeout: Optional[float] = None) -> Any:
860
+ """Returns the result of the computation or raises its exception.
861
+
862
+ See grpc.Future.result for the full API contract.
863
+ """
864
+ with self._state.condition:
865
+ timed_out = _common.wait(
866
+ self._state.condition.wait, self._is_complete, timeout=timeout
867
+ )
868
+ if timed_out:
869
+ raise grpc.FutureTimeoutError()
870
+ if self._state.code is grpc.StatusCode.OK:
871
+ return self._state.response
872
+ if self._state.cancelled:
873
+ raise grpc.FutureCancelledError()
874
+ raise self
875
+
876
+ def exception(self, timeout: Optional[float] = None) -> Optional[Exception]:
877
+ """Return the exception raised by the computation.
878
+
879
+ See grpc.Future.exception for the full API contract.
880
+ """
881
+ with self._state.condition:
882
+ timed_out = _common.wait(
883
+ self._state.condition.wait, self._is_complete, timeout=timeout
884
+ )
885
+ if timed_out:
886
+ raise grpc.FutureTimeoutError()
887
+ if self._state.code is grpc.StatusCode.OK:
888
+ return None
889
+ if self._state.cancelled:
890
+ raise grpc.FutureCancelledError()
891
+ return self
892
+
893
+ def traceback(
894
+ self, timeout: Optional[float] = None
895
+ ) -> Optional[types.TracebackType]:
896
+ """Access the traceback of the exception raised by the computation.
897
+
898
+ See grpc.future.traceback for the full API contract.
899
+ """
900
+ with self._state.condition:
901
+ timed_out = _common.wait(
902
+ self._state.condition.wait, self._is_complete, timeout=timeout
903
+ )
904
+ if timed_out:
905
+ raise grpc.FutureTimeoutError()
906
+ if self._state.code is grpc.StatusCode.OK:
907
+ return None
908
+ if self._state.cancelled:
909
+ raise grpc.FutureCancelledError()
910
+ try:
911
+ raise self
912
+ except grpc.RpcError:
913
+ return sys.exc_info()[2]
914
+
915
+ def add_done_callback(self, fn: Callable[[grpc.Future], None]) -> None:
916
+ with self._state.condition:
917
+ if self._state.code is None:
918
+ self._state.callbacks.append(functools.partial(fn, self))
919
+ return
920
+
921
+ fn(self)
922
+
923
+ def _next(self) -> Any:
924
+ with self._state.condition:
925
+ if self._state.code is None:
926
+ event_handler = _event_handler(
927
+ self._state, self._response_deserializer
928
+ )
929
+ self._state.due.add(cygrpc.OperationType.receive_message)
930
+ operating = self._call.operate(
931
+ (cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),),
932
+ event_handler,
933
+ )
934
+ if not operating:
935
+ self._state.due.remove(cygrpc.OperationType.receive_message)
936
+ elif self._state.code is grpc.StatusCode.OK:
937
+ raise StopIteration()
938
+ else:
939
+ raise self
940
+
941
+ def _response_ready():
942
+ return self._state.response is not None or (
943
+ cygrpc.OperationType.receive_message not in self._state.due
944
+ and self._state.code is not None
945
+ )
946
+
947
+ _common.wait(self._state.condition.wait, _response_ready)
948
+ if self._state.response is not None:
949
+ response = self._state.response
950
+ self._state.response = None
951
+ return response
952
+ if cygrpc.OperationType.receive_message not in self._state.due:
953
+ if self._state.code is grpc.StatusCode.OK:
954
+ raise StopIteration()
955
+ if self._state.code is not None:
956
+ raise self
957
+
958
+
959
+ def _start_unary_request(
960
+ request: Any,
961
+ timeout: Optional[float],
962
+ request_serializer: SerializingFunction,
963
+ ) -> Tuple[Optional[float], Optional[bytes], Optional[grpc.RpcError]]:
964
+ deadline = _deadline(timeout)
965
+ serialized_request = _common.serialize(request, request_serializer)
966
+ if serialized_request is None:
967
+ state = _RPCState(
968
+ (),
969
+ (),
970
+ (),
971
+ grpc.StatusCode.INTERNAL,
972
+ "Exception serializing request!",
973
+ )
974
+ error = _InactiveRpcError(state)
975
+ return deadline, None, error
976
+ return deadline, serialized_request, None
977
+
978
+
979
+ def _end_unary_response_blocking(
980
+ state: _RPCState,
981
+ call: cygrpc.SegregatedCall,
982
+ with_call: bool,
983
+ deadline: Optional[float],
984
+ ) -> Union[ResponseType, Tuple[ResponseType, grpc.Call]]:
985
+ if state.code is grpc.StatusCode.OK:
986
+ if with_call:
987
+ rendezvous = _MultiThreadedRendezvous(state, call, None, deadline)
988
+ return state.response, rendezvous
989
+ return state.response
990
+ raise _InactiveRpcError(state) # pytype: disable=not-instantiable
991
+
992
+
993
+ def _stream_unary_invocation_operations(
994
+ metadata: Optional[MetadataType], initial_metadata_flags: int
995
+ ) -> Sequence[Sequence[cygrpc.Operation]]:
996
+ return (
997
+ (
998
+ cygrpc.SendInitialMetadataOperation(
999
+ metadata, initial_metadata_flags
1000
+ ),
1001
+ cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),
1002
+ cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),
1003
+ ),
1004
+ (cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),),
1005
+ )
1006
+
1007
+
1008
+ def _stream_unary_invocation_operations_and_tags(
1009
+ metadata: Optional[MetadataType], initial_metadata_flags: int
1010
+ ) -> Sequence[Tuple[Sequence[cygrpc.Operation], Optional[UserTag]]]:
1011
+ return tuple(
1012
+ (
1013
+ operations,
1014
+ None,
1015
+ )
1016
+ for operations in _stream_unary_invocation_operations(
1017
+ metadata, initial_metadata_flags
1018
+ )
1019
+ )
1020
+
1021
+
1022
+ def _determine_deadline(user_deadline: Optional[float]) -> Optional[float]:
1023
+ parent_deadline = cygrpc.get_deadline_from_context()
1024
+ if parent_deadline is None and user_deadline is None:
1025
+ return None
1026
+ if parent_deadline is not None and user_deadline is None:
1027
+ return parent_deadline
1028
+ if user_deadline is not None and parent_deadline is None:
1029
+ return user_deadline
1030
+ return min(parent_deadline, user_deadline)
1031
+
1032
+
1033
+ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable):
1034
+ _channel: cygrpc.Channel
1035
+ _managed_call: IntegratedCallFactory
1036
+ _method: bytes
1037
+ _target: bytes
1038
+ _request_serializer: Optional[SerializingFunction]
1039
+ _response_deserializer: Optional[DeserializingFunction]
1040
+ _context: Any
1041
+ _registered_call_handle: Optional[int]
1042
+
1043
+ __slots__ = [
1044
+ "_channel",
1045
+ "_context",
1046
+ "_managed_call",
1047
+ "_method",
1048
+ "_request_serializer",
1049
+ "_response_deserializer",
1050
+ "_target",
1051
+ ]
1052
+
1053
+ # pylint: disable=too-many-arguments
1054
+ def __init__(
1055
+ self,
1056
+ channel: cygrpc.Channel,
1057
+ managed_call: IntegratedCallFactory,
1058
+ method: bytes,
1059
+ target: bytes,
1060
+ request_serializer: Optional[SerializingFunction],
1061
+ response_deserializer: Optional[DeserializingFunction],
1062
+ _registered_call_handle: Optional[int],
1063
+ ):
1064
+ self._channel = channel
1065
+ self._managed_call = managed_call
1066
+ self._method = method
1067
+ self._target = target
1068
+ self._request_serializer = request_serializer
1069
+ self._response_deserializer = response_deserializer
1070
+ self._context = cygrpc.build_census_context()
1071
+ self._registered_call_handle = _registered_call_handle
1072
+
1073
+ def _prepare(
1074
+ self,
1075
+ request: Any,
1076
+ timeout: Optional[float],
1077
+ metadata: Optional[MetadataType],
1078
+ wait_for_ready: Optional[bool],
1079
+ compression: Optional[grpc.Compression],
1080
+ ) -> Tuple[
1081
+ Optional[_RPCState],
1082
+ Optional[Sequence[cygrpc.Operation]],
1083
+ Optional[float],
1084
+ Optional[grpc.RpcError],
1085
+ ]:
1086
+ deadline, serialized_request, rendezvous = _start_unary_request(
1087
+ request, timeout, self._request_serializer
1088
+ )
1089
+ initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready(
1090
+ wait_for_ready
1091
+ )
1092
+ augmented_metadata = _compression.augment_metadata(
1093
+ metadata, compression
1094
+ )
1095
+ if serialized_request is None:
1096
+ return None, None, None, rendezvous
1097
+ state = _RPCState(_UNARY_UNARY_INITIAL_DUE, None, None, None, None)
1098
+ operations = (
1099
+ cygrpc.SendInitialMetadataOperation(
1100
+ augmented_metadata, initial_metadata_flags
1101
+ ),
1102
+ cygrpc.SendMessageOperation(serialized_request, _EMPTY_FLAGS),
1103
+ cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS),
1104
+ cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),
1105
+ cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),
1106
+ cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),
1107
+ )
1108
+ return state, operations, deadline, None
1109
+
1110
+ def _blocking(
1111
+ self,
1112
+ request: Any,
1113
+ timeout: Optional[float] = None,
1114
+ metadata: Optional[MetadataType] = None,
1115
+ credentials: Optional[grpc.CallCredentials] = None,
1116
+ wait_for_ready: Optional[bool] = None,
1117
+ compression: Optional[grpc.Compression] = None,
1118
+ ) -> Tuple[_RPCState, cygrpc.SegregatedCall]:
1119
+ state, operations, deadline, rendezvous = self._prepare(
1120
+ request, timeout, metadata, wait_for_ready, compression
1121
+ )
1122
+ if state is None:
1123
+ raise rendezvous # pylint: disable-msg=raising-bad-type
1124
+ state.rpc_start_time = time.perf_counter()
1125
+ state.method = _common.decode(self._method)
1126
+ state.target = _common.decode(self._target)
1127
+ call = self._channel.segregated_call(
1128
+ cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS,
1129
+ self._method,
1130
+ None,
1131
+ _determine_deadline(deadline),
1132
+ metadata,
1133
+ None if credentials is None else credentials._credentials,
1134
+ (
1135
+ (
1136
+ operations,
1137
+ None,
1138
+ ),
1139
+ ),
1140
+ self._context,
1141
+ self._registered_call_handle,
1142
+ )
1143
+ event = call.next_event()
1144
+ _handle_event(event, state, self._response_deserializer)
1145
+ return state, call
1146
+
1147
+ def __call__(
1148
+ self,
1149
+ request: Any,
1150
+ timeout: Optional[float] = None,
1151
+ metadata: Optional[MetadataType] = None,
1152
+ credentials: Optional[grpc.CallCredentials] = None,
1153
+ wait_for_ready: Optional[bool] = None,
1154
+ compression: Optional[grpc.Compression] = None,
1155
+ ) -> Any:
1156
+ state, call = self._blocking(
1157
+ request, timeout, metadata, credentials, wait_for_ready, compression
1158
+ )
1159
+ return _end_unary_response_blocking(state, call, False, None)
1160
+
1161
+ def with_call(
1162
+ self,
1163
+ request: Any,
1164
+ timeout: Optional[float] = None,
1165
+ metadata: Optional[MetadataType] = None,
1166
+ credentials: Optional[grpc.CallCredentials] = None,
1167
+ wait_for_ready: Optional[bool] = None,
1168
+ compression: Optional[grpc.Compression] = None,
1169
+ ) -> Tuple[Any, grpc.Call]:
1170
+ state, call = self._blocking(
1171
+ request, timeout, metadata, credentials, wait_for_ready, compression
1172
+ )
1173
+ return _end_unary_response_blocking(state, call, True, None)
1174
+
1175
+ def future(
1176
+ self,
1177
+ request: Any,
1178
+ timeout: Optional[float] = None,
1179
+ metadata: Optional[MetadataType] = None,
1180
+ credentials: Optional[grpc.CallCredentials] = None,
1181
+ wait_for_ready: Optional[bool] = None,
1182
+ compression: Optional[grpc.Compression] = None,
1183
+ ) -> _MultiThreadedRendezvous:
1184
+ state, operations, deadline, rendezvous = self._prepare(
1185
+ request, timeout, metadata, wait_for_ready, compression
1186
+ )
1187
+ if state is None:
1188
+ raise rendezvous # pylint: disable-msg=raising-bad-type
1189
+ event_handler = _event_handler(state, self._response_deserializer)
1190
+ state.rpc_start_time = time.perf_counter()
1191
+ state.method = _common.decode(self._method)
1192
+ state.target = _common.decode(self._target)
1193
+ call = self._managed_call(
1194
+ cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS,
1195
+ self._method,
1196
+ None,
1197
+ deadline,
1198
+ metadata,
1199
+ None if credentials is None else credentials._credentials,
1200
+ (operations,),
1201
+ event_handler,
1202
+ self._context,
1203
+ self._registered_call_handle,
1204
+ )
1205
+ return _MultiThreadedRendezvous(
1206
+ state, call, self._response_deserializer, deadline
1207
+ )
1208
+
1209
+
1210
+ class _SingleThreadedUnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable):
1211
+ _channel: cygrpc.Channel
1212
+ _method: bytes
1213
+ _target: bytes
1214
+ _request_serializer: Optional[SerializingFunction]
1215
+ _response_deserializer: Optional[DeserializingFunction]
1216
+ _context: Any
1217
+ _registered_call_handle: Optional[int]
1218
+
1219
+ __slots__ = [
1220
+ "_channel",
1221
+ "_context",
1222
+ "_method",
1223
+ "_request_serializer",
1224
+ "_response_deserializer",
1225
+ "_target",
1226
+ ]
1227
+
1228
+ # pylint: disable=too-many-arguments
1229
+ def __init__(
1230
+ self,
1231
+ channel: cygrpc.Channel,
1232
+ method: bytes,
1233
+ target: bytes,
1234
+ request_serializer: SerializingFunction,
1235
+ response_deserializer: DeserializingFunction,
1236
+ _registered_call_handle: Optional[int],
1237
+ ):
1238
+ self._channel = channel
1239
+ self._method = method
1240
+ self._target = target
1241
+ self._request_serializer = request_serializer
1242
+ self._response_deserializer = response_deserializer
1243
+ self._context = cygrpc.build_census_context()
1244
+ self._registered_call_handle = _registered_call_handle
1245
+
1246
+ def __call__( # pylint: disable=too-many-locals
1247
+ self,
1248
+ request: Any,
1249
+ timeout: Optional[float] = None,
1250
+ metadata: Optional[MetadataType] = None,
1251
+ credentials: Optional[grpc.CallCredentials] = None,
1252
+ wait_for_ready: Optional[bool] = None,
1253
+ compression: Optional[grpc.Compression] = None,
1254
+ ) -> _SingleThreadedRendezvous:
1255
+ deadline = _deadline(timeout)
1256
+ serialized_request = _common.serialize(
1257
+ request, self._request_serializer
1258
+ )
1259
+ if serialized_request is None:
1260
+ state = _RPCState(
1261
+ (),
1262
+ (),
1263
+ (),
1264
+ grpc.StatusCode.INTERNAL,
1265
+ "Exception serializing request!",
1266
+ )
1267
+ raise _InactiveRpcError(state)
1268
+
1269
+ state = _RPCState(_UNARY_STREAM_INITIAL_DUE, None, None, None, None)
1270
+ call_credentials = (
1271
+ None if credentials is None else credentials._credentials
1272
+ )
1273
+ initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready(
1274
+ wait_for_ready
1275
+ )
1276
+ augmented_metadata = _compression.augment_metadata(
1277
+ metadata, compression
1278
+ )
1279
+ operations = (
1280
+ (
1281
+ cygrpc.SendInitialMetadataOperation(
1282
+ augmented_metadata, initial_metadata_flags
1283
+ ),
1284
+ cygrpc.SendMessageOperation(serialized_request, _EMPTY_FLAGS),
1285
+ cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS),
1286
+ ),
1287
+ (cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),),
1288
+ (cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),),
1289
+ )
1290
+ operations_and_tags = tuple((ops, None) for ops in operations)
1291
+ state.rpc_start_time = time.perf_counter()
1292
+ state.method = _common.decode(self._method)
1293
+ state.target = _common.decode(self._target)
1294
+ call = self._channel.segregated_call(
1295
+ cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS,
1296
+ self._method,
1297
+ None,
1298
+ _determine_deadline(deadline),
1299
+ metadata,
1300
+ call_credentials,
1301
+ operations_and_tags,
1302
+ self._context,
1303
+ self._registered_call_handle,
1304
+ )
1305
+ return _SingleThreadedRendezvous(
1306
+ state, call, self._response_deserializer, deadline
1307
+ )
1308
+
1309
+
1310
+ class _UnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable):
1311
+ _channel: cygrpc.Channel
1312
+ _managed_call: IntegratedCallFactory
1313
+ _method: bytes
1314
+ _target: bytes
1315
+ _request_serializer: Optional[SerializingFunction]
1316
+ _response_deserializer: Optional[DeserializingFunction]
1317
+ _context: Any
1318
+ _registered_call_handle: Optional[int]
1319
+
1320
+ __slots__ = [
1321
+ "_channel",
1322
+ "_context",
1323
+ "_managed_call",
1324
+ "_method",
1325
+ "_request_serializer",
1326
+ "_response_deserializer",
1327
+ "_target",
1328
+ ]
1329
+
1330
+ # pylint: disable=too-many-arguments
1331
+ def __init__(
1332
+ self,
1333
+ channel: cygrpc.Channel,
1334
+ managed_call: IntegratedCallFactory,
1335
+ method: bytes,
1336
+ target: bytes,
1337
+ request_serializer: SerializingFunction,
1338
+ response_deserializer: DeserializingFunction,
1339
+ _registered_call_handle: Optional[int],
1340
+ ):
1341
+ self._channel = channel
1342
+ self._managed_call = managed_call
1343
+ self._method = method
1344
+ self._target = target
1345
+ self._request_serializer = request_serializer
1346
+ self._response_deserializer = response_deserializer
1347
+ self._context = cygrpc.build_census_context()
1348
+ self._registered_call_handle = _registered_call_handle
1349
+
1350
+ def __call__( # pylint: disable=too-many-locals
1351
+ self,
1352
+ request: Any,
1353
+ timeout: Optional[float] = None,
1354
+ metadata: Optional[MetadataType] = None,
1355
+ credentials: Optional[grpc.CallCredentials] = None,
1356
+ wait_for_ready: Optional[bool] = None,
1357
+ compression: Optional[grpc.Compression] = None,
1358
+ ) -> _MultiThreadedRendezvous:
1359
+ deadline, serialized_request, rendezvous = _start_unary_request(
1360
+ request, timeout, self._request_serializer
1361
+ )
1362
+ initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready(
1363
+ wait_for_ready
1364
+ )
1365
+ if serialized_request is None:
1366
+ raise rendezvous # pylint: disable-msg=raising-bad-type
1367
+ augmented_metadata = _compression.augment_metadata(
1368
+ metadata, compression
1369
+ )
1370
+ state = _RPCState(_UNARY_STREAM_INITIAL_DUE, None, None, None, None)
1371
+ operations = (
1372
+ (
1373
+ cygrpc.SendInitialMetadataOperation(
1374
+ augmented_metadata, initial_metadata_flags
1375
+ ),
1376
+ cygrpc.SendMessageOperation(serialized_request, _EMPTY_FLAGS),
1377
+ cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS),
1378
+ cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),
1379
+ ),
1380
+ (cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),),
1381
+ )
1382
+ state.rpc_start_time = time.perf_counter()
1383
+ state.method = _common.decode(self._method)
1384
+ state.target = _common.decode(self._target)
1385
+ call = self._managed_call(
1386
+ cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS,
1387
+ self._method,
1388
+ None,
1389
+ _determine_deadline(deadline),
1390
+ metadata,
1391
+ None if credentials is None else credentials._credentials,
1392
+ operations,
1393
+ _event_handler(state, self._response_deserializer),
1394
+ self._context,
1395
+ self._registered_call_handle,
1396
+ )
1397
+ return _MultiThreadedRendezvous(
1398
+ state, call, self._response_deserializer, deadline
1399
+ )
1400
+
1401
+
1402
+ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable):
1403
+ _channel: cygrpc.Channel
1404
+ _managed_call: IntegratedCallFactory
1405
+ _method: bytes
1406
+ _target: bytes
1407
+ _request_serializer: Optional[SerializingFunction]
1408
+ _response_deserializer: Optional[DeserializingFunction]
1409
+ _context: Any
1410
+ _registered_call_handle: Optional[int]
1411
+
1412
+ __slots__ = [
1413
+ "_channel",
1414
+ "_context",
1415
+ "_managed_call",
1416
+ "_method",
1417
+ "_request_serializer",
1418
+ "_response_deserializer",
1419
+ "_target",
1420
+ ]
1421
+
1422
+ # pylint: disable=too-many-arguments
1423
+ def __init__(
1424
+ self,
1425
+ channel: cygrpc.Channel,
1426
+ managed_call: IntegratedCallFactory,
1427
+ method: bytes,
1428
+ target: bytes,
1429
+ request_serializer: Optional[SerializingFunction],
1430
+ response_deserializer: Optional[DeserializingFunction],
1431
+ _registered_call_handle: Optional[int],
1432
+ ):
1433
+ self._channel = channel
1434
+ self._managed_call = managed_call
1435
+ self._method = method
1436
+ self._target = target
1437
+ self._request_serializer = request_serializer
1438
+ self._response_deserializer = response_deserializer
1439
+ self._context = cygrpc.build_census_context()
1440
+ self._registered_call_handle = _registered_call_handle
1441
+
1442
+ def _blocking(
1443
+ self,
1444
+ request_iterator: Iterator,
1445
+ timeout: Optional[float],
1446
+ metadata: Optional[MetadataType],
1447
+ credentials: Optional[grpc.CallCredentials],
1448
+ wait_for_ready: Optional[bool],
1449
+ compression: Optional[grpc.Compression],
1450
+ ) -> Tuple[_RPCState, cygrpc.SegregatedCall]:
1451
+ deadline = _deadline(timeout)
1452
+ state = _RPCState(_STREAM_UNARY_INITIAL_DUE, None, None, None, None)
1453
+ initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready(
1454
+ wait_for_ready
1455
+ )
1456
+ augmented_metadata = _compression.augment_metadata(
1457
+ metadata, compression
1458
+ )
1459
+ state.rpc_start_time = time.perf_counter()
1460
+ state.method = _common.decode(self._method)
1461
+ state.target = _common.decode(self._target)
1462
+ call = self._channel.segregated_call(
1463
+ cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS,
1464
+ self._method,
1465
+ None,
1466
+ _determine_deadline(deadline),
1467
+ augmented_metadata,
1468
+ None if credentials is None else credentials._credentials,
1469
+ _stream_unary_invocation_operations_and_tags(
1470
+ augmented_metadata, initial_metadata_flags
1471
+ ),
1472
+ self._context,
1473
+ self._registered_call_handle,
1474
+ )
1475
+ _consume_request_iterator(
1476
+ request_iterator, state, call, self._request_serializer, None
1477
+ )
1478
+ while True:
1479
+ event = call.next_event()
1480
+ with state.condition:
1481
+ _handle_event(event, state, self._response_deserializer)
1482
+ state.condition.notify_all()
1483
+ if not state.due:
1484
+ break
1485
+ return state, call
1486
+
1487
+ def __call__(
1488
+ self,
1489
+ request_iterator: Iterator,
1490
+ timeout: Optional[float] = None,
1491
+ metadata: Optional[MetadataType] = None,
1492
+ credentials: Optional[grpc.CallCredentials] = None,
1493
+ wait_for_ready: Optional[bool] = None,
1494
+ compression: Optional[grpc.Compression] = None,
1495
+ ) -> Any:
1496
+ state, call = self._blocking(
1497
+ request_iterator,
1498
+ timeout,
1499
+ metadata,
1500
+ credentials,
1501
+ wait_for_ready,
1502
+ compression,
1503
+ )
1504
+ return _end_unary_response_blocking(state, call, False, None)
1505
+
1506
+ def with_call(
1507
+ self,
1508
+ request_iterator: Iterator,
1509
+ timeout: Optional[float] = None,
1510
+ metadata: Optional[MetadataType] = None,
1511
+ credentials: Optional[grpc.CallCredentials] = None,
1512
+ wait_for_ready: Optional[bool] = None,
1513
+ compression: Optional[grpc.Compression] = None,
1514
+ ) -> Tuple[Any, grpc.Call]:
1515
+ state, call = self._blocking(
1516
+ request_iterator,
1517
+ timeout,
1518
+ metadata,
1519
+ credentials,
1520
+ wait_for_ready,
1521
+ compression,
1522
+ )
1523
+ return _end_unary_response_blocking(state, call, True, None)
1524
+
1525
+ def future(
1526
+ self,
1527
+ request_iterator: Iterator,
1528
+ timeout: Optional[float] = None,
1529
+ metadata: Optional[MetadataType] = None,
1530
+ credentials: Optional[grpc.CallCredentials] = None,
1531
+ wait_for_ready: Optional[bool] = None,
1532
+ compression: Optional[grpc.Compression] = None,
1533
+ ) -> _MultiThreadedRendezvous:
1534
+ deadline = _deadline(timeout)
1535
+ state = _RPCState(_STREAM_UNARY_INITIAL_DUE, None, None, None, None)
1536
+ event_handler = _event_handler(state, self._response_deserializer)
1537
+ initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready(
1538
+ wait_for_ready
1539
+ )
1540
+ augmented_metadata = _compression.augment_metadata(
1541
+ metadata, compression
1542
+ )
1543
+ state.rpc_start_time = time.perf_counter()
1544
+ state.method = _common.decode(self._method)
1545
+ state.target = _common.decode(self._target)
1546
+ call = self._managed_call(
1547
+ cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS,
1548
+ self._method,
1549
+ None,
1550
+ deadline,
1551
+ augmented_metadata,
1552
+ None if credentials is None else credentials._credentials,
1553
+ _stream_unary_invocation_operations(
1554
+ metadata, initial_metadata_flags
1555
+ ),
1556
+ event_handler,
1557
+ self._context,
1558
+ self._registered_call_handle,
1559
+ )
1560
+ _consume_request_iterator(
1561
+ request_iterator,
1562
+ state,
1563
+ call,
1564
+ self._request_serializer,
1565
+ event_handler,
1566
+ )
1567
+ return _MultiThreadedRendezvous(
1568
+ state, call, self._response_deserializer, deadline
1569
+ )
1570
+
1571
+
1572
+ class _StreamStreamMultiCallable(grpc.StreamStreamMultiCallable):
1573
+ _channel: cygrpc.Channel
1574
+ _managed_call: IntegratedCallFactory
1575
+ _method: bytes
1576
+ _target: bytes
1577
+ _request_serializer: Optional[SerializingFunction]
1578
+ _response_deserializer: Optional[DeserializingFunction]
1579
+ _context: Any
1580
+ _registered_call_handle: Optional[int]
1581
+
1582
+ __slots__ = [
1583
+ "_channel",
1584
+ "_context",
1585
+ "_managed_call",
1586
+ "_method",
1587
+ "_request_serializer",
1588
+ "_response_deserializer",
1589
+ "_target",
1590
+ ]
1591
+
1592
+ # pylint: disable=too-many-arguments
1593
+ def __init__(
1594
+ self,
1595
+ channel: cygrpc.Channel,
1596
+ managed_call: IntegratedCallFactory,
1597
+ method: bytes,
1598
+ target: bytes,
1599
+ request_serializer: Optional[SerializingFunction],
1600
+ response_deserializer: Optional[DeserializingFunction],
1601
+ _registered_call_handle: Optional[int],
1602
+ ):
1603
+ self._channel = channel
1604
+ self._managed_call = managed_call
1605
+ self._method = method
1606
+ self._target = target
1607
+ self._request_serializer = request_serializer
1608
+ self._response_deserializer = response_deserializer
1609
+ self._context = cygrpc.build_census_context()
1610
+ self._registered_call_handle = _registered_call_handle
1611
+
1612
+ def __call__(
1613
+ self,
1614
+ request_iterator: Iterator,
1615
+ timeout: Optional[float] = None,
1616
+ metadata: Optional[MetadataType] = None,
1617
+ credentials: Optional[grpc.CallCredentials] = None,
1618
+ wait_for_ready: Optional[bool] = None,
1619
+ compression: Optional[grpc.Compression] = None,
1620
+ ) -> _MultiThreadedRendezvous:
1621
+ deadline = _deadline(timeout)
1622
+ state = _RPCState(_STREAM_STREAM_INITIAL_DUE, None, None, None, None)
1623
+ initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready(
1624
+ wait_for_ready
1625
+ )
1626
+ augmented_metadata = _compression.augment_metadata(
1627
+ metadata, compression
1628
+ )
1629
+ operations = (
1630
+ (
1631
+ cygrpc.SendInitialMetadataOperation(
1632
+ augmented_metadata, initial_metadata_flags
1633
+ ),
1634
+ cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),
1635
+ ),
1636
+ (cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),),
1637
+ )
1638
+ event_handler = _event_handler(state, self._response_deserializer)
1639
+ state.rpc_start_time = time.perf_counter()
1640
+ state.method = _common.decode(self._method)
1641
+ state.target = _common.decode(self._target)
1642
+ call = self._managed_call(
1643
+ cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS,
1644
+ self._method,
1645
+ None,
1646
+ _determine_deadline(deadline),
1647
+ augmented_metadata,
1648
+ None if credentials is None else credentials._credentials,
1649
+ operations,
1650
+ event_handler,
1651
+ self._context,
1652
+ self._registered_call_handle,
1653
+ )
1654
+ _consume_request_iterator(
1655
+ request_iterator,
1656
+ state,
1657
+ call,
1658
+ self._request_serializer,
1659
+ event_handler,
1660
+ )
1661
+ return _MultiThreadedRendezvous(
1662
+ state, call, self._response_deserializer, deadline
1663
+ )
1664
+
1665
+
1666
+ class _InitialMetadataFlags(int):
1667
+ """Stores immutable initial metadata flags"""
1668
+
1669
+ def __new__(cls, value: int = _EMPTY_FLAGS):
1670
+ value &= cygrpc.InitialMetadataFlags.used_mask
1671
+ return super(_InitialMetadataFlags, cls).__new__(cls, value)
1672
+
1673
+ def with_wait_for_ready(self, wait_for_ready: Optional[bool]) -> int:
1674
+ if wait_for_ready is not None:
1675
+ if wait_for_ready:
1676
+ return self.__class__(
1677
+ self
1678
+ | cygrpc.InitialMetadataFlags.wait_for_ready
1679
+ | cygrpc.InitialMetadataFlags.wait_for_ready_explicitly_set
1680
+ )
1681
+ if not wait_for_ready:
1682
+ return self.__class__(
1683
+ self & ~cygrpc.InitialMetadataFlags.wait_for_ready
1684
+ | cygrpc.InitialMetadataFlags.wait_for_ready_explicitly_set
1685
+ )
1686
+ return self
1687
+
1688
+
1689
+ class _ChannelCallState(object):
1690
+ channel: cygrpc.Channel
1691
+ managed_calls: int
1692
+ threading: bool
1693
+
1694
+ def __init__(self, channel: cygrpc.Channel):
1695
+ self.lock = threading.Lock()
1696
+ self.channel = channel
1697
+ self.managed_calls = 0
1698
+ self.threading = False
1699
+
1700
+ def reset_postfork_child(self) -> None:
1701
+ self.managed_calls = 0
1702
+
1703
+ def __del__(self):
1704
+ try:
1705
+ self.channel.close(
1706
+ cygrpc.StatusCode.cancelled, "Channel deallocated!"
1707
+ )
1708
+ except (TypeError, AttributeError):
1709
+ pass
1710
+
1711
+
1712
+ def _run_channel_spin_thread(state: _ChannelCallState) -> None:
1713
+ def channel_spin():
1714
+ while True:
1715
+ cygrpc.block_if_fork_in_progress(state)
1716
+ event = state.channel.next_call_event()
1717
+ if event.completion_type == cygrpc.CompletionType.queue_timeout:
1718
+ continue
1719
+ call_completed = event.tag(event)
1720
+ if call_completed:
1721
+ with state.lock:
1722
+ state.managed_calls -= 1
1723
+ if state.managed_calls == 0:
1724
+ return
1725
+
1726
+ channel_spin_thread = cygrpc.ForkManagedThread(target=channel_spin)
1727
+ channel_spin_thread.setDaemon(True)
1728
+ channel_spin_thread.start()
1729
+
1730
+
1731
+ def _channel_managed_call_management(state: _ChannelCallState):
1732
+ # pylint: disable=too-many-arguments
1733
+ def create(
1734
+ flags: int,
1735
+ method: bytes,
1736
+ host: Optional[str],
1737
+ deadline: Optional[float],
1738
+ metadata: Optional[MetadataType],
1739
+ credentials: Optional[cygrpc.CallCredentials],
1740
+ operations: Sequence[Sequence[cygrpc.Operation]],
1741
+ event_handler: UserTag,
1742
+ context: Any,
1743
+ _registered_call_handle: Optional[int],
1744
+ ) -> cygrpc.IntegratedCall:
1745
+ """Creates a cygrpc.IntegratedCall.
1746
+
1747
+ Args:
1748
+ flags: An integer bitfield of call flags.
1749
+ method: The RPC method.
1750
+ host: A host string for the created call.
1751
+ deadline: A float to be the deadline of the created call or None if
1752
+ the call is to have an infinite deadline.
1753
+ metadata: The metadata for the call or None.
1754
+ credentials: A cygrpc.CallCredentials or None.
1755
+ operations: A sequence of sequences of cygrpc.Operations to be
1756
+ started on the call.
1757
+ event_handler: A behavior to call to handle the events resultant from
1758
+ the operations on the call.
1759
+ context: Context object for distributed tracing.
1760
+ _registered_call_handle: An int representing the call handle of the
1761
+ method, or None if the method is not registered.
1762
+
1763
+ Returns:
1764
+ A cygrpc.IntegratedCall with which to conduct an RPC.
1765
+ """
1766
+ operations_and_tags = tuple(
1767
+ (
1768
+ operation,
1769
+ event_handler,
1770
+ )
1771
+ for operation in operations
1772
+ )
1773
+ with state.lock:
1774
+ call = state.channel.integrated_call(
1775
+ flags,
1776
+ method,
1777
+ host,
1778
+ deadline,
1779
+ metadata,
1780
+ credentials,
1781
+ operations_and_tags,
1782
+ context,
1783
+ _registered_call_handle,
1784
+ )
1785
+ if state.managed_calls == 0:
1786
+ state.managed_calls = 1
1787
+ _run_channel_spin_thread(state)
1788
+ else:
1789
+ state.managed_calls += 1
1790
+ return call
1791
+
1792
+ return create
1793
+
1794
+
1795
+ class _ChannelConnectivityState(object):
1796
+ lock: threading.RLock
1797
+ channel: grpc.Channel
1798
+ polling: bool
1799
+ connectivity: grpc.ChannelConnectivity
1800
+ try_to_connect: bool
1801
+ # TODO(xuanwn): Refactor this: https://github.com/grpc/grpc/issues/31704
1802
+ callbacks_and_connectivities: List[
1803
+ Sequence[
1804
+ Union[
1805
+ Callable[[grpc.ChannelConnectivity], None],
1806
+ Optional[grpc.ChannelConnectivity],
1807
+ ]
1808
+ ]
1809
+ ]
1810
+ delivering: bool
1811
+
1812
+ def __init__(self, channel: grpc.Channel):
1813
+ self.lock = threading.RLock()
1814
+ self.channel = channel
1815
+ self.polling = False
1816
+ self.connectivity = None
1817
+ self.try_to_connect = False
1818
+ self.callbacks_and_connectivities = []
1819
+ self.delivering = False
1820
+
1821
+ def reset_postfork_child(self) -> None:
1822
+ self.polling = False
1823
+ self.connectivity = None
1824
+ self.try_to_connect = False
1825
+ self.callbacks_and_connectivities = []
1826
+ self.delivering = False
1827
+
1828
+
1829
+ def _deliveries(
1830
+ state: _ChannelConnectivityState,
1831
+ ) -> List[Callable[[grpc.ChannelConnectivity], None]]:
1832
+ callbacks_needing_update = []
1833
+ for callback_and_connectivity in state.callbacks_and_connectivities:
1834
+ callback, callback_connectivity = callback_and_connectivity
1835
+ if callback_connectivity is not state.connectivity:
1836
+ callbacks_needing_update.append(callback)
1837
+ callback_and_connectivity[1] = state.connectivity
1838
+ return callbacks_needing_update
1839
+
1840
+
1841
+ def _deliver(
1842
+ state: _ChannelConnectivityState,
1843
+ initial_connectivity: grpc.ChannelConnectivity,
1844
+ initial_callbacks: Sequence[Callable[[grpc.ChannelConnectivity], None]],
1845
+ ) -> None:
1846
+ connectivity = initial_connectivity
1847
+ callbacks = initial_callbacks
1848
+ while True:
1849
+ for callback in callbacks:
1850
+ cygrpc.block_if_fork_in_progress(state)
1851
+ try:
1852
+ callback(connectivity)
1853
+ except Exception: # pylint: disable=broad-except
1854
+ _LOGGER.exception(
1855
+ _CHANNEL_SUBSCRIPTION_CALLBACK_ERROR_LOG_MESSAGE
1856
+ )
1857
+ with state.lock:
1858
+ callbacks = _deliveries(state)
1859
+ if callbacks:
1860
+ connectivity = state.connectivity
1861
+ else:
1862
+ state.delivering = False
1863
+ return
1864
+
1865
+
1866
+ def _spawn_delivery(
1867
+ state: _ChannelConnectivityState,
1868
+ callbacks: Sequence[Callable[[grpc.ChannelConnectivity], None]],
1869
+ ) -> None:
1870
+ delivering_thread = cygrpc.ForkManagedThread(
1871
+ target=_deliver,
1872
+ args=(
1873
+ state,
1874
+ state.connectivity,
1875
+ callbacks,
1876
+ ),
1877
+ )
1878
+ delivering_thread.setDaemon(True)
1879
+ delivering_thread.start()
1880
+ state.delivering = True
1881
+
1882
+
1883
+ # NOTE(https://github.com/grpc/grpc/issues/3064): We'd rather not poll.
1884
+ def _poll_connectivity(
1885
+ state: _ChannelConnectivityState,
1886
+ channel: grpc.Channel,
1887
+ initial_try_to_connect: bool,
1888
+ ) -> None:
1889
+ try_to_connect = initial_try_to_connect
1890
+ connectivity = channel.check_connectivity_state(try_to_connect)
1891
+ with state.lock:
1892
+ state.connectivity = (
1893
+ _common.CYGRPC_CONNECTIVITY_STATE_TO_CHANNEL_CONNECTIVITY[
1894
+ connectivity
1895
+ ]
1896
+ )
1897
+ callbacks = tuple(
1898
+ callback for callback, _ in state.callbacks_and_connectivities
1899
+ )
1900
+ for callback_and_connectivity in state.callbacks_and_connectivities:
1901
+ callback_and_connectivity[1] = state.connectivity
1902
+ if callbacks:
1903
+ _spawn_delivery(state, callbacks)
1904
+ while True:
1905
+ event = channel.watch_connectivity_state(
1906
+ connectivity, time.time() + 0.2
1907
+ )
1908
+ cygrpc.block_if_fork_in_progress(state)
1909
+ with state.lock:
1910
+ if (
1911
+ not state.callbacks_and_connectivities
1912
+ and not state.try_to_connect
1913
+ ):
1914
+ state.polling = False
1915
+ state.connectivity = None
1916
+ break
1917
+ try_to_connect = state.try_to_connect
1918
+ state.try_to_connect = False
1919
+ if event.success or try_to_connect:
1920
+ connectivity = channel.check_connectivity_state(try_to_connect)
1921
+ with state.lock:
1922
+ state.connectivity = (
1923
+ _common.CYGRPC_CONNECTIVITY_STATE_TO_CHANNEL_CONNECTIVITY[
1924
+ connectivity
1925
+ ]
1926
+ )
1927
+ if not state.delivering:
1928
+ callbacks = _deliveries(state)
1929
+ if callbacks:
1930
+ _spawn_delivery(state, callbacks)
1931
+
1932
+
1933
+ def _subscribe(
1934
+ state: _ChannelConnectivityState,
1935
+ callback: Callable[[grpc.ChannelConnectivity], None],
1936
+ try_to_connect: bool,
1937
+ ) -> None:
1938
+ with state.lock:
1939
+ if not state.callbacks_and_connectivities and not state.polling:
1940
+ polling_thread = cygrpc.ForkManagedThread(
1941
+ target=_poll_connectivity,
1942
+ args=(state, state.channel, bool(try_to_connect)),
1943
+ )
1944
+ polling_thread.setDaemon(True)
1945
+ polling_thread.start()
1946
+ state.polling = True
1947
+ state.callbacks_and_connectivities.append([callback, None])
1948
+ elif not state.delivering and state.connectivity is not None:
1949
+ _spawn_delivery(state, (callback,))
1950
+ state.try_to_connect |= bool(try_to_connect)
1951
+ state.callbacks_and_connectivities.append(
1952
+ [callback, state.connectivity]
1953
+ )
1954
+ else:
1955
+ state.try_to_connect |= bool(try_to_connect)
1956
+ state.callbacks_and_connectivities.append([callback, None])
1957
+
1958
+
1959
+ def _unsubscribe(
1960
+ state: _ChannelConnectivityState,
1961
+ callback: Callable[[grpc.ChannelConnectivity], None],
1962
+ ) -> None:
1963
+ with state.lock:
1964
+ for index, (subscribed_callback, _unused_connectivity) in enumerate(
1965
+ state.callbacks_and_connectivities
1966
+ ):
1967
+ if callback == subscribed_callback:
1968
+ state.callbacks_and_connectivities.pop(index)
1969
+ break
1970
+
1971
+
1972
+ def _augment_options(
1973
+ base_options: Sequence[ChannelArgumentType],
1974
+ compression: Optional[grpc.Compression],
1975
+ ) -> Sequence[ChannelArgumentType]:
1976
+ compression_option = _compression.create_channel_option(compression)
1977
+ return (
1978
+ tuple(base_options)
1979
+ + compression_option
1980
+ + (
1981
+ (
1982
+ cygrpc.ChannelArgKey.primary_user_agent_string,
1983
+ _USER_AGENT,
1984
+ ),
1985
+ )
1986
+ )
1987
+
1988
+
1989
+ def _separate_channel_options(
1990
+ options: Sequence[ChannelArgumentType],
1991
+ ) -> Tuple[Sequence[ChannelArgumentType], Sequence[ChannelArgumentType]]:
1992
+ """Separates core channel options from Python channel options."""
1993
+ core_options = []
1994
+ python_options = []
1995
+ for pair in options:
1996
+ if (
1997
+ pair[0]
1998
+ == grpc.experimental.ChannelOptions.SingleThreadedUnaryStream
1999
+ ):
2000
+ python_options.append(pair)
2001
+ else:
2002
+ core_options.append(pair)
2003
+ return python_options, core_options
2004
+
2005
+
2006
+ class Channel(grpc.Channel):
2007
+ """A cygrpc.Channel-backed implementation of grpc.Channel."""
2008
+
2009
+ _single_threaded_unary_stream: bool
2010
+ _channel: cygrpc.Channel
2011
+ _call_state: _ChannelCallState
2012
+ _connectivity_state: _ChannelConnectivityState
2013
+ _target: str
2014
+ _registered_call_handles: Dict[str, int]
2015
+
2016
+ def __init__(
2017
+ self,
2018
+ target: str,
2019
+ options: Sequence[ChannelArgumentType],
2020
+ credentials: Optional[grpc.ChannelCredentials],
2021
+ compression: Optional[grpc.Compression],
2022
+ ):
2023
+ """Constructor.
2024
+
2025
+ Args:
2026
+ target: The target to which to connect.
2027
+ options: Configuration options for the channel.
2028
+ credentials: A cygrpc.ChannelCredentials or None.
2029
+ compression: An optional value indicating the compression method to be
2030
+ used over the lifetime of the channel.
2031
+ """
2032
+ python_options, core_options = _separate_channel_options(options)
2033
+ self._single_threaded_unary_stream = (
2034
+ _DEFAULT_SINGLE_THREADED_UNARY_STREAM
2035
+ )
2036
+ self._process_python_options(python_options)
2037
+ self._channel = cygrpc.Channel(
2038
+ _common.encode(target),
2039
+ _augment_options(core_options, compression),
2040
+ credentials,
2041
+ )
2042
+ self._target = target
2043
+ self._call_state = _ChannelCallState(self._channel)
2044
+ self._connectivity_state = _ChannelConnectivityState(self._channel)
2045
+ cygrpc.fork_register_channel(self)
2046
+ if cygrpc.g_gevent_activated:
2047
+ cygrpc.gevent_increment_channel_count()
2048
+
2049
+ def _get_registered_call_handle(self, method: str) -> int:
2050
+ """
2051
+ Get the registered call handle for a method.
2052
+
2053
+ This is a semi-private method. It is intended for use only by gRPC generated code.
2054
+
2055
+ This method is not thread-safe.
2056
+
2057
+ Args:
2058
+ method: Required, the method name for the RPC.
2059
+
2060
+ Returns:
2061
+ The registered call handle pointer in the form of a Python Long.
2062
+ """
2063
+ return self._channel.get_registered_call_handle(_common.encode(method))
2064
+
2065
+ def _process_python_options(
2066
+ self, python_options: Sequence[ChannelArgumentType]
2067
+ ) -> None:
2068
+ """Sets channel attributes according to python-only channel options."""
2069
+ for pair in python_options:
2070
+ if (
2071
+ pair[0]
2072
+ == grpc.experimental.ChannelOptions.SingleThreadedUnaryStream
2073
+ ):
2074
+ self._single_threaded_unary_stream = True
2075
+
2076
+ def subscribe(
2077
+ self,
2078
+ callback: Callable[[grpc.ChannelConnectivity], None],
2079
+ try_to_connect: Optional[bool] = None,
2080
+ ) -> None:
2081
+ _subscribe(self._connectivity_state, callback, try_to_connect)
2082
+
2083
+ def unsubscribe(
2084
+ self, callback: Callable[[grpc.ChannelConnectivity], None]
2085
+ ) -> None:
2086
+ _unsubscribe(self._connectivity_state, callback)
2087
+
2088
+ # pylint: disable=arguments-differ
2089
+ def unary_unary(
2090
+ self,
2091
+ method: str,
2092
+ request_serializer: Optional[SerializingFunction] = None,
2093
+ response_deserializer: Optional[DeserializingFunction] = None,
2094
+ _registered_method: Optional[bool] = False,
2095
+ ) -> grpc.UnaryUnaryMultiCallable:
2096
+ _registered_call_handle = None
2097
+ if _registered_method:
2098
+ _registered_call_handle = self._get_registered_call_handle(method)
2099
+ return _UnaryUnaryMultiCallable(
2100
+ self._channel,
2101
+ _channel_managed_call_management(self._call_state),
2102
+ _common.encode(method),
2103
+ _common.encode(self._target),
2104
+ request_serializer,
2105
+ response_deserializer,
2106
+ _registered_call_handle,
2107
+ )
2108
+
2109
+ # pylint: disable=arguments-differ
2110
+ def unary_stream(
2111
+ self,
2112
+ method: str,
2113
+ request_serializer: Optional[SerializingFunction] = None,
2114
+ response_deserializer: Optional[DeserializingFunction] = None,
2115
+ _registered_method: Optional[bool] = False,
2116
+ ) -> grpc.UnaryStreamMultiCallable:
2117
+ _registered_call_handle = None
2118
+ if _registered_method:
2119
+ _registered_call_handle = self._get_registered_call_handle(method)
2120
+ # NOTE(rbellevi): Benchmarks have shown that running a unary-stream RPC
2121
+ # on a single Python thread results in an appreciable speed-up. However,
2122
+ # due to slight differences in capability, the multi-threaded variant
2123
+ # remains the default.
2124
+ if self._single_threaded_unary_stream:
2125
+ return _SingleThreadedUnaryStreamMultiCallable(
2126
+ self._channel,
2127
+ _common.encode(method),
2128
+ _common.encode(self._target),
2129
+ request_serializer,
2130
+ response_deserializer,
2131
+ _registered_call_handle,
2132
+ )
2133
+ return _UnaryStreamMultiCallable(
2134
+ self._channel,
2135
+ _channel_managed_call_management(self._call_state),
2136
+ _common.encode(method),
2137
+ _common.encode(self._target),
2138
+ request_serializer,
2139
+ response_deserializer,
2140
+ _registered_call_handle,
2141
+ )
2142
+
2143
+ # pylint: disable=arguments-differ
2144
+ def stream_unary(
2145
+ self,
2146
+ method: str,
2147
+ request_serializer: Optional[SerializingFunction] = None,
2148
+ response_deserializer: Optional[DeserializingFunction] = None,
2149
+ _registered_method: Optional[bool] = False,
2150
+ ) -> grpc.StreamUnaryMultiCallable:
2151
+ _registered_call_handle = None
2152
+ if _registered_method:
2153
+ _registered_call_handle = self._get_registered_call_handle(method)
2154
+ return _StreamUnaryMultiCallable(
2155
+ self._channel,
2156
+ _channel_managed_call_management(self._call_state),
2157
+ _common.encode(method),
2158
+ _common.encode(self._target),
2159
+ request_serializer,
2160
+ response_deserializer,
2161
+ _registered_call_handle,
2162
+ )
2163
+
2164
+ # pylint: disable=arguments-differ
2165
+ def stream_stream(
2166
+ self,
2167
+ method: str,
2168
+ request_serializer: Optional[SerializingFunction] = None,
2169
+ response_deserializer: Optional[DeserializingFunction] = None,
2170
+ _registered_method: Optional[bool] = False,
2171
+ ) -> grpc.StreamStreamMultiCallable:
2172
+ _registered_call_handle = None
2173
+ if _registered_method:
2174
+ _registered_call_handle = self._get_registered_call_handle(method)
2175
+ return _StreamStreamMultiCallable(
2176
+ self._channel,
2177
+ _channel_managed_call_management(self._call_state),
2178
+ _common.encode(method),
2179
+ _common.encode(self._target),
2180
+ request_serializer,
2181
+ response_deserializer,
2182
+ _registered_call_handle,
2183
+ )
2184
+
2185
+ def _unsubscribe_all(self) -> None:
2186
+ state = self._connectivity_state
2187
+ if state:
2188
+ with state.lock:
2189
+ del state.callbacks_and_connectivities[:]
2190
+
2191
+ def _close(self) -> None:
2192
+ self._unsubscribe_all()
2193
+ self._channel.close(cygrpc.StatusCode.cancelled, "Channel closed!")
2194
+ cygrpc.fork_unregister_channel(self)
2195
+ if cygrpc.g_gevent_activated:
2196
+ cygrpc.gevent_decrement_channel_count()
2197
+
2198
+ def _close_on_fork(self) -> None:
2199
+ self._unsubscribe_all()
2200
+ self._channel.close_on_fork(
2201
+ cygrpc.StatusCode.cancelled, "Channel closed due to fork"
2202
+ )
2203
+
2204
+ def __enter__(self):
2205
+ return self
2206
+
2207
+ def __exit__(self, exc_type, exc_val, exc_tb):
2208
+ self._close()
2209
+ return False
2210
+
2211
+ def close(self) -> None:
2212
+ self._close()
2213
+
2214
+ def __del__(self):
2215
+ # TODO(https://github.com/grpc/grpc/issues/12531): Several releases
2216
+ # after 1.12 (1.16 or thereabouts?) add a "self._channel.close" call
2217
+ # here (or more likely, call self._close() here). We don't do this today
2218
+ # because many valid use cases today allow the channel to be deleted
2219
+ # immediately after stubs are created. After a sufficient period of time
2220
+ # has passed for all users to be trusted to freeze out to their channels
2221
+ # for as long as they are in use and to close them after using them,
2222
+ # then deletion of this grpc._channel.Channel instance can be made to
2223
+ # effect closure of the underlying cygrpc.Channel instance.
2224
+ try:
2225
+ self._unsubscribe_all()
2226
+ except: # pylint: disable=bare-except # noqa: E722
2227
+ # Exceptions in __del__ are ignored by Python anyway, but they can
2228
+ # keep spamming logs. Just silence them.
2229
+ pass
loan-advisor-agent/.venv/Lib/site-packages/grpc/_common.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 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
+ """Shared implementation."""
15
+
16
+ import logging
17
+ import time
18
+ from typing import Any, AnyStr, Callable, Optional, Union
19
+
20
+ import grpc
21
+ from grpc._cython import cygrpc
22
+ from grpc._typing import DeserializingFunction
23
+ from grpc._typing import SerializingFunction
24
+
25
+ _LOGGER = logging.getLogger(__name__)
26
+
27
+ CYGRPC_CONNECTIVITY_STATE_TO_CHANNEL_CONNECTIVITY = {
28
+ cygrpc.ConnectivityState.idle: grpc.ChannelConnectivity.IDLE,
29
+ cygrpc.ConnectivityState.connecting: grpc.ChannelConnectivity.CONNECTING,
30
+ cygrpc.ConnectivityState.ready: grpc.ChannelConnectivity.READY,
31
+ cygrpc.ConnectivityState.transient_failure: grpc.ChannelConnectivity.TRANSIENT_FAILURE,
32
+ cygrpc.ConnectivityState.shutdown: grpc.ChannelConnectivity.SHUTDOWN,
33
+ }
34
+
35
+ CYGRPC_STATUS_CODE_TO_STATUS_CODE = {
36
+ cygrpc.StatusCode.ok: grpc.StatusCode.OK,
37
+ cygrpc.StatusCode.cancelled: grpc.StatusCode.CANCELLED,
38
+ cygrpc.StatusCode.unknown: grpc.StatusCode.UNKNOWN,
39
+ cygrpc.StatusCode.invalid_argument: grpc.StatusCode.INVALID_ARGUMENT,
40
+ cygrpc.StatusCode.deadline_exceeded: grpc.StatusCode.DEADLINE_EXCEEDED,
41
+ cygrpc.StatusCode.not_found: grpc.StatusCode.NOT_FOUND,
42
+ cygrpc.StatusCode.already_exists: grpc.StatusCode.ALREADY_EXISTS,
43
+ cygrpc.StatusCode.permission_denied: grpc.StatusCode.PERMISSION_DENIED,
44
+ cygrpc.StatusCode.unauthenticated: grpc.StatusCode.UNAUTHENTICATED,
45
+ cygrpc.StatusCode.resource_exhausted: grpc.StatusCode.RESOURCE_EXHAUSTED,
46
+ cygrpc.StatusCode.failed_precondition: grpc.StatusCode.FAILED_PRECONDITION,
47
+ cygrpc.StatusCode.aborted: grpc.StatusCode.ABORTED,
48
+ cygrpc.StatusCode.out_of_range: grpc.StatusCode.OUT_OF_RANGE,
49
+ cygrpc.StatusCode.unimplemented: grpc.StatusCode.UNIMPLEMENTED,
50
+ cygrpc.StatusCode.internal: grpc.StatusCode.INTERNAL,
51
+ cygrpc.StatusCode.unavailable: grpc.StatusCode.UNAVAILABLE,
52
+ cygrpc.StatusCode.data_loss: grpc.StatusCode.DATA_LOSS,
53
+ }
54
+ STATUS_CODE_TO_CYGRPC_STATUS_CODE = {
55
+ grpc_code: cygrpc_code
56
+ for cygrpc_code, grpc_code in CYGRPC_STATUS_CODE_TO_STATUS_CODE.items()
57
+ }
58
+
59
+ MAXIMUM_WAIT_TIMEOUT = 0.1
60
+
61
+ _ERROR_MESSAGE_PORT_BINDING_FAILED = (
62
+ "Failed to bind to address %s; set "
63
+ "GRPC_VERBOSITY=debug environment variable to see detailed error message."
64
+ )
65
+
66
+
67
+ def encode(s: AnyStr) -> bytes:
68
+ if isinstance(s, bytes):
69
+ return s
70
+ return s.encode("utf8")
71
+
72
+
73
+ def decode(b: AnyStr) -> str:
74
+ if isinstance(b, bytes):
75
+ return b.decode("utf-8", "replace")
76
+ return b
77
+
78
+
79
+ def _transform(
80
+ message: Any,
81
+ transformer: Union[SerializingFunction, DeserializingFunction, None],
82
+ exception_message: str,
83
+ ) -> Any:
84
+ if transformer is None:
85
+ return message
86
+ try:
87
+ return transformer(message)
88
+ except Exception: # pylint: disable=broad-except
89
+ _LOGGER.exception(exception_message)
90
+ return None
91
+
92
+
93
+ def serialize(message: Any, serializer: Optional[SerializingFunction]) -> bytes:
94
+ return _transform(message, serializer, "Exception serializing message!")
95
+
96
+
97
+ def deserialize(
98
+ serialized_message: bytes, deserializer: Optional[DeserializingFunction]
99
+ ) -> Any:
100
+ return _transform(
101
+ serialized_message, deserializer, "Exception deserializing message!"
102
+ )
103
+
104
+
105
+ def fully_qualified_method(group: str, method: str) -> str:
106
+ return "/{}/{}".format(group, method)
107
+
108
+
109
+ def _wait_once(
110
+ wait_fn: Callable[..., bool],
111
+ timeout: float,
112
+ spin_cb: Optional[Callable[[], None]],
113
+ ):
114
+ wait_fn(timeout=timeout)
115
+ if spin_cb is not None:
116
+ spin_cb()
117
+
118
+
119
+ def wait(
120
+ wait_fn: Callable[..., bool],
121
+ wait_complete_fn: Callable[[], bool],
122
+ timeout: Optional[float] = None,
123
+ spin_cb: Optional[Callable[[], None]] = None,
124
+ ) -> bool:
125
+ """Blocks waiting for an event without blocking the thread indefinitely.
126
+
127
+ See https://github.com/grpc/grpc/issues/19464 for full context. CPython's
128
+ `threading.Event.wait` and `threading.Condition.wait` methods, if invoked
129
+ without a timeout kwarg, may block the calling thread indefinitely. If the
130
+ call is made from the main thread, this means that signal handlers may not
131
+ run for an arbitrarily long period of time.
132
+
133
+ This wrapper calls the supplied wait function with an arbitrary short
134
+ timeout to ensure that no signal handler has to wait longer than
135
+ MAXIMUM_WAIT_TIMEOUT before executing.
136
+
137
+ Args:
138
+ wait_fn: A callable acceptable a single float-valued kwarg named
139
+ `timeout`. This function is expected to be one of `threading.Event.wait`
140
+ or `threading.Condition.wait`.
141
+ wait_complete_fn: A callable taking no arguments and returning a bool.
142
+ When this function returns true, it indicates that waiting should cease.
143
+ timeout: An optional float-valued number of seconds after which the wait
144
+ should cease.
145
+ spin_cb: An optional Callable taking no arguments and returning nothing.
146
+ This callback will be called on each iteration of the spin. This may be
147
+ used for, e.g. work related to forking.
148
+
149
+ Returns:
150
+ True if a timeout was supplied and it was reached. False otherwise.
151
+ """
152
+ if timeout is None:
153
+ while not wait_complete_fn():
154
+ _wait_once(wait_fn, MAXIMUM_WAIT_TIMEOUT, spin_cb)
155
+ else:
156
+ end = time.time() + timeout
157
+ while not wait_complete_fn():
158
+ remaining = min(end - time.time(), MAXIMUM_WAIT_TIMEOUT)
159
+ if remaining < 0:
160
+ return True
161
+ _wait_once(wait_fn, remaining, spin_cb)
162
+ return False
163
+
164
+
165
+ def validate_port_binding_result(address: str, port: int) -> int:
166
+ """Validates if the port binding succeed.
167
+
168
+ If the port returned by Core is 0, the binding is failed. However, in that
169
+ case, the Core API doesn't return a detailed failing reason. The best we
170
+ can do is raising an exception to prevent further confusion.
171
+
172
+ Args:
173
+ address: The address string to be bound.
174
+ port: An int returned by core
175
+ """
176
+ if port == 0:
177
+ # The Core API doesn't return a failure message. The best we can do
178
+ # is raising an exception to prevent further confusion.
179
+ raise RuntimeError(_ERROR_MESSAGE_PORT_BINDING_FAILED % address)
180
+ return port
loan-advisor-agent/.venv/Lib/site-packages/grpc/_compression.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2019 The 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
+
15
+ from __future__ import annotations
16
+
17
+ from typing import Optional
18
+
19
+ import grpc
20
+ from grpc._cython import cygrpc
21
+ from grpc._typing import MetadataType
22
+
23
+ NoCompression = cygrpc.CompressionAlgorithm.none
24
+ Deflate = cygrpc.CompressionAlgorithm.deflate
25
+ Gzip = cygrpc.CompressionAlgorithm.gzip
26
+
27
+ _METADATA_STRING_MAPPING = {
28
+ NoCompression: "identity",
29
+ Deflate: "deflate",
30
+ Gzip: "gzip",
31
+ }
32
+
33
+
34
+ def _compression_algorithm_to_metadata_value(
35
+ compression: grpc.Compression,
36
+ ) -> str:
37
+ return _METADATA_STRING_MAPPING[compression]
38
+
39
+
40
+ def compression_algorithm_to_metadata(compression: grpc.Compression):
41
+ return (
42
+ cygrpc.GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY,
43
+ _compression_algorithm_to_metadata_value(compression),
44
+ )
45
+
46
+
47
+ def create_channel_option(compression: Optional[grpc.Compression]):
48
+ return (
49
+ ((cygrpc.GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM, int(compression)),)
50
+ if compression
51
+ else ()
52
+ )
53
+
54
+
55
+ def augment_metadata(
56
+ metadata: Optional[MetadataType], compression: Optional[grpc.Compression]
57
+ ):
58
+ if not metadata and not compression:
59
+ return None
60
+ base_metadata = tuple(metadata) if metadata else ()
61
+ compression_metadata = (
62
+ (compression_algorithm_to_metadata(compression),) if compression else ()
63
+ )
64
+ return base_metadata + compression_metadata
65
+
66
+
67
+ __all__ = (
68
+ "Deflate",
69
+ "Gzip",
70
+ "NoCompression",
71
+ )
loan-advisor-agent/.venv/Lib/site-packages/grpc/_cython/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2015 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.
loan-advisor-agent/.venv/Lib/site-packages/grpc/_cython/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (189 Bytes). View file
 
loan-advisor-agent/.venv/Lib/site-packages/grpc/_cython/_credentials/roots.pem ADDED
The diff for this file is too large to render. See raw diff
 
loan-advisor-agent/.venv/Lib/site-packages/grpc/_cython/_cygrpc/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2015 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.
loan-advisor-agent/.venv/Lib/site-packages/grpc/_cython/_cygrpc/private_key_signing/private_key_signer_py_wrapper.cc ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //
2
+ //
3
+ // Copyright 2026 gRPC authors.
4
+ //
5
+ // Licensed under the Apache License, Version 2.0 (the "License");
6
+ // you may not use this file except in compliance with the License.
7
+ // You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing, software
12
+ // distributed under the License is distributed on an "AS IS" BASIS,
13
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ // See the License for the specific language governing permissions and
15
+ // limitations under the License.
16
+ //
17
+ //
18
+
19
+ #include "src/python/grpcio/grpc/_cython/_cygrpc/private_key_signing/private_key_signer_py_wrapper.h"
20
+
21
+ #include <grpc/support/log.h>
22
+
23
+ #include <memory>
24
+
25
+ #include "Python.h"
26
+ #include "grpc/private_key_signer.h"
27
+ #include "absl/status/status.h"
28
+
29
+ namespace grpc_python {
30
+
31
+ std::shared_ptr<grpc_core::PrivateKeySigner> PrivateKeySignerPyWrapper::Create(
32
+ PrivateKeySignerPyWrapper::SignWrapperForPy sign_py_wrapper,
33
+ PyObject* py_user_sign_fn, PyObject* destroy_event) {
34
+ PyGILState_STATE state = PyGILState_Ensure();
35
+ Py_INCREF(py_user_sign_fn);
36
+ Py_INCREF(destroy_event);
37
+ PyGILState_Release(state);
38
+ return std::make_shared<PrivateKeySignerPyWrapper>(
39
+ sign_py_wrapper, py_user_sign_fn, destroy_event);
40
+ }
41
+
42
+ PrivateKeySignerPyWrapper::~PrivateKeySignerPyWrapper() {
43
+ PyGILState_STATE state = PyGILState_Ensure();
44
+ Py_DECREF(static_cast<PyObject*>(py_user_sign_fn_));
45
+ // Python will stay alive until this event is set
46
+ PyObject* result = PyObject_CallMethod(destroy_event_, "set", "()");
47
+ // crash if result is nullptr? - discussing
48
+ Py_XDECREF(result);
49
+ PyGILState_Release(state);
50
+ }
51
+
52
+ std::variant<absl::StatusOr<std::string>,
53
+ std::shared_ptr<grpc_core::PrivateKeySigner::AsyncSigningHandle>>
54
+ PrivateKeySignerPyWrapper::Sign(absl::string_view data_to_sign,
55
+ SignatureAlgorithm signature_algorithm,
56
+ OnSignComplete on_sign_complete) {
57
+ auto completion_context =
58
+ std::make_shared<CompletionContext>(std::move(on_sign_complete));
59
+
60
+ PrivateKeySignerPyWrapperResult result = sign_py_wrapper_(
61
+ data_to_sign, signature_algorithm, py_user_sign_fn_, completion_context);
62
+ if (result.is_sync) {
63
+ return result.sync_result;
64
+ } else {
65
+ auto handle = std::make_shared<AsyncSigningHandlePyWrapper>(
66
+ result.async_result.cancel_wrapper,
67
+ result.async_result.py_user_cancel_fn, std::move(completion_context));
68
+ return handle;
69
+ }
70
+ }
71
+
72
+ void PrivateKeySignerPyWrapper::Cancel(
73
+ std::shared_ptr<AsyncSigningHandle> handle) {
74
+ if (handle == nullptr) return;
75
+ auto handle_impl =
76
+ std::static_pointer_cast<AsyncSigningHandlePyWrapper>(handle);
77
+ handle_impl->Cancel();
78
+ }
79
+
80
+ PrivateKeySignerPyWrapper::AsyncSigningHandlePyWrapper::
81
+ ~AsyncSigningHandlePyWrapper() {
82
+ PyGILState_STATE state = PyGILState_Ensure();
83
+ Py_DECREF(py_user_cancel_fn_);
84
+ PyGILState_Release(state);
85
+ }
86
+
87
+ void PrivateKeySignerPyWrapper::AsyncSigningHandlePyWrapper::Cancel() {
88
+ if (cancel_py_wrapper_ != nullptr && py_user_cancel_fn_ != nullptr) {
89
+ cancel_py_wrapper_(py_user_cancel_fn_);
90
+ }
91
+ completion_context_.reset();
92
+ }
93
+
94
+ std::string MakeStringForCython(const char* inp, size_t size) {
95
+ return std::string(inp, size);
96
+ }
97
+
98
+ std::string MakeStringForCython(const char* inp) { return std::string(inp); }
99
+
100
+ } // namespace grpc_python
loan-advisor-agent/.venv/Lib/site-packages/grpc/_cython/_cygrpc/private_key_signing/private_key_signer_py_wrapper.h ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //
2
+ //
3
+ // Copyright 2026 gRPC authors.
4
+ //
5
+ // Licensed under the Apache License, Version 2.0 (the "License");
6
+ // you may not use this file except in compliance with the License.
7
+ // You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing, software
12
+ // distributed under the License is distributed on an "AS IS" BASIS,
13
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ // See the License for the specific language governing permissions and
15
+ // limitations under the License.
16
+ //
17
+ //
18
+
19
+ #ifndef GRPC_PRIVATE_KEY_SIGNER_PY_WRAPPER_H
20
+ #define GRPC_PRIVATE_KEY_SIGNER_PY_WRAPPER_H
21
+
22
+ #include <memory>
23
+ #include <string>
24
+ #include <variant>
25
+
26
+ #include "Python.h"
27
+ #include "grpc/private_key_signer.h"
28
+ #include "absl/status/statusor.h"
29
+
30
+ namespace grpc_python {
31
+
32
+ // An implementation of PrivateKeySigner for interop with Python.
33
+ // It is thread-safe to call Sign on this class.
34
+ class PrivateKeySignerPyWrapper final
35
+ : public grpc_core::PrivateKeySigner,
36
+ public std::enable_shared_from_this<PrivateKeySignerPyWrapper> {
37
+ public:
38
+ // A C-style callback for the PrivateKeySigner Cancel function.
39
+ typedef void (*CancelWrapperForPy)(PyObject* cancel_data);
40
+
41
+ // A wrapper for holding the user's Python cancellation function as well as
42
+ // the C callback that can call that function.
43
+ struct AsyncResult {
44
+ CancelWrapperForPy cancel_wrapper;
45
+ PyObject* py_user_cancel_fn;
46
+ };
47
+
48
+ // The result of the sign call for interop between Cython and C. Is converted
49
+ // to the C++ std::variant Sign result.
50
+ struct PrivateKeySignerPyWrapperResult {
51
+ absl::StatusOr<std::string> sync_result;
52
+ AsyncResult async_result;
53
+ bool is_sync;
54
+ };
55
+
56
+ // The context needed for calling the Completion callback at the Cython layer.
57
+ // Wrapped in regular Python and passed to the user for them to be able to
58
+ // call the proper on_complete callback passed out by gRPC Core.
59
+ class CompletionContext final {
60
+ public:
61
+ explicit CompletionContext(
62
+ grpc_core::PrivateKeySigner::OnSignComplete on_complete)
63
+ : on_complete_(std::move(on_complete)) {}
64
+ void OnComplete(absl::StatusOr<std::string> result) {
65
+ on_complete_(std::move(result));
66
+ };
67
+
68
+ private:
69
+ // Holds the completion function passed out by gRPC Core.
70
+ grpc_core::PrivateKeySigner::OnSignComplete on_complete_;
71
+ };
72
+
73
+ // A C-Style function for the Cython layer to call when the gRPC C++ layer
74
+ // calls `Sign` on the `PrivateKeySignerPyWrapper`.
75
+ typedef PrivateKeySignerPyWrapperResult (*SignWrapperForPy)(
76
+ absl::string_view data_to_sign,
77
+ grpc_core::PrivateKeySigner::SignatureAlgorithm signature_algorithm,
78
+ PyObject* py_user_sign_fn,
79
+ std::weak_ptr<CompletionContext> completion_context);
80
+
81
+ class AsyncSigningHandlePyWrapper
82
+ : public grpc_core::PrivateKeySigner::AsyncSigningHandle {
83
+ public:
84
+ AsyncSigningHandlePyWrapper(
85
+ PrivateKeySignerPyWrapper::CancelWrapperForPy cancel_py_wrapper,
86
+ PyObject* py_user_cancel_fn,
87
+ std::shared_ptr<PrivateKeySignerPyWrapper::CompletionContext>
88
+ completion_context)
89
+ : cancel_py_wrapper_(cancel_py_wrapper),
90
+ py_user_cancel_fn_(py_user_cancel_fn),
91
+ completion_context_(std::move(completion_context)) {}
92
+ // This will decrememnt the py_user_cancel_fn on object destruction
93
+ ~AsyncSigningHandlePyWrapper() override;
94
+ void Cancel();
95
+
96
+ private:
97
+ // This is a function provided by the Cython implementation of Private Key
98
+ // Offloading.
99
+ PrivateKeySignerPyWrapper::CancelWrapperForPy cancel_py_wrapper_;
100
+ // This will hold the Python callable object
101
+ PyObject* py_user_cancel_fn_;
102
+ std::shared_ptr<PrivateKeySignerPyWrapper::CompletionContext>
103
+ completion_context_;
104
+ };
105
+
106
+ // The entry point for Cython to build a PrivateKeySigner.
107
+ static std::shared_ptr<grpc_core::PrivateKeySigner> Create(
108
+ SignWrapperForPy sign, PyObject* py_user_sign_fn,
109
+ PyObject* destroy_event);
110
+
111
+ PrivateKeySignerPyWrapper(SignWrapperForPy sign_py_wrapper,
112
+ PyObject* py_user_sign_fn, PyObject* destroy_event)
113
+ : sign_py_wrapper_(sign_py_wrapper),
114
+ py_user_sign_fn_(py_user_sign_fn),
115
+ destroy_event_(destroy_event) {}
116
+ ~PrivateKeySignerPyWrapper() override;
117
+
118
+ std::variant<absl::StatusOr<std::string>, std::shared_ptr<AsyncSigningHandle>>
119
+ Sign(absl::string_view data_to_sign, SignatureAlgorithm signature_algorithm,
120
+ OnSignComplete on_sign_complete) override;
121
+
122
+ void Cancel(std::shared_ptr<AsyncSigningHandle> handle) override;
123
+
124
+ private:
125
+ // This is a function provided by the Cython implementation of Private Key
126
+ // Offloading.
127
+ SignWrapperForPy sign_py_wrapper_;
128
+ // This will hold the Python callable object
129
+ PyObject* py_user_sign_fn_;
130
+ // An event to make sure the python interpreter stays alive until this
131
+ // destruction is complete
132
+ PyObject* destroy_event_;
133
+ };
134
+
135
+ // Python cannot call the string constructor directly in Cython. The string
136
+ // constructor can throw exceptions, so the generated C code from Cython
137
+ // contains try/catch statements. This fails our strict builds. Instead, we can
138
+ // just construct them here and pass them down.
139
+ std::string MakeStringForCython(const char* inp);
140
+ std::string MakeStringForCython(const char* inp, size_t size);
141
+ } // namespace grpc_python
142
+
143
+ #endif // GRPC_PRIVATE_KEY_SIGNER_PY_WRAPPER_H
loan-advisor-agent/.venv/Lib/site-packages/grpc/_cython/cygrpc.cp312-win_amd64.pyd ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:37c9cdf231205b9c4b942946ef686e65e6b6c31fd97b72ad51aed4e699b6bfba
3
+ size 10800128
loan-advisor-agent/.venv/Lib/site-packages/grpc/_grpcio_metadata.py ADDED
@@ -0,0 +1 @@
 
 
1
+ __version__ = """1.80.0"""
loan-advisor-agent/.venv/Lib/site-packages/grpc/_interceptor.py ADDED
@@ -0,0 +1,809 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 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
+ """Implementation of gRPC Python interceptors."""
15
+
16
+ import collections
17
+ import sys
18
+ import types
19
+ from typing import Any, Callable, Optional, Sequence, Tuple, Union
20
+
21
+ import grpc
22
+
23
+ from ._typing import DeserializingFunction
24
+ from ._typing import DoneCallbackType
25
+ from ._typing import MetadataType
26
+ from ._typing import RequestIterableType
27
+ from ._typing import SerializingFunction
28
+
29
+
30
+ class _ServicePipeline(object):
31
+ interceptors: Tuple[grpc.ServerInterceptor]
32
+
33
+ def __init__(self, interceptors: Sequence[grpc.ServerInterceptor]):
34
+ self.interceptors = tuple(interceptors)
35
+
36
+ def _continuation(self, thunk: Callable, index: int) -> Callable:
37
+ return lambda context: self._intercept_at(thunk, index, context)
38
+
39
+ def _intercept_at(
40
+ self, thunk: Callable, index: int, context: grpc.HandlerCallDetails
41
+ ) -> grpc.RpcMethodHandler:
42
+ if index < len(self.interceptors):
43
+ interceptor = self.interceptors[index]
44
+ thunk = self._continuation(thunk, index + 1)
45
+ return interceptor.intercept_service(thunk, context)
46
+ return thunk(context)
47
+
48
+ def execute(
49
+ self, thunk: Callable, context: grpc.HandlerCallDetails
50
+ ) -> grpc.RpcMethodHandler:
51
+ return self._intercept_at(thunk, 0, context)
52
+
53
+
54
+ def service_pipeline(
55
+ interceptors: Optional[Sequence[grpc.ServerInterceptor]],
56
+ ) -> Optional[_ServicePipeline]:
57
+ return _ServicePipeline(interceptors) if interceptors else None
58
+
59
+
60
+ class _ClientCallDetails(
61
+ collections.namedtuple(
62
+ "_ClientCallDetails",
63
+ (
64
+ "method",
65
+ "timeout",
66
+ "metadata",
67
+ "credentials",
68
+ "wait_for_ready",
69
+ "compression",
70
+ ),
71
+ ),
72
+ grpc.ClientCallDetails,
73
+ ):
74
+ pass
75
+
76
+
77
+ def _unwrap_client_call_details(
78
+ call_details: grpc.ClientCallDetails,
79
+ default_details: grpc.ClientCallDetails,
80
+ ) -> Tuple[
81
+ str, float, MetadataType, grpc.CallCredentials, bool, grpc.Compression
82
+ ]:
83
+ try:
84
+ method = call_details.method # pytype: disable=attribute-error
85
+ except AttributeError:
86
+ method = default_details.method # pytype: disable=attribute-error
87
+
88
+ try:
89
+ timeout = call_details.timeout # pytype: disable=attribute-error
90
+ except AttributeError:
91
+ timeout = default_details.timeout # pytype: disable=attribute-error
92
+
93
+ try:
94
+ metadata = call_details.metadata # pytype: disable=attribute-error
95
+ except AttributeError:
96
+ metadata = default_details.metadata # pytype: disable=attribute-error
97
+
98
+ try:
99
+ credentials = (
100
+ call_details.credentials
101
+ ) # pytype: disable=attribute-error
102
+ except AttributeError:
103
+ credentials = (
104
+ default_details.credentials
105
+ ) # pytype: disable=attribute-error
106
+
107
+ try:
108
+ wait_for_ready = (
109
+ call_details.wait_for_ready
110
+ ) # pytype: disable=attribute-error
111
+ except AttributeError:
112
+ wait_for_ready = (
113
+ default_details.wait_for_ready
114
+ ) # pytype: disable=attribute-error
115
+
116
+ try:
117
+ compression = (
118
+ call_details.compression
119
+ ) # pytype: disable=attribute-error
120
+ except AttributeError:
121
+ compression = (
122
+ default_details.compression
123
+ ) # pytype: disable=attribute-error
124
+
125
+ return method, timeout, metadata, credentials, wait_for_ready, compression
126
+
127
+
128
+ class _FailureOutcome(
129
+ grpc.RpcError, grpc.Future, grpc.Call
130
+ ): # pylint: disable=too-many-ancestors
131
+ _exception: Exception
132
+ _traceback: types.TracebackType
133
+
134
+ def __init__(self, exception: Exception, traceback: types.TracebackType):
135
+ super(_FailureOutcome, self).__init__()
136
+ self._exception = exception
137
+ self._traceback = traceback
138
+
139
+ def initial_metadata(self) -> Optional[MetadataType]:
140
+ return None
141
+
142
+ def trailing_metadata(self) -> Optional[MetadataType]:
143
+ return None
144
+
145
+ def code(self) -> Optional[grpc.StatusCode]:
146
+ return grpc.StatusCode.INTERNAL
147
+
148
+ def details(self) -> Optional[str]:
149
+ return "Exception raised while intercepting the RPC"
150
+
151
+ def cancel(self) -> bool:
152
+ return False
153
+
154
+ def cancelled(self) -> bool:
155
+ return False
156
+
157
+ def is_active(self) -> bool:
158
+ return False
159
+
160
+ def time_remaining(self) -> Optional[float]:
161
+ return None
162
+
163
+ def running(self) -> bool:
164
+ return False
165
+
166
+ def done(self) -> bool:
167
+ return True
168
+
169
+ def result(self, ignored_timeout: Optional[float] = None):
170
+ raise self._exception
171
+
172
+ def exception(
173
+ self, ignored_timeout: Optional[float] = None
174
+ ) -> Optional[Exception]:
175
+ return self._exception
176
+
177
+ def traceback(
178
+ self, ignored_timeout: Optional[float] = None
179
+ ) -> Optional[types.TracebackType]:
180
+ return self._traceback
181
+
182
+ def add_callback(self, unused_callback) -> bool:
183
+ return False
184
+
185
+ def add_done_callback(self, fn: DoneCallbackType) -> None:
186
+ fn(self)
187
+
188
+ def __iter__(self):
189
+ return self
190
+
191
+ def __next__(self):
192
+ raise self._exception
193
+
194
+ def next(self):
195
+ return self.__next__()
196
+
197
+
198
+ class _UnaryOutcome(grpc.Call, grpc.Future):
199
+ _response: Any
200
+ _call: grpc.Call
201
+
202
+ def __init__(self, response: Any, call: grpc.Call):
203
+ self._response = response
204
+ self._call = call
205
+
206
+ def initial_metadata(self) -> Optional[MetadataType]:
207
+ return self._call.initial_metadata()
208
+
209
+ def trailing_metadata(self) -> Optional[MetadataType]:
210
+ return self._call.trailing_metadata()
211
+
212
+ def code(self) -> Optional[grpc.StatusCode]:
213
+ return self._call.code()
214
+
215
+ def details(self) -> Optional[str]:
216
+ return self._call.details()
217
+
218
+ def is_active(self) -> bool:
219
+ return self._call.is_active()
220
+
221
+ def time_remaining(self) -> Optional[float]:
222
+ return self._call.time_remaining()
223
+
224
+ def cancel(self) -> bool:
225
+ return self._call.cancel()
226
+
227
+ def add_callback(self, callback) -> bool:
228
+ return self._call.add_callback(callback)
229
+
230
+ def cancelled(self) -> bool:
231
+ return False
232
+
233
+ def running(self) -> bool:
234
+ return False
235
+
236
+ def done(self) -> bool:
237
+ return True
238
+
239
+ def result(self, ignored_timeout: Optional[float] = None):
240
+ return self._response
241
+
242
+ def exception(self, ignored_timeout: Optional[float] = None):
243
+ return None
244
+
245
+ def traceback(self, ignored_timeout: Optional[float] = None):
246
+ return None
247
+
248
+ def add_done_callback(self, fn: DoneCallbackType) -> None:
249
+ fn(self)
250
+
251
+
252
+ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable):
253
+ _thunk: Callable
254
+ _method: str
255
+ _interceptor: grpc.UnaryUnaryClientInterceptor
256
+
257
+ def __init__(
258
+ self,
259
+ thunk: Callable,
260
+ method: str,
261
+ interceptor: grpc.UnaryUnaryClientInterceptor,
262
+ ):
263
+ self._thunk = thunk
264
+ self._method = method
265
+ self._interceptor = interceptor
266
+
267
+ def __call__(
268
+ self,
269
+ request: Any,
270
+ timeout: Optional[float] = None,
271
+ metadata: Optional[MetadataType] = None,
272
+ credentials: Optional[grpc.CallCredentials] = None,
273
+ wait_for_ready: Optional[bool] = None,
274
+ compression: Optional[grpc.Compression] = None,
275
+ ) -> Any:
276
+ response, ignored_call = self._with_call(
277
+ request,
278
+ timeout=timeout,
279
+ metadata=metadata,
280
+ credentials=credentials,
281
+ wait_for_ready=wait_for_ready,
282
+ compression=compression,
283
+ )
284
+ return response
285
+
286
+ def _with_call(
287
+ self,
288
+ request: Any,
289
+ timeout: Optional[float] = None,
290
+ metadata: Optional[MetadataType] = None,
291
+ credentials: Optional[grpc.CallCredentials] = None,
292
+ wait_for_ready: Optional[bool] = None,
293
+ compression: Optional[grpc.Compression] = None,
294
+ ) -> Tuple[Any, grpc.Call]:
295
+ client_call_details = _ClientCallDetails(
296
+ self._method,
297
+ timeout,
298
+ metadata,
299
+ credentials,
300
+ wait_for_ready,
301
+ compression,
302
+ )
303
+
304
+ def continuation(new_details, request):
305
+ (
306
+ new_method,
307
+ new_timeout,
308
+ new_metadata,
309
+ new_credentials,
310
+ new_wait_for_ready,
311
+ new_compression,
312
+ ) = _unwrap_client_call_details(new_details, client_call_details)
313
+ try:
314
+ response, call = self._thunk(new_method).with_call(
315
+ request,
316
+ timeout=new_timeout,
317
+ metadata=new_metadata,
318
+ credentials=new_credentials,
319
+ wait_for_ready=new_wait_for_ready,
320
+ compression=new_compression,
321
+ )
322
+ return _UnaryOutcome(response, call)
323
+ except grpc.RpcError as rpc_error:
324
+ return rpc_error
325
+ except Exception as exception: # pylint:disable=broad-except
326
+ return _FailureOutcome(exception, sys.exc_info()[2])
327
+
328
+ call = self._interceptor.intercept_unary_unary(
329
+ continuation, client_call_details, request
330
+ )
331
+ return call.result(), call
332
+
333
+ def with_call(
334
+ self,
335
+ request: Any,
336
+ timeout: Optional[float] = None,
337
+ metadata: Optional[MetadataType] = None,
338
+ credentials: Optional[grpc.CallCredentials] = None,
339
+ wait_for_ready: Optional[bool] = None,
340
+ compression: Optional[grpc.Compression] = None,
341
+ ) -> Tuple[Any, grpc.Call]:
342
+ return self._with_call(
343
+ request,
344
+ timeout=timeout,
345
+ metadata=metadata,
346
+ credentials=credentials,
347
+ wait_for_ready=wait_for_ready,
348
+ compression=compression,
349
+ )
350
+
351
+ def future(
352
+ self,
353
+ request: Any,
354
+ timeout: Optional[float] = None,
355
+ metadata: Optional[MetadataType] = None,
356
+ credentials: Optional[grpc.CallCredentials] = None,
357
+ wait_for_ready: Optional[bool] = None,
358
+ compression: Optional[grpc.Compression] = None,
359
+ ) -> Any:
360
+ client_call_details = _ClientCallDetails(
361
+ self._method,
362
+ timeout,
363
+ metadata,
364
+ credentials,
365
+ wait_for_ready,
366
+ compression,
367
+ )
368
+
369
+ def continuation(new_details, request):
370
+ (
371
+ new_method,
372
+ new_timeout,
373
+ new_metadata,
374
+ new_credentials,
375
+ new_wait_for_ready,
376
+ new_compression,
377
+ ) = _unwrap_client_call_details(new_details, client_call_details)
378
+ return self._thunk(new_method).future(
379
+ request,
380
+ timeout=new_timeout,
381
+ metadata=new_metadata,
382
+ credentials=new_credentials,
383
+ wait_for_ready=new_wait_for_ready,
384
+ compression=new_compression,
385
+ )
386
+
387
+ try:
388
+ return self._interceptor.intercept_unary_unary(
389
+ continuation, client_call_details, request
390
+ )
391
+ except Exception as exception: # pylint:disable=broad-except
392
+ return _FailureOutcome(exception, sys.exc_info()[2])
393
+
394
+
395
+ class _UnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable):
396
+ _thunk: Callable
397
+ _method: str
398
+ _interceptor: grpc.UnaryStreamClientInterceptor
399
+
400
+ def __init__(
401
+ self,
402
+ thunk: Callable,
403
+ method: str,
404
+ interceptor: grpc.UnaryStreamClientInterceptor,
405
+ ):
406
+ self._thunk = thunk
407
+ self._method = method
408
+ self._interceptor = interceptor
409
+
410
+ def __call__(
411
+ self,
412
+ request: Any,
413
+ timeout: Optional[float] = None,
414
+ metadata: Optional[MetadataType] = None,
415
+ credentials: Optional[grpc.CallCredentials] = None,
416
+ wait_for_ready: Optional[bool] = None,
417
+ compression: Optional[grpc.Compression] = None,
418
+ ):
419
+ client_call_details = _ClientCallDetails(
420
+ self._method,
421
+ timeout,
422
+ metadata,
423
+ credentials,
424
+ wait_for_ready,
425
+ compression,
426
+ )
427
+
428
+ def continuation(new_details, request):
429
+ (
430
+ new_method,
431
+ new_timeout,
432
+ new_metadata,
433
+ new_credentials,
434
+ new_wait_for_ready,
435
+ new_compression,
436
+ ) = _unwrap_client_call_details(new_details, client_call_details)
437
+ return self._thunk(new_method)(
438
+ request,
439
+ timeout=new_timeout,
440
+ metadata=new_metadata,
441
+ credentials=new_credentials,
442
+ wait_for_ready=new_wait_for_ready,
443
+ compression=new_compression,
444
+ )
445
+
446
+ try:
447
+ return self._interceptor.intercept_unary_stream(
448
+ continuation, client_call_details, request
449
+ )
450
+ except Exception as exception: # pylint:disable=broad-except
451
+ return _FailureOutcome(exception, sys.exc_info()[2])
452
+
453
+
454
+ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable):
455
+ _thunk: Callable
456
+ _method: str
457
+ _interceptor: grpc.StreamUnaryClientInterceptor
458
+
459
+ def __init__(
460
+ self,
461
+ thunk: Callable,
462
+ method: str,
463
+ interceptor: grpc.StreamUnaryClientInterceptor,
464
+ ):
465
+ self._thunk = thunk
466
+ self._method = method
467
+ self._interceptor = interceptor
468
+
469
+ def __call__(
470
+ self,
471
+ request_iterator: RequestIterableType,
472
+ timeout: Optional[float] = None,
473
+ metadata: Optional[MetadataType] = None,
474
+ credentials: Optional[grpc.CallCredentials] = None,
475
+ wait_for_ready: Optional[bool] = None,
476
+ compression: Optional[grpc.Compression] = None,
477
+ ) -> Any:
478
+ response, ignored_call = self._with_call(
479
+ request_iterator,
480
+ timeout=timeout,
481
+ metadata=metadata,
482
+ credentials=credentials,
483
+ wait_for_ready=wait_for_ready,
484
+ compression=compression,
485
+ )
486
+ return response
487
+
488
+ def _with_call(
489
+ self,
490
+ request_iterator: RequestIterableType,
491
+ timeout: Optional[float] = None,
492
+ metadata: Optional[MetadataType] = None,
493
+ credentials: Optional[grpc.CallCredentials] = None,
494
+ wait_for_ready: Optional[bool] = None,
495
+ compression: Optional[grpc.Compression] = None,
496
+ ) -> Tuple[Any, grpc.Call]:
497
+ client_call_details = _ClientCallDetails(
498
+ self._method,
499
+ timeout,
500
+ metadata,
501
+ credentials,
502
+ wait_for_ready,
503
+ compression,
504
+ )
505
+
506
+ def continuation(new_details, request_iterator):
507
+ (
508
+ new_method,
509
+ new_timeout,
510
+ new_metadata,
511
+ new_credentials,
512
+ new_wait_for_ready,
513
+ new_compression,
514
+ ) = _unwrap_client_call_details(new_details, client_call_details)
515
+ try:
516
+ response, call = self._thunk(new_method).with_call(
517
+ request_iterator,
518
+ timeout=new_timeout,
519
+ metadata=new_metadata,
520
+ credentials=new_credentials,
521
+ wait_for_ready=new_wait_for_ready,
522
+ compression=new_compression,
523
+ )
524
+ return _UnaryOutcome(response, call)
525
+ except grpc.RpcError as rpc_error:
526
+ return rpc_error
527
+ except Exception as exception: # pylint:disable=broad-except
528
+ return _FailureOutcome(exception, sys.exc_info()[2])
529
+
530
+ call = self._interceptor.intercept_stream_unary(
531
+ continuation, client_call_details, request_iterator
532
+ )
533
+ return call.result(), call
534
+
535
+ def with_call(
536
+ self,
537
+ request_iterator: RequestIterableType,
538
+ timeout: Optional[float] = None,
539
+ metadata: Optional[MetadataType] = None,
540
+ credentials: Optional[grpc.CallCredentials] = None,
541
+ wait_for_ready: Optional[bool] = None,
542
+ compression: Optional[grpc.Compression] = None,
543
+ ) -> Tuple[Any, grpc.Call]:
544
+ return self._with_call(
545
+ request_iterator,
546
+ timeout=timeout,
547
+ metadata=metadata,
548
+ credentials=credentials,
549
+ wait_for_ready=wait_for_ready,
550
+ compression=compression,
551
+ )
552
+
553
+ def future(
554
+ self,
555
+ request_iterator: RequestIterableType,
556
+ timeout: Optional[float] = None,
557
+ metadata: Optional[MetadataType] = None,
558
+ credentials: Optional[grpc.CallCredentials] = None,
559
+ wait_for_ready: Optional[bool] = None,
560
+ compression: Optional[grpc.Compression] = None,
561
+ ) -> Any:
562
+ client_call_details = _ClientCallDetails(
563
+ self._method,
564
+ timeout,
565
+ metadata,
566
+ credentials,
567
+ wait_for_ready,
568
+ compression,
569
+ )
570
+
571
+ def continuation(new_details, request_iterator):
572
+ (
573
+ new_method,
574
+ new_timeout,
575
+ new_metadata,
576
+ new_credentials,
577
+ new_wait_for_ready,
578
+ new_compression,
579
+ ) = _unwrap_client_call_details(new_details, client_call_details)
580
+ return self._thunk(new_method).future(
581
+ request_iterator,
582
+ timeout=new_timeout,
583
+ metadata=new_metadata,
584
+ credentials=new_credentials,
585
+ wait_for_ready=new_wait_for_ready,
586
+ compression=new_compression,
587
+ )
588
+
589
+ try:
590
+ return self._interceptor.intercept_stream_unary(
591
+ continuation, client_call_details, request_iterator
592
+ )
593
+ except Exception as exception: # pylint:disable=broad-except
594
+ return _FailureOutcome(exception, sys.exc_info()[2])
595
+
596
+
597
+ class _StreamStreamMultiCallable(grpc.StreamStreamMultiCallable):
598
+ _thunk: Callable
599
+ _method: str
600
+ _interceptor: grpc.StreamStreamClientInterceptor
601
+
602
+ def __init__(
603
+ self,
604
+ thunk: Callable,
605
+ method: str,
606
+ interceptor: grpc.StreamStreamClientInterceptor,
607
+ ):
608
+ self._thunk = thunk
609
+ self._method = method
610
+ self._interceptor = interceptor
611
+
612
+ def __call__(
613
+ self,
614
+ request_iterator: RequestIterableType,
615
+ timeout: Optional[float] = None,
616
+ metadata: Optional[MetadataType] = None,
617
+ credentials: Optional[grpc.CallCredentials] = None,
618
+ wait_for_ready: Optional[bool] = None,
619
+ compression: Optional[grpc.Compression] = None,
620
+ ):
621
+ client_call_details = _ClientCallDetails(
622
+ self._method,
623
+ timeout,
624
+ metadata,
625
+ credentials,
626
+ wait_for_ready,
627
+ compression,
628
+ )
629
+
630
+ def continuation(new_details, request_iterator):
631
+ (
632
+ new_method,
633
+ new_timeout,
634
+ new_metadata,
635
+ new_credentials,
636
+ new_wait_for_ready,
637
+ new_compression,
638
+ ) = _unwrap_client_call_details(new_details, client_call_details)
639
+ return self._thunk(new_method)(
640
+ request_iterator,
641
+ timeout=new_timeout,
642
+ metadata=new_metadata,
643
+ credentials=new_credentials,
644
+ wait_for_ready=new_wait_for_ready,
645
+ compression=new_compression,
646
+ )
647
+
648
+ try:
649
+ return self._interceptor.intercept_stream_stream(
650
+ continuation, client_call_details, request_iterator
651
+ )
652
+ except Exception as exception: # pylint:disable=broad-except
653
+ return _FailureOutcome(exception, sys.exc_info()[2])
654
+
655
+
656
+ class _Channel(grpc.Channel):
657
+ _channel: grpc.Channel
658
+ _interceptor: Union[
659
+ grpc.UnaryUnaryClientInterceptor,
660
+ grpc.UnaryStreamClientInterceptor,
661
+ grpc.StreamStreamClientInterceptor,
662
+ grpc.StreamUnaryClientInterceptor,
663
+ ]
664
+
665
+ def __init__(
666
+ self,
667
+ channel: grpc.Channel,
668
+ interceptor: Union[
669
+ grpc.UnaryUnaryClientInterceptor,
670
+ grpc.UnaryStreamClientInterceptor,
671
+ grpc.StreamStreamClientInterceptor,
672
+ grpc.StreamUnaryClientInterceptor,
673
+ ],
674
+ ):
675
+ self._channel = channel
676
+ self._interceptor = interceptor
677
+
678
+ def subscribe(
679
+ self, callback: Callable, try_to_connect: Optional[bool] = False
680
+ ):
681
+ self._channel.subscribe(callback, try_to_connect=try_to_connect)
682
+
683
+ def unsubscribe(self, callback: Callable):
684
+ self._channel.unsubscribe(callback)
685
+
686
+ # pylint: disable=arguments-differ
687
+ def unary_unary(
688
+ self,
689
+ method: str,
690
+ request_serializer: Optional[SerializingFunction] = None,
691
+ response_deserializer: Optional[DeserializingFunction] = None,
692
+ _registered_method: Optional[bool] = False,
693
+ ) -> grpc.UnaryUnaryMultiCallable:
694
+ # pytype: disable=wrong-arg-count
695
+ thunk = lambda m: self._channel.unary_unary(
696
+ m,
697
+ request_serializer,
698
+ response_deserializer,
699
+ _registered_method,
700
+ )
701
+ # pytype: enable=wrong-arg-count
702
+ if isinstance(self._interceptor, grpc.UnaryUnaryClientInterceptor):
703
+ return _UnaryUnaryMultiCallable(thunk, method, self._interceptor)
704
+ return thunk(method)
705
+
706
+ # pylint: disable=arguments-differ
707
+ def unary_stream(
708
+ self,
709
+ method: str,
710
+ request_serializer: Optional[SerializingFunction] = None,
711
+ response_deserializer: Optional[DeserializingFunction] = None,
712
+ _registered_method: Optional[bool] = False,
713
+ ) -> grpc.UnaryStreamMultiCallable:
714
+ # pytype: disable=wrong-arg-count
715
+ thunk = lambda m: self._channel.unary_stream(
716
+ m,
717
+ request_serializer,
718
+ response_deserializer,
719
+ _registered_method,
720
+ )
721
+ # pytype: enable=wrong-arg-count
722
+ if isinstance(self._interceptor, grpc.UnaryStreamClientInterceptor):
723
+ return _UnaryStreamMultiCallable(thunk, method, self._interceptor)
724
+ return thunk(method)
725
+
726
+ # pylint: disable=arguments-differ
727
+ def stream_unary(
728
+ self,
729
+ method: str,
730
+ request_serializer: Optional[SerializingFunction] = None,
731
+ response_deserializer: Optional[DeserializingFunction] = None,
732
+ _registered_method: Optional[bool] = False,
733
+ ) -> grpc.StreamUnaryMultiCallable:
734
+ # pytype: disable=wrong-arg-count
735
+ thunk = lambda m: self._channel.stream_unary(
736
+ m,
737
+ request_serializer,
738
+ response_deserializer,
739
+ _registered_method,
740
+ )
741
+ # pytype: enable=wrong-arg-count
742
+ if isinstance(self._interceptor, grpc.StreamUnaryClientInterceptor):
743
+ return _StreamUnaryMultiCallable(thunk, method, self._interceptor)
744
+ return thunk(method)
745
+
746
+ # pylint: disable=arguments-differ
747
+ def stream_stream(
748
+ self,
749
+ method: str,
750
+ request_serializer: Optional[SerializingFunction] = None,
751
+ response_deserializer: Optional[DeserializingFunction] = None,
752
+ _registered_method: Optional[bool] = False,
753
+ ) -> grpc.StreamStreamMultiCallable:
754
+ # pytype: disable=wrong-arg-count
755
+ thunk = lambda m: self._channel.stream_stream(
756
+ m,
757
+ request_serializer,
758
+ response_deserializer,
759
+ _registered_method,
760
+ )
761
+ # pytype: enable=wrong-arg-count
762
+ if isinstance(self._interceptor, grpc.StreamStreamClientInterceptor):
763
+ return _StreamStreamMultiCallable(thunk, method, self._interceptor)
764
+ return thunk(method)
765
+
766
+ def _close(self):
767
+ self._channel.close()
768
+
769
+ def __enter__(self):
770
+ return self
771
+
772
+ def __exit__(self, exc_type, exc_val, exc_tb):
773
+ self._close()
774
+ return False
775
+
776
+ def close(self):
777
+ self._channel.close()
778
+
779
+
780
+ def intercept_channel(
781
+ channel: grpc.Channel,
782
+ *interceptors: Optional[
783
+ Sequence[
784
+ Union[
785
+ grpc.UnaryUnaryClientInterceptor,
786
+ grpc.UnaryStreamClientInterceptor,
787
+ grpc.StreamStreamClientInterceptor,
788
+ grpc.StreamUnaryClientInterceptor,
789
+ ]
790
+ ]
791
+ ],
792
+ ) -> grpc.Channel:
793
+ for interceptor in reversed(list(interceptors)):
794
+ if (
795
+ not isinstance(interceptor, grpc.UnaryUnaryClientInterceptor)
796
+ and not isinstance(interceptor, grpc.UnaryStreamClientInterceptor)
797
+ and not isinstance(interceptor, grpc.StreamUnaryClientInterceptor)
798
+ and not isinstance(interceptor, grpc.StreamStreamClientInterceptor)
799
+ ):
800
+ error_msg = (
801
+ "interceptor must be "
802
+ "grpc.UnaryUnaryClientInterceptor or "
803
+ "grpc.UnaryStreamClientInterceptor or "
804
+ "grpc.StreamUnaryClientInterceptor or "
805
+ "grpc.StreamStreamClientInterceptor"
806
+ )
807
+ raise TypeError(error_msg)
808
+ channel = _Channel(channel, interceptor)
809
+ return channel
loan-advisor-agent/.venv/Lib/site-packages/grpc/_observability.py ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The 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
+
15
+ from __future__ import annotations
16
+
17
+ import abc
18
+ import contextlib
19
+ import logging
20
+ import threading
21
+ from typing import (
22
+ Any,
23
+ Generator,
24
+ Generic,
25
+ List,
26
+ Optional,
27
+ Tuple,
28
+ TypeVar,
29
+ Union,
30
+ )
31
+
32
+ from grpc._cython import cygrpc as _cygrpc
33
+ from grpc._typing import ChannelArgumentType
34
+
35
+ _LOGGER = logging.getLogger(__name__)
36
+
37
+ _channel = Any # _channel.py imports this module.
38
+ ClientCallTracerCapsule = TypeVar("ClientCallTracerCapsule")
39
+ ServerCallTracerFactoryCapsule = TypeVar("ServerCallTracerFactoryCapsule")
40
+
41
+ _plugin_lock: threading.RLock = threading.RLock()
42
+ _OBSERVABILITY_PLUGIN: Optional["ObservabilityPlugin"] = None
43
+ _SERVICES_TO_EXCLUDE: List[bytes] = [
44
+ b"google.monitoring.v3.MetricService",
45
+ b"google.devtools.cloudtrace.v2.TraceService",
46
+ ]
47
+
48
+
49
+ class ServerCallTracerFactory:
50
+ """An encapsulation of a ServerCallTracerFactory.
51
+
52
+ Instances of this class can be passed to a Channel as values for the
53
+ grpc.experimental.server_call_tracer_factory option
54
+ """
55
+
56
+ def __init__(self, address):
57
+ self._address = address
58
+
59
+ def __int__(self):
60
+ return self._address
61
+
62
+
63
+ class ObservabilityPlugin(
64
+ Generic[ClientCallTracerCapsule, ServerCallTracerFactoryCapsule],
65
+ metaclass=abc.ABCMeta,
66
+ ):
67
+ """Abstract base class for observability plugin.
68
+
69
+ *This is a semi-private class that was intended for the exclusive use of
70
+ the gRPC team.*
71
+
72
+ The ClientCallTracerCapsule and ClientCallTracerCapsule created by this
73
+ plugin should be injected to gRPC core using observability_init at the
74
+ start of a program, before any channels/servers are built.
75
+
76
+ Any future methods added to this interface cannot have the
77
+ @abc.abstractmethod annotation.
78
+
79
+ Attributes:
80
+ _stats_enabled: A bool indicates whether tracing is enabled.
81
+ _tracing_enabled: A bool indicates whether stats(metrics) is enabled.
82
+ _registered_methods: A set which stores the registered method names in
83
+ bytes.
84
+ """
85
+
86
+ _tracing_enabled: bool = False
87
+ _stats_enabled: bool = False
88
+
89
+ @abc.abstractmethod
90
+ def create_client_call_tracer(
91
+ self, method_name: bytes, target: bytes
92
+ ) -> ClientCallTracerCapsule:
93
+ """Creates a ClientCallTracerCapsule.
94
+
95
+ After register the plugin, if tracing or stats is enabled, this method
96
+ will be called after a call was created, the ClientCallTracer created
97
+ by this method will be saved to call context.
98
+
99
+ The ClientCallTracer is an object which implements `grpc_core::ClientCallTracer`
100
+ interface and wrapped in a PyCapsule using `client_call_tracer` as name.
101
+
102
+ Args:
103
+ method_name: The method name of the call in byte format.
104
+ target: The channel target of the call in byte format.
105
+ registered_method: Whether this method is pre-registered.
106
+
107
+ Returns:
108
+ A PyCapsule which stores a ClientCallTracer object.
109
+ """
110
+ raise NotImplementedError()
111
+
112
+ @abc.abstractmethod
113
+ def save_trace_context(
114
+ self, trace_id: str, span_id: str, is_sampled: bool
115
+ ) -> None:
116
+ """Saves the trace_id and span_id related to the current span.
117
+
118
+ After register the plugin, if tracing is enabled, this method will be
119
+ called after the server finished sending response.
120
+
121
+ This method can be used to propagate census context.
122
+
123
+ Args:
124
+ trace_id: The identifier for the trace associated with the span as a
125
+ 32-character hexadecimal encoded string,
126
+ e.g. 26ed0036f2eff2b7317bccce3e28d01f
127
+ span_id: The identifier for the span as a 16-character hexadecimal encoded
128
+ string. e.g. 113ec879e62583bc
129
+ is_sampled: A bool indicates whether the span is sampled.
130
+ """
131
+ raise NotImplementedError()
132
+
133
+ @abc.abstractmethod
134
+ def create_server_call_tracer_factory(
135
+ self,
136
+ *,
137
+ xds: bool = False,
138
+ ) -> Optional[ServerCallTracerFactoryCapsule]:
139
+ """Creates a ServerCallTracerFactoryCapsule.
140
+
141
+ This method will be called at server initialization time to create a
142
+ ServerCallTracerFactory, which will be registered to gRPC core.
143
+
144
+ The ServerCallTracerFactory is an object which implements
145
+ `grpc_core::ServerCallTracerFactory` interface and wrapped in a PyCapsule
146
+ using `server_call_tracer_factory` as name.
147
+
148
+ Args:
149
+ xds: Whether the server is xds server.
150
+
151
+ Returns:
152
+ A PyCapsule which stores a ServerCallTracerFactory object. Or None if
153
+ plugin decides not to create ServerCallTracerFactory.
154
+ """
155
+ raise NotImplementedError()
156
+
157
+ @abc.abstractmethod
158
+ def record_rpc_latency(
159
+ self, method: str, target: str, rpc_latency: float, status_code: Any
160
+ ) -> None:
161
+ """Record the latency of the RPC.
162
+
163
+ After register the plugin, if stats is enabled, this method will be
164
+ called at the end of each RPC.
165
+
166
+ Args:
167
+ method: The fully-qualified name of the RPC method being invoked.
168
+ target: The target name of the RPC method being invoked.
169
+ rpc_latency: The latency for the RPC in seconds, equals to the time between
170
+ when the client invokes the RPC and when the client receives the status.
171
+ status_code: An element of grpc.StatusCode in string format representing the
172
+ final status for the RPC.
173
+ """
174
+ raise NotImplementedError()
175
+
176
+ def set_tracing(self, enable: bool) -> None:
177
+ """Enable or disable tracing.
178
+
179
+ Args:
180
+ enable: A bool indicates whether tracing should be enabled.
181
+ """
182
+ self._tracing_enabled = enable
183
+
184
+ def set_stats(self, enable: bool) -> None:
185
+ """Enable or disable stats(metrics).
186
+
187
+ Args:
188
+ enable: A bool indicates whether stats should be enabled.
189
+ """
190
+ self._stats_enabled = enable
191
+
192
+ def save_registered_method(self, method_name: bytes) -> None:
193
+ """Saves the method name to registered_method list.
194
+
195
+ When exporting metrics, method name for unregistered methods will be replaced
196
+ with 'other' by default.
197
+
198
+ Args:
199
+ method_name: The method name in bytes.
200
+ """
201
+ raise NotImplementedError()
202
+
203
+ @property
204
+ def tracing_enabled(self) -> bool:
205
+ return self._tracing_enabled
206
+
207
+ @property
208
+ def stats_enabled(self) -> bool:
209
+ return self._stats_enabled
210
+
211
+ @property
212
+ def observability_enabled(self) -> bool:
213
+ return self.tracing_enabled or self.stats_enabled
214
+
215
+
216
+ @contextlib.contextmanager
217
+ def get_plugin() -> Generator[Optional[ObservabilityPlugin], None, None]:
218
+ """Get the ObservabilityPlugin in _observability module.
219
+
220
+ Returns:
221
+ The ObservabilityPlugin currently registered with the _observability
222
+ module. Or None if no plugin exists at the time of calling this method.
223
+ """
224
+ with _plugin_lock:
225
+ yield _OBSERVABILITY_PLUGIN
226
+
227
+
228
+ def set_plugin(observability_plugin: Optional[ObservabilityPlugin]) -> None:
229
+ """Save ObservabilityPlugin to _observability module.
230
+
231
+ Args:
232
+ observability_plugin: The ObservabilityPlugin to save.
233
+
234
+ Raises:
235
+ ValueError: If an ObservabilityPlugin was already registered at the
236
+ time of calling this method.
237
+ """
238
+ global _OBSERVABILITY_PLUGIN # pylint: disable=global-statement # noqa: PLW0603
239
+ with _plugin_lock:
240
+ if observability_plugin and _OBSERVABILITY_PLUGIN:
241
+ error_msg = "observability_plugin was already set!"
242
+ raise ValueError(error_msg)
243
+ _OBSERVABILITY_PLUGIN = observability_plugin
244
+
245
+
246
+ def observability_init(observability_plugin: ObservabilityPlugin) -> None:
247
+ """Initialize observability with provided ObservabilityPlugin.
248
+
249
+ This method have to be called at the start of a program, before any
250
+ channels/servers are built.
251
+
252
+ Args:
253
+ observability_plugin: The ObservabilityPlugin to use.
254
+
255
+ Raises:
256
+ ValueError: If an ObservabilityPlugin was already registered at the
257
+ time of calling this method.
258
+ """
259
+ set_plugin(observability_plugin)
260
+
261
+
262
+ def observability_deinit() -> None:
263
+ """Clear the observability context, including ObservabilityPlugin and
264
+ ServerCallTracerFactory
265
+
266
+ This method have to be called after exit observability context so that
267
+ it's possible to re-initialize again.
268
+ """
269
+ set_plugin(None)
270
+ _cygrpc.clear_server_call_tracer_factory()
271
+
272
+
273
+ def maybe_record_rpc_latency(state: "_channel._RPCState") -> None:
274
+ """Record the latency of the RPC, if the plugin is registered and stats is enabled.
275
+
276
+ This method will be called at the end of each RPC.
277
+
278
+ Args:
279
+ state: a grpc._channel._RPCState object which contains the stats related to the
280
+ RPC.
281
+ """
282
+ # TODO(xuanwn): use channel args to exclude those metrics.
283
+ for exclude_prefix in _SERVICES_TO_EXCLUDE:
284
+ if exclude_prefix in state.method.encode("utf8"):
285
+ return
286
+ with get_plugin() as plugin:
287
+ if plugin and plugin.stats_enabled:
288
+ rpc_latency_s = state.rpc_end_time - state.rpc_start_time
289
+ rpc_latency_ms = rpc_latency_s * 1000
290
+ plugin.record_rpc_latency(
291
+ state.method, state.target, rpc_latency_ms, state.code
292
+ )
293
+
294
+
295
+ def create_server_call_tracer_factory_option(
296
+ xds: bool,
297
+ ) -> Union[Tuple[ChannelArgumentType], Tuple[()]]:
298
+ with get_plugin() as plugin:
299
+ if plugin and plugin.stats_enabled:
300
+ server_call_tracer_factory_address = (
301
+ _cygrpc.get_server_call_tracer_factory_address(plugin, xds)
302
+ )
303
+ if server_call_tracer_factory_address:
304
+ return (
305
+ (
306
+ "grpc.experimental.server_call_tracer_factory",
307
+ ServerCallTracerFactory(
308
+ server_call_tracer_factory_address
309
+ ),
310
+ ),
311
+ )
312
+ return ()
loan-advisor-agent/.venv/Lib/site-packages/grpc/_plugin_wrapping.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2015 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
+
15
+ import collections
16
+ import logging
17
+ import threading
18
+ from typing import Callable, Optional, Type
19
+
20
+ import grpc
21
+ from grpc import _common
22
+ from grpc._cython import cygrpc
23
+ from grpc._typing import MetadataType
24
+
25
+ _LOGGER = logging.getLogger(__name__)
26
+
27
+
28
+ class _AuthMetadataContext(
29
+ collections.namedtuple(
30
+ "AuthMetadataContext",
31
+ (
32
+ "service_url",
33
+ "method_name",
34
+ ),
35
+ ),
36
+ grpc.AuthMetadataContext,
37
+ ):
38
+ pass
39
+
40
+
41
+ class _CallbackState(object):
42
+ def __init__(self):
43
+ self.lock = threading.Lock()
44
+ self.called = False
45
+ self.exception = None
46
+
47
+
48
+ class _AuthMetadataPluginCallback(grpc.AuthMetadataPluginCallback):
49
+ _state: _CallbackState
50
+ _callback: Callable
51
+
52
+ def __init__(self, state: _CallbackState, callback: Callable):
53
+ self._state = state
54
+ self._callback = callback
55
+
56
+ def __call__(
57
+ self, metadata: MetadataType, error: Optional[Type[BaseException]]
58
+ ):
59
+ with self._state.lock:
60
+ if self._state.exception is None:
61
+ if self._state.called:
62
+ error_msg = (
63
+ "AuthMetadataPluginCallback invoked more than once!"
64
+ )
65
+ raise RuntimeError(error_msg)
66
+ self._state.called = True
67
+ else:
68
+ error_msg = (
69
+ "AuthMetadataPluginCallback"
70
+ 'raised exception "{self._state.exception}"!'
71
+ )
72
+ raise RuntimeError(error_msg)
73
+ if error is None:
74
+ self._callback(metadata, cygrpc.StatusCode.ok, None)
75
+ else:
76
+ self._callback(
77
+ None, cygrpc.StatusCode.internal, _common.encode(str(error))
78
+ )
79
+
80
+
81
+ class _Plugin(object):
82
+ _metadata_plugin: grpc.AuthMetadataPlugin
83
+
84
+ def __init__(self, metadata_plugin: grpc.AuthMetadataPlugin):
85
+ self._metadata_plugin = metadata_plugin
86
+ self._stored_ctx = None
87
+
88
+ try:
89
+ import contextvars # pylint: disable=wrong-import-position
90
+
91
+ # The plugin may be invoked on a thread created by Core, which will not
92
+ # have the context propagated. This context is stored and installed in
93
+ # the thread invoking the plugin.
94
+ self._stored_ctx = contextvars.copy_context()
95
+ except ImportError:
96
+ # Support versions predating contextvars.
97
+ pass
98
+
99
+ def __call__(self, service_url: str, method_name: str, callback: Callable):
100
+ context = _AuthMetadataContext(
101
+ _common.decode(service_url), _common.decode(method_name)
102
+ )
103
+ callback_state = _CallbackState()
104
+ try:
105
+ self._metadata_plugin(
106
+ context, _AuthMetadataPluginCallback(callback_state, callback)
107
+ )
108
+ except Exception as exception: # pylint: disable=broad-except
109
+ _LOGGER.exception(
110
+ 'AuthMetadataPluginCallback "%s" raised exception!',
111
+ self._metadata_plugin,
112
+ )
113
+ with callback_state.lock:
114
+ callback_state.exception = exception
115
+ if callback_state.called:
116
+ return
117
+ callback(
118
+ None, cygrpc.StatusCode.internal, _common.encode(str(exception))
119
+ )
120
+
121
+
122
+ def metadata_plugin_call_credentials(
123
+ metadata_plugin: grpc.AuthMetadataPlugin, name: Optional[str]
124
+ ) -> grpc.CallCredentials:
125
+ if name is None:
126
+ try:
127
+ effective_name = metadata_plugin.__name__
128
+ except AttributeError:
129
+ effective_name = metadata_plugin.__class__.__name__
130
+ else:
131
+ effective_name = name
132
+ return grpc.CallCredentials(
133
+ cygrpc.MetadataPluginCallCredentials(
134
+ _Plugin(metadata_plugin), _common.encode(effective_name)
135
+ )
136
+ )
loan-advisor-agent/.venv/Lib/site-packages/grpc/_runtime_protos.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The 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
+
15
+ import sys
16
+ import types
17
+ from typing import Tuple, Union
18
+
19
+ _REQUIRED_SYMBOLS = ("_protos", "_services", "_protos_and_services")
20
+ _MINIMUM_VERSION = (3, 5, 0)
21
+
22
+ _UNINSTALLED_TEMPLATE = (
23
+ "Install the grpcio-tools package (1.32.0+) to use the {} function."
24
+ )
25
+ _VERSION_ERROR_TEMPLATE = (
26
+ "The {} function is only on available on Python 3.X interpreters."
27
+ )
28
+
29
+
30
+ def _has_runtime_proto_symbols(mod: types.ModuleType) -> bool:
31
+ return all(hasattr(mod, sym) for sym in _REQUIRED_SYMBOLS)
32
+
33
+
34
+ def _is_grpc_tools_importable() -> bool:
35
+ try:
36
+ import grpc_tools # pylint: disable=unused-import # pytype: disable=import-error
37
+
38
+ return True
39
+ except ImportError as e:
40
+ # NOTE: It's possible that we're encountering a transitive ImportError, so
41
+ # we check for that and re-raise if so.
42
+ if "grpc_tools" not in e.args[0]:
43
+ raise
44
+ return False
45
+
46
+
47
+ def _call_with_lazy_import(
48
+ fn_name: str, protobuf_path: str
49
+ ) -> Union[types.ModuleType, Tuple[types.ModuleType, types.ModuleType]]:
50
+ """Calls one of the three functions, lazily importing grpc_tools.
51
+
52
+ Args:
53
+ fn_name: The name of the function to import from grpc_tools.protoc.
54
+ protobuf_path: The path to import.
55
+
56
+ Returns:
57
+ The appropriate module object.
58
+ """
59
+ if sys.version_info < _MINIMUM_VERSION:
60
+ raise NotImplementedError(_VERSION_ERROR_TEMPLATE.format(fn_name))
61
+ if not _is_grpc_tools_importable():
62
+ raise NotImplementedError(_UNINSTALLED_TEMPLATE.format(fn_name))
63
+ import grpc_tools.protoc # pytype: disable=import-error
64
+
65
+ if _has_runtime_proto_symbols(grpc_tools.protoc):
66
+ fn = getattr(grpc_tools.protoc, "_" + fn_name)
67
+ return fn(protobuf_path)
68
+ raise NotImplementedError(_UNINSTALLED_TEMPLATE.format(fn_name))
69
+
70
+
71
+ def protos(protobuf_path): # pylint: disable=unused-argument
72
+ """Returns a module generated by the indicated .proto file.
73
+
74
+ THIS IS AN EXPERIMENTAL API.
75
+
76
+ Use this function to retrieve classes corresponding to message
77
+ definitions in the .proto file.
78
+
79
+ To inspect the contents of the returned module, use the dir function.
80
+ For example:
81
+
82
+ ```
83
+ protos = grpc.protos("foo.proto")
84
+ print(dir(protos))
85
+ ```
86
+
87
+ The returned module object corresponds to the _pb2.py file generated
88
+ by protoc. The path is expected to be relative to an entry on sys.path
89
+ and all transitive dependencies of the file should also be resolvable
90
+ from an entry on sys.path.
91
+
92
+ To completely disable the machinery behind this function, set the
93
+ GRPC_PYTHON_DISABLE_DYNAMIC_STUBS environment variable to "true".
94
+
95
+ Args:
96
+ protobuf_path: The path to the .proto file on the filesystem. This path
97
+ must be resolvable from an entry on sys.path and so must all of its
98
+ transitive dependencies.
99
+
100
+ Returns:
101
+ A module object corresponding to the message code for the indicated
102
+ .proto file. Equivalent to a generated _pb2.py file.
103
+ """
104
+ return _call_with_lazy_import("protos", protobuf_path)
105
+
106
+
107
+ def services(protobuf_path): # pylint: disable=unused-argument
108
+ """Returns a module generated by the indicated .proto file.
109
+
110
+ THIS IS AN EXPERIMENTAL API.
111
+
112
+ Use this function to retrieve classes and functions corresponding to
113
+ service definitions in the .proto file, including both stub and servicer
114
+ definitions.
115
+
116
+ To inspect the contents of the returned module, use the dir function.
117
+ For example:
118
+
119
+ ```
120
+ services = grpc.services("foo.proto")
121
+ print(dir(services))
122
+ ```
123
+
124
+ The returned module object corresponds to the _pb2_grpc.py file generated
125
+ by protoc. The path is expected to be relative to an entry on sys.path
126
+ and all transitive dependencies of the file should also be resolvable
127
+ from an entry on sys.path.
128
+
129
+ To completely disable the machinery behind this function, set the
130
+ GRPC_PYTHON_DISABLE_DYNAMIC_STUBS environment variable to "true".
131
+
132
+ Args:
133
+ protobuf_path: The path to the .proto file on the filesystem. This path
134
+ must be resolvable from an entry on sys.path and so must all of its
135
+ transitive dependencies.
136
+
137
+ Returns:
138
+ A module object corresponding to the stub/service code for the indicated
139
+ .proto file. Equivalent to a generated _pb2_grpc.py file.
140
+ """
141
+ return _call_with_lazy_import("services", protobuf_path)
142
+
143
+
144
+ def protos_and_services(protobuf_path): # pylint: disable=unused-argument
145
+ """Returns a 2-tuple of modules corresponding to protos and services.
146
+
147
+ THIS IS AN EXPERIMENTAL API.
148
+
149
+ The return value of this function is equivalent to a call to protos and a
150
+ call to services.
151
+
152
+ To completely disable the machinery behind this function, set the
153
+ GRPC_PYTHON_DISABLE_DYNAMIC_STUBS environment variable to "true".
154
+
155
+ Args:
156
+ protobuf_path: The path to the .proto file on the filesystem. This path
157
+ must be resolvable from an entry on sys.path and so must all of its
158
+ transitive dependencies.
159
+
160
+ Returns:
161
+ A 2-tuple of module objects corresponding to (protos(path), services(path)).
162
+ """
163
+ return _call_with_lazy_import("protos_and_services", protobuf_path)
loan-advisor-agent/.venv/Lib/site-packages/grpc/_server.py ADDED
@@ -0,0 +1,1515 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 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
+ """Service-side implementation of gRPC Python."""
15
+
16
+ from __future__ import annotations
17
+
18
+ import abc
19
+ import collections
20
+ from concurrent import futures
21
+ import contextvars
22
+ import enum
23
+ import logging
24
+ import threading
25
+ import time
26
+ import traceback
27
+ from typing import (
28
+ Any,
29
+ Callable,
30
+ Dict,
31
+ Iterable,
32
+ Iterator,
33
+ List,
34
+ Mapping,
35
+ Optional,
36
+ Sequence,
37
+ Set,
38
+ Tuple,
39
+ Union,
40
+ )
41
+
42
+ import grpc
43
+ from grpc import _common
44
+ from grpc import _compression
45
+ from grpc import _interceptor
46
+ from grpc import _observability
47
+ from grpc._cython import cygrpc
48
+ from grpc._typing import ArityAgnosticMethodHandler
49
+ from grpc._typing import ChannelArgumentType
50
+ from grpc._typing import DeserializingFunction
51
+ from grpc._typing import MetadataType
52
+ from grpc._typing import NullaryCallbackType
53
+ from grpc._typing import ResponseType
54
+ from grpc._typing import SerializingFunction
55
+ from grpc._typing import ServerCallbackTag
56
+ from grpc._typing import ServerTagCallbackType
57
+ from typing_extensions import override
58
+
59
+ _LOGGER = logging.getLogger(__name__)
60
+
61
+ _SHUTDOWN_TAG = "shutdown"
62
+ _REQUEST_CALL_TAG = "request_call"
63
+
64
+ _RECEIVE_CLOSE_ON_SERVER_TOKEN = "receive_close_on_server"
65
+ _SEND_INITIAL_METADATA_TOKEN = "send_initial_metadata"
66
+ _RECEIVE_MESSAGE_TOKEN = "receive_message"
67
+ _SEND_MESSAGE_TOKEN = "send_message"
68
+ _SEND_INITIAL_METADATA_AND_SEND_MESSAGE_TOKEN = (
69
+ "send_initial_metadata * send_message"
70
+ )
71
+ _SEND_STATUS_FROM_SERVER_TOKEN = "send_status_from_server"
72
+ _SEND_INITIAL_METADATA_AND_SEND_STATUS_FROM_SERVER_TOKEN = (
73
+ "send_initial_metadata * send_status_from_server"
74
+ )
75
+
76
+ _OPEN = "open"
77
+ _CLOSED = "closed"
78
+ _CANCELLED = "cancelled"
79
+
80
+ _EMPTY_FLAGS = 0
81
+
82
+ _DEALLOCATED_SERVER_CHECK_PERIOD_S = 1.0
83
+ _INF_TIMEOUT = 1e9
84
+
85
+
86
+ def _serialized_request(request_event: cygrpc.BaseEvent) -> bytes:
87
+ return request_event.batch_operations[0].message()
88
+
89
+
90
+ def _application_code(code: grpc.StatusCode) -> cygrpc.StatusCode:
91
+ cygrpc_code = _common.STATUS_CODE_TO_CYGRPC_STATUS_CODE.get(code)
92
+ return cygrpc.StatusCode.unknown if cygrpc_code is None else cygrpc_code
93
+
94
+
95
+ def _completion_code(state: _RPCState) -> cygrpc.StatusCode:
96
+ if state.code is None:
97
+ return cygrpc.StatusCode.ok
98
+ return _application_code(state.code)
99
+
100
+
101
+ def _abortion_code(
102
+ state: _RPCState, code: cygrpc.StatusCode
103
+ ) -> cygrpc.StatusCode:
104
+ if state.code is None:
105
+ return code
106
+ return _application_code(state.code)
107
+
108
+
109
+ def _details(state: _RPCState) -> bytes:
110
+ return b"" if state.details is None else state.details
111
+
112
+
113
+ class _HandlerCallDetails(
114
+ collections.namedtuple(
115
+ "_HandlerCallDetails",
116
+ (
117
+ "method",
118
+ "invocation_metadata",
119
+ ),
120
+ ),
121
+ grpc.HandlerCallDetails,
122
+ ):
123
+ pass
124
+
125
+
126
+ class _Method(abc.ABC):
127
+ @abc.abstractmethod
128
+ def name(self) -> Optional[str]:
129
+ raise NotImplementedError()
130
+
131
+ @abc.abstractmethod
132
+ def handler(
133
+ self, handler_call_details: _HandlerCallDetails
134
+ ) -> Optional[grpc.RpcMethodHandler]:
135
+ raise NotImplementedError()
136
+
137
+
138
+ class _RegisteredMethod(_Method):
139
+ def __init__(
140
+ self,
141
+ name: str,
142
+ registered_handler: Optional[grpc.RpcMethodHandler],
143
+ ):
144
+ self._name = name
145
+ self._registered_handler = registered_handler
146
+
147
+ @override
148
+ def name(self) -> Optional[str]:
149
+ return self._name
150
+
151
+ @override
152
+ def handler(
153
+ self, handler_call_details: _HandlerCallDetails
154
+ ) -> Optional[grpc.RpcMethodHandler]:
155
+ return self._registered_handler
156
+
157
+
158
+ class _GenericMethod(_Method):
159
+ def __init__(
160
+ self,
161
+ generic_handlers: List[grpc.GenericRpcHandler],
162
+ ):
163
+ self._generic_handlers = generic_handlers
164
+
165
+ @override
166
+ def name(self) -> Optional[str]:
167
+ return None
168
+
169
+ @override
170
+ def handler(
171
+ self, handler_call_details: _HandlerCallDetails
172
+ ) -> Optional[grpc.RpcMethodHandler]:
173
+ # If the same method have both generic and registered handler,
174
+ # registered handler will take precedence.
175
+ for generic_handler in self._generic_handlers:
176
+ method_handler = generic_handler.service(handler_call_details)
177
+ if method_handler is not None:
178
+ return method_handler
179
+ return None
180
+
181
+
182
+ class _RPCState(object):
183
+ context: contextvars.Context
184
+ condition: threading.Condition
185
+ due = Set[str]
186
+ request: Any
187
+ client: str
188
+ initial_metadata_allowed: bool
189
+ compression_algorithm: Optional[grpc.Compression]
190
+ disable_next_compression: bool
191
+ trailing_metadata: Optional[MetadataType]
192
+ code: Optional[grpc.StatusCode]
193
+ details: Optional[bytes]
194
+ statused: bool
195
+ rpc_errors: List[Exception]
196
+ callbacks: Optional[List[NullaryCallbackType]]
197
+ aborted: bool
198
+
199
+ def __init__(self):
200
+ self.context = contextvars.Context()
201
+ self.condition = threading.Condition()
202
+ self.due = set()
203
+ self.request = None
204
+ self.client = _OPEN
205
+ self.initial_metadata_allowed = True
206
+ self.compression_algorithm = None
207
+ self.disable_next_compression = False
208
+ self.trailing_metadata = None
209
+ self.code = None
210
+ self.details = None
211
+ self.statused = False
212
+ self.rpc_errors = []
213
+ self.callbacks = []
214
+ self.aborted = False
215
+
216
+
217
+ def _raise_rpc_error(state: _RPCState) -> None:
218
+ rpc_error = grpc.RpcError()
219
+ state.rpc_errors.append(rpc_error)
220
+ raise rpc_error
221
+
222
+
223
+ def _possibly_finish_call(
224
+ state: _RPCState, token: str
225
+ ) -> ServerTagCallbackType:
226
+ state.due.remove(token)
227
+ if not _is_rpc_state_active(state) and not state.due:
228
+ callbacks = state.callbacks
229
+ state.callbacks = None
230
+ return state, callbacks
231
+ return None, ()
232
+
233
+
234
+ def _send_status_from_server(state: _RPCState, token: str) -> ServerCallbackTag:
235
+ def send_status_from_server(unused_send_status_from_server_event):
236
+ with state.condition:
237
+ return _possibly_finish_call(state, token)
238
+
239
+ return send_status_from_server
240
+
241
+
242
+ def _get_initial_metadata(
243
+ state: _RPCState, metadata: Optional[MetadataType]
244
+ ) -> Optional[MetadataType]:
245
+ with state.condition:
246
+ if state.compression_algorithm:
247
+ compression_metadata = (
248
+ _compression.compression_algorithm_to_metadata(
249
+ state.compression_algorithm
250
+ ),
251
+ )
252
+ if metadata is None:
253
+ return compression_metadata
254
+ return compression_metadata + tuple(metadata)
255
+ return metadata
256
+
257
+
258
+ def _get_initial_metadata_operation(
259
+ state: _RPCState, metadata: Optional[MetadataType]
260
+ ) -> cygrpc.Operation:
261
+ operation = cygrpc.SendInitialMetadataOperation(
262
+ _get_initial_metadata(state, metadata), _EMPTY_FLAGS
263
+ )
264
+ return operation
265
+
266
+
267
+ def _abort(
268
+ state: _RPCState, call: cygrpc.Call, code: cygrpc.StatusCode, details: bytes
269
+ ) -> None:
270
+ if state.client is not _CANCELLED:
271
+ effective_code = _abortion_code(state, code)
272
+ effective_details = details if state.details is None else state.details
273
+ if state.initial_metadata_allowed:
274
+ operations = (
275
+ _get_initial_metadata_operation(state, None),
276
+ cygrpc.SendStatusFromServerOperation(
277
+ state.trailing_metadata,
278
+ effective_code,
279
+ effective_details,
280
+ _EMPTY_FLAGS,
281
+ ),
282
+ )
283
+ token = _SEND_INITIAL_METADATA_AND_SEND_STATUS_FROM_SERVER_TOKEN
284
+ else:
285
+ operations = (
286
+ cygrpc.SendStatusFromServerOperation(
287
+ state.trailing_metadata,
288
+ effective_code,
289
+ effective_details,
290
+ _EMPTY_FLAGS,
291
+ ),
292
+ )
293
+ token = _SEND_STATUS_FROM_SERVER_TOKEN
294
+ call.start_server_batch(
295
+ operations, _send_status_from_server(state, token)
296
+ )
297
+ state.statused = True
298
+ state.due.add(token)
299
+
300
+
301
+ def _receive_close_on_server(state: _RPCState) -> ServerCallbackTag:
302
+ def receive_close_on_server(receive_close_on_server_event):
303
+ with state.condition:
304
+ if receive_close_on_server_event.batch_operations[0].cancelled():
305
+ state.client = _CANCELLED
306
+ elif state.client is _OPEN:
307
+ state.client = _CLOSED
308
+ state.condition.notify_all()
309
+ return _possibly_finish_call(state, _RECEIVE_CLOSE_ON_SERVER_TOKEN)
310
+
311
+ return receive_close_on_server
312
+
313
+
314
+ def _receive_message(
315
+ state: _RPCState,
316
+ call: cygrpc.Call,
317
+ request_deserializer: Optional[DeserializingFunction],
318
+ ) -> ServerCallbackTag:
319
+ def receive_message(receive_message_event):
320
+ serialized_request = _serialized_request(receive_message_event)
321
+ if serialized_request is None:
322
+ with state.condition:
323
+ if state.client is _OPEN:
324
+ state.client = _CLOSED
325
+ state.condition.notify_all()
326
+ return _possibly_finish_call(state, _RECEIVE_MESSAGE_TOKEN)
327
+ else:
328
+ request = _common.deserialize(
329
+ serialized_request, request_deserializer
330
+ )
331
+ with state.condition:
332
+ if request is None:
333
+ _abort(
334
+ state,
335
+ call,
336
+ cygrpc.StatusCode.internal,
337
+ b"Exception deserializing request!",
338
+ )
339
+ else:
340
+ state.request = request
341
+ state.condition.notify_all()
342
+ return _possibly_finish_call(state, _RECEIVE_MESSAGE_TOKEN)
343
+
344
+ return receive_message
345
+
346
+
347
+ def _send_initial_metadata(state: _RPCState) -> ServerCallbackTag:
348
+ def send_initial_metadata(unused_send_initial_metadata_event):
349
+ with state.condition:
350
+ return _possibly_finish_call(state, _SEND_INITIAL_METADATA_TOKEN)
351
+
352
+ return send_initial_metadata
353
+
354
+
355
+ def _send_message(state: _RPCState, token: str) -> ServerCallbackTag:
356
+ def send_message(unused_send_message_event):
357
+ with state.condition:
358
+ state.condition.notify_all()
359
+ return _possibly_finish_call(state, token)
360
+
361
+ return send_message
362
+
363
+
364
+ class _Context(grpc.ServicerContext):
365
+ _rpc_event: cygrpc.BaseEvent
366
+ _state: _RPCState
367
+ request_deserializer: Optional[DeserializingFunction]
368
+
369
+ def __init__(
370
+ self,
371
+ rpc_event: cygrpc.BaseEvent,
372
+ state: _RPCState,
373
+ request_deserializer: Optional[DeserializingFunction],
374
+ ):
375
+ self._rpc_event = rpc_event
376
+ self._state = state
377
+ self._request_deserializer = request_deserializer
378
+
379
+ def is_active(self) -> bool:
380
+ with self._state.condition:
381
+ return _is_rpc_state_active(self._state)
382
+
383
+ def time_remaining(self) -> float:
384
+ return max(self._rpc_event.call_details.deadline - time.time(), 0)
385
+
386
+ def cancel(self) -> None:
387
+ self._rpc_event.call.cancel()
388
+
389
+ def add_callback(self, callback: NullaryCallbackType) -> bool:
390
+ with self._state.condition:
391
+ if self._state.callbacks is None:
392
+ return False
393
+ self._state.callbacks.append(callback)
394
+ return True
395
+
396
+ def disable_next_message_compression(self) -> None:
397
+ with self._state.condition:
398
+ self._state.disable_next_compression = True
399
+
400
+ def invocation_metadata(self) -> Optional[MetadataType]:
401
+ return self._rpc_event.invocation_metadata
402
+
403
+ def peer(self) -> str:
404
+ return _common.decode(self._rpc_event.call.peer())
405
+
406
+ def peer_identities(self) -> Optional[Sequence[bytes]]:
407
+ return cygrpc.peer_identities(self._rpc_event.call)
408
+
409
+ def peer_identity_key(self) -> Optional[str]:
410
+ id_key = cygrpc.peer_identity_key(self._rpc_event.call)
411
+ return id_key if id_key is None else _common.decode(id_key)
412
+
413
+ def auth_context(self) -> Mapping[str, Sequence[bytes]]:
414
+ auth_context = cygrpc.auth_context(self._rpc_event.call)
415
+ auth_context_dict = {} if auth_context is None else auth_context
416
+ return {
417
+ _common.decode(key): value
418
+ for key, value in auth_context_dict.items()
419
+ }
420
+
421
+ def set_compression(self, compression: grpc.Compression) -> None:
422
+ with self._state.condition:
423
+ self._state.compression_algorithm = compression
424
+
425
+ def send_initial_metadata(self, initial_metadata: MetadataType) -> None:
426
+ with self._state.condition:
427
+ if self._state.client is _CANCELLED:
428
+ _raise_rpc_error(self._state)
429
+ if self._state.initial_metadata_allowed:
430
+ operation = _get_initial_metadata_operation(
431
+ self._state, initial_metadata
432
+ )
433
+ self._rpc_event.call.start_server_batch(
434
+ (operation,), _send_initial_metadata(self._state)
435
+ )
436
+ self._state.initial_metadata_allowed = False
437
+ self._state.due.add(_SEND_INITIAL_METADATA_TOKEN)
438
+ else:
439
+ error_msg = "Initial metadata no longer allowed!"
440
+ raise ValueError(error_msg)
441
+
442
+ def set_trailing_metadata(self, trailing_metadata: MetadataType) -> None:
443
+ with self._state.condition:
444
+ self._state.trailing_metadata = trailing_metadata
445
+
446
+ def trailing_metadata(self) -> Optional[MetadataType]:
447
+ return self._state.trailing_metadata
448
+
449
+ def abort(self, code: grpc.StatusCode, details: str) -> None:
450
+ # treat OK like other invalid arguments: fail the RPC
451
+ if code == grpc.StatusCode.OK:
452
+ _LOGGER.error(
453
+ "abort() called with StatusCode.OK; returning UNKNOWN"
454
+ )
455
+ code = grpc.StatusCode.UNKNOWN
456
+ details = ""
457
+ with self._state.condition:
458
+ self._state.code = code
459
+ self._state.details = _common.encode(details)
460
+ self._state.aborted = True
461
+ raise Exception() # noqa: TRY002
462
+
463
+ def abort_with_status(self, status: grpc.Status) -> None:
464
+ self._state.trailing_metadata = status.trailing_metadata
465
+ self.abort(status.code, status.details)
466
+
467
+ def set_code(self, code: grpc.StatusCode) -> None:
468
+ with self._state.condition:
469
+ self._state.code = code
470
+
471
+ def code(self) -> grpc.StatusCode:
472
+ return self._state.code
473
+
474
+ def set_details(self, details: str) -> None:
475
+ with self._state.condition:
476
+ self._state.details = _common.encode(details)
477
+
478
+ def details(self) -> bytes:
479
+ return self._state.details
480
+
481
+ def _finalize_state(self) -> None:
482
+ pass
483
+
484
+
485
+ class _RequestIterator(object):
486
+ _state: _RPCState
487
+ _call: cygrpc.Call
488
+ _request_deserializer: Optional[DeserializingFunction]
489
+
490
+ def __init__(
491
+ self,
492
+ state: _RPCState,
493
+ call: cygrpc.Call,
494
+ request_deserializer: Optional[DeserializingFunction],
495
+ ):
496
+ self._state = state
497
+ self._call = call
498
+ self._request_deserializer = request_deserializer
499
+
500
+ def _raise_or_start_receive_message(self) -> None:
501
+ if self._state.client is _CANCELLED:
502
+ _raise_rpc_error(self._state)
503
+ elif not _is_rpc_state_active(self._state):
504
+ raise StopIteration()
505
+ else:
506
+ self._call.start_server_batch(
507
+ (cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),),
508
+ _receive_message(
509
+ self._state, self._call, self._request_deserializer
510
+ ),
511
+ )
512
+ self._state.due.add(_RECEIVE_MESSAGE_TOKEN)
513
+
514
+ def _look_for_request(self) -> Any:
515
+ if self._state.client is _CANCELLED:
516
+ _raise_rpc_error(self._state)
517
+ elif (
518
+ self._state.request is None
519
+ and _RECEIVE_MESSAGE_TOKEN not in self._state.due
520
+ ):
521
+ raise StopIteration()
522
+ else:
523
+ request = self._state.request
524
+ self._state.request = None
525
+ return request
526
+
527
+ raise AssertionError() # should never run
528
+
529
+ def _next(self) -> Any:
530
+ with self._state.condition:
531
+ self._raise_or_start_receive_message()
532
+ while True:
533
+ self._state.condition.wait()
534
+ request = self._look_for_request()
535
+ if request is not None:
536
+ return request
537
+
538
+ def __iter__(self) -> _RequestIterator:
539
+ return self
540
+
541
+ def __next__(self) -> Any:
542
+ return self._next()
543
+
544
+ def next(self) -> Any:
545
+ return self._next()
546
+
547
+
548
+ def _unary_request(
549
+ rpc_event: cygrpc.BaseEvent,
550
+ state: _RPCState,
551
+ request_deserializer: Optional[DeserializingFunction],
552
+ ) -> Callable[[], Any]:
553
+ def unary_request():
554
+ with state.condition:
555
+ if not _is_rpc_state_active(state):
556
+ return None
557
+ rpc_event.call.start_server_batch(
558
+ (cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),),
559
+ _receive_message(state, rpc_event.call, request_deserializer),
560
+ )
561
+ state.due.add(_RECEIVE_MESSAGE_TOKEN)
562
+ while True:
563
+ state.condition.wait()
564
+ if state.request is None:
565
+ if state.client is _CLOSED:
566
+ details = (
567
+ '"{}" requires exactly one request message.'.format(
568
+ rpc_event.call_details.method
569
+ )
570
+ )
571
+ _abort(
572
+ state,
573
+ rpc_event.call,
574
+ cygrpc.StatusCode.unimplemented,
575
+ _common.encode(details),
576
+ )
577
+ return None
578
+ if state.client is _CANCELLED:
579
+ return None
580
+ else:
581
+ request = state.request
582
+ state.request = None
583
+ return request
584
+
585
+ return unary_request
586
+
587
+
588
+ def _call_behavior(
589
+ rpc_event: cygrpc.BaseEvent,
590
+ state: _RPCState,
591
+ behavior: ArityAgnosticMethodHandler,
592
+ argument: Any,
593
+ request_deserializer: Optional[DeserializingFunction],
594
+ send_response_callback: Optional[Callable[[ResponseType], None]] = None,
595
+ ) -> Tuple[Union[ResponseType, Iterator[ResponseType]], bool]:
596
+ from grpc import _create_servicer_context
597
+
598
+ with _create_servicer_context(
599
+ rpc_event, state, request_deserializer
600
+ ) as context:
601
+ try:
602
+ response_or_iterator = None
603
+ if send_response_callback is not None:
604
+ response_or_iterator = behavior(
605
+ argument, context, send_response_callback
606
+ )
607
+ else:
608
+ response_or_iterator = behavior(argument, context)
609
+ return response_or_iterator, True
610
+ except Exception as exception: # pylint: disable=broad-except
611
+ with state.condition:
612
+ if state.aborted:
613
+ _abort(
614
+ state,
615
+ rpc_event.call,
616
+ cygrpc.StatusCode.unknown,
617
+ b"RPC Aborted",
618
+ )
619
+ elif exception not in state.rpc_errors:
620
+ try:
621
+ details = "Exception calling application: {}".format(
622
+ exception
623
+ )
624
+ except Exception: # pylint: disable=broad-except
625
+ details = (
626
+ "Calling application raised unprintable Exception!"
627
+ )
628
+ _LOGGER.exception(
629
+ traceback.format_exception(
630
+ type(exception),
631
+ exception,
632
+ exception.__traceback__,
633
+ )
634
+ )
635
+ traceback.print_exc()
636
+ _LOGGER.exception(details)
637
+ _abort(
638
+ state,
639
+ rpc_event.call,
640
+ cygrpc.StatusCode.unknown,
641
+ _common.encode(details),
642
+ )
643
+ return None, False
644
+
645
+
646
+ def _take_response_from_response_iterator(
647
+ rpc_event: cygrpc.BaseEvent,
648
+ state: _RPCState,
649
+ response_iterator: Iterator[ResponseType],
650
+ ) -> Tuple[ResponseType, bool]:
651
+ try:
652
+ return next(response_iterator), True
653
+ except StopIteration:
654
+ return None, True
655
+ except Exception as exception: # pylint: disable=broad-except
656
+ with state.condition:
657
+ if state.aborted:
658
+ _abort(
659
+ state,
660
+ rpc_event.call,
661
+ cygrpc.StatusCode.unknown,
662
+ b"RPC Aborted",
663
+ )
664
+ elif exception not in state.rpc_errors:
665
+ details = "Exception iterating responses: {}".format(exception)
666
+ _LOGGER.exception(details)
667
+ _abort(
668
+ state,
669
+ rpc_event.call,
670
+ cygrpc.StatusCode.unknown,
671
+ _common.encode(details),
672
+ )
673
+ return None, False
674
+
675
+
676
+ def _serialize_response(
677
+ rpc_event: cygrpc.BaseEvent,
678
+ state: _RPCState,
679
+ response: Any,
680
+ response_serializer: Optional[SerializingFunction],
681
+ ) -> Optional[bytes]:
682
+ serialized_response = _common.serialize(response, response_serializer)
683
+ if serialized_response is None:
684
+ with state.condition:
685
+ _abort(
686
+ state,
687
+ rpc_event.call,
688
+ cygrpc.StatusCode.internal,
689
+ b"Failed to serialize response!",
690
+ )
691
+ return None
692
+ return serialized_response
693
+
694
+
695
+ def _get_send_message_op_flags_from_state(
696
+ state: _RPCState,
697
+ ) -> Union[int, cygrpc.WriteFlag]:
698
+ if state.disable_next_compression:
699
+ return cygrpc.WriteFlag.no_compress
700
+ return _EMPTY_FLAGS
701
+
702
+
703
+ def _reset_per_message_state(state: _RPCState) -> None:
704
+ with state.condition:
705
+ state.disable_next_compression = False
706
+
707
+
708
+ def _send_response(
709
+ rpc_event: cygrpc.BaseEvent, state: _RPCState, serialized_response: bytes
710
+ ) -> bool:
711
+ with state.condition:
712
+ if not _is_rpc_state_active(state):
713
+ return False
714
+ if state.initial_metadata_allowed:
715
+ operations = (
716
+ _get_initial_metadata_operation(state, None),
717
+ cygrpc.SendMessageOperation(
718
+ serialized_response,
719
+ _get_send_message_op_flags_from_state(state),
720
+ ),
721
+ )
722
+ state.initial_metadata_allowed = False
723
+ token = _SEND_INITIAL_METADATA_AND_SEND_MESSAGE_TOKEN
724
+ else:
725
+ operations = (
726
+ cygrpc.SendMessageOperation(
727
+ serialized_response,
728
+ _get_send_message_op_flags_from_state(state),
729
+ ),
730
+ )
731
+ token = _SEND_MESSAGE_TOKEN
732
+ rpc_event.call.start_server_batch(
733
+ operations, _send_message(state, token)
734
+ )
735
+ state.due.add(token)
736
+ _reset_per_message_state(state)
737
+ while True:
738
+ state.condition.wait()
739
+ if token not in state.due:
740
+ return _is_rpc_state_active(state)
741
+
742
+
743
+ def _status(
744
+ rpc_event: cygrpc.BaseEvent,
745
+ state: _RPCState,
746
+ serialized_response: Optional[bytes],
747
+ ) -> None:
748
+ with state.condition:
749
+ if state.client is not _CANCELLED:
750
+ code = _completion_code(state)
751
+ details = _details(state)
752
+ operations = [
753
+ cygrpc.SendStatusFromServerOperation(
754
+ state.trailing_metadata, code, details, _EMPTY_FLAGS
755
+ ),
756
+ ]
757
+ if state.initial_metadata_allowed:
758
+ operations.append(_get_initial_metadata_operation(state, None))
759
+ if serialized_response is not None:
760
+ operations.append(
761
+ cygrpc.SendMessageOperation(
762
+ serialized_response,
763
+ _get_send_message_op_flags_from_state(state),
764
+ )
765
+ )
766
+ rpc_event.call.start_server_batch(
767
+ operations,
768
+ _send_status_from_server(state, _SEND_STATUS_FROM_SERVER_TOKEN),
769
+ )
770
+ state.statused = True
771
+ _reset_per_message_state(state)
772
+ state.due.add(_SEND_STATUS_FROM_SERVER_TOKEN)
773
+
774
+
775
+ def _unary_response_in_pool(
776
+ rpc_event: cygrpc.BaseEvent,
777
+ state: _RPCState,
778
+ behavior: ArityAgnosticMethodHandler,
779
+ argument_thunk: Callable[[], Any],
780
+ request_deserializer: Optional[SerializingFunction],
781
+ response_serializer: Optional[SerializingFunction],
782
+ ) -> None:
783
+ cygrpc.install_context_from_request_call_event(rpc_event)
784
+
785
+ try:
786
+ argument = argument_thunk()
787
+ if argument is not None:
788
+ response, proceed = _call_behavior(
789
+ rpc_event, state, behavior, argument, request_deserializer
790
+ )
791
+ if proceed:
792
+ serialized_response = _serialize_response(
793
+ rpc_event, state, response, response_serializer
794
+ )
795
+ if serialized_response is not None:
796
+ _status(rpc_event, state, serialized_response)
797
+ except Exception: # pylint: disable=broad-except
798
+ traceback.print_exc()
799
+ finally:
800
+ cygrpc.uninstall_context()
801
+
802
+
803
+ def _stream_response_in_pool(
804
+ rpc_event: cygrpc.BaseEvent,
805
+ state: _RPCState,
806
+ behavior: ArityAgnosticMethodHandler,
807
+ argument_thunk: Callable[[], Any],
808
+ request_deserializer: Optional[DeserializingFunction],
809
+ response_serializer: Optional[SerializingFunction],
810
+ ) -> None:
811
+ cygrpc.install_context_from_request_call_event(rpc_event)
812
+
813
+ def send_response(response: Any) -> None:
814
+ if response is None:
815
+ _status(rpc_event, state, None)
816
+ else:
817
+ serialized_response = _serialize_response(
818
+ rpc_event, state, response, response_serializer
819
+ )
820
+ if serialized_response is not None:
821
+ _send_response(rpc_event, state, serialized_response)
822
+
823
+ try:
824
+ argument = argument_thunk()
825
+ if argument is not None:
826
+ if (
827
+ hasattr(behavior, "experimental_non_blocking")
828
+ and behavior.experimental_non_blocking
829
+ ):
830
+ _call_behavior(
831
+ rpc_event,
832
+ state,
833
+ behavior,
834
+ argument,
835
+ request_deserializer,
836
+ send_response_callback=send_response,
837
+ )
838
+ else:
839
+ response_iterator, proceed = _call_behavior(
840
+ rpc_event, state, behavior, argument, request_deserializer
841
+ )
842
+ if proceed:
843
+ _send_message_callback_to_blocking_iterator_adapter(
844
+ rpc_event, state, send_response, response_iterator
845
+ )
846
+ except Exception: # pylint: disable=broad-except
847
+ traceback.print_exc()
848
+ finally:
849
+ cygrpc.uninstall_context()
850
+
851
+
852
+ def _is_rpc_state_active(state: _RPCState) -> bool:
853
+ return state.client is not _CANCELLED and not state.statused
854
+
855
+
856
+ def _send_message_callback_to_blocking_iterator_adapter(
857
+ rpc_event: cygrpc.BaseEvent,
858
+ state: _RPCState,
859
+ send_response_callback: Callable[[ResponseType], None],
860
+ response_iterator: Iterator[ResponseType],
861
+ ) -> None:
862
+ while True:
863
+ response, proceed = _take_response_from_response_iterator(
864
+ rpc_event, state, response_iterator
865
+ )
866
+ if proceed:
867
+ send_response_callback(response)
868
+ if not _is_rpc_state_active(state):
869
+ break
870
+ else:
871
+ break
872
+
873
+
874
+ def _select_thread_pool_for_behavior(
875
+ behavior: ArityAgnosticMethodHandler,
876
+ default_thread_pool: futures.ThreadPoolExecutor,
877
+ ) -> futures.ThreadPoolExecutor:
878
+ if hasattr(behavior, "experimental_thread_pool") and isinstance(
879
+ behavior.experimental_thread_pool, futures.ThreadPoolExecutor
880
+ ):
881
+ return behavior.experimental_thread_pool
882
+ return default_thread_pool
883
+
884
+
885
+ def _handle_unary_unary(
886
+ rpc_event: cygrpc.BaseEvent,
887
+ state: _RPCState,
888
+ method_handler: grpc.RpcMethodHandler,
889
+ default_thread_pool: futures.ThreadPoolExecutor,
890
+ ) -> futures.Future:
891
+ unary_request = _unary_request(
892
+ rpc_event, state, method_handler.request_deserializer
893
+ )
894
+ thread_pool = _select_thread_pool_for_behavior(
895
+ method_handler.unary_unary, default_thread_pool
896
+ )
897
+ return thread_pool.submit(
898
+ state.context.run,
899
+ _unary_response_in_pool,
900
+ rpc_event,
901
+ state,
902
+ method_handler.unary_unary,
903
+ unary_request,
904
+ method_handler.request_deserializer,
905
+ method_handler.response_serializer,
906
+ )
907
+
908
+
909
+ def _handle_unary_stream(
910
+ rpc_event: cygrpc.BaseEvent,
911
+ state: _RPCState,
912
+ method_handler: grpc.RpcMethodHandler,
913
+ default_thread_pool: futures.ThreadPoolExecutor,
914
+ ) -> futures.Future:
915
+ unary_request = _unary_request(
916
+ rpc_event, state, method_handler.request_deserializer
917
+ )
918
+ thread_pool = _select_thread_pool_for_behavior(
919
+ method_handler.unary_stream, default_thread_pool
920
+ )
921
+ return thread_pool.submit(
922
+ state.context.run,
923
+ _stream_response_in_pool,
924
+ rpc_event,
925
+ state,
926
+ method_handler.unary_stream,
927
+ unary_request,
928
+ method_handler.request_deserializer,
929
+ method_handler.response_serializer,
930
+ )
931
+
932
+
933
+ def _handle_stream_unary(
934
+ rpc_event: cygrpc.BaseEvent,
935
+ state: _RPCState,
936
+ method_handler: grpc.RpcMethodHandler,
937
+ default_thread_pool: futures.ThreadPoolExecutor,
938
+ ) -> futures.Future:
939
+ request_iterator = _RequestIterator(
940
+ state, rpc_event.call, method_handler.request_deserializer
941
+ )
942
+ thread_pool = _select_thread_pool_for_behavior(
943
+ method_handler.stream_unary, default_thread_pool
944
+ )
945
+ return thread_pool.submit(
946
+ state.context.run,
947
+ _unary_response_in_pool,
948
+ rpc_event,
949
+ state,
950
+ method_handler.stream_unary,
951
+ lambda: request_iterator,
952
+ method_handler.request_deserializer,
953
+ method_handler.response_serializer,
954
+ )
955
+
956
+
957
+ def _handle_stream_stream(
958
+ rpc_event: cygrpc.BaseEvent,
959
+ state: _RPCState,
960
+ method_handler: grpc.RpcMethodHandler,
961
+ default_thread_pool: futures.ThreadPoolExecutor,
962
+ ) -> futures.Future:
963
+ request_iterator = _RequestIterator(
964
+ state, rpc_event.call, method_handler.request_deserializer
965
+ )
966
+ thread_pool = _select_thread_pool_for_behavior(
967
+ method_handler.stream_stream, default_thread_pool
968
+ )
969
+ return thread_pool.submit(
970
+ state.context.run,
971
+ _stream_response_in_pool,
972
+ rpc_event,
973
+ state,
974
+ method_handler.stream_stream,
975
+ lambda: request_iterator,
976
+ method_handler.request_deserializer,
977
+ method_handler.response_serializer,
978
+ )
979
+
980
+
981
+ def _find_method_handler(
982
+ rpc_event: cygrpc.BaseEvent,
983
+ state: _RPCState,
984
+ method_with_handler: _Method,
985
+ interceptor_pipeline: Optional[_interceptor._ServicePipeline],
986
+ ) -> Optional[grpc.RpcMethodHandler]:
987
+ def query_handlers(
988
+ handler_call_details: _HandlerCallDetails,
989
+ ) -> Optional[grpc.RpcMethodHandler]:
990
+ return method_with_handler.handler(handler_call_details)
991
+
992
+ method_name = method_with_handler.name()
993
+ if not method_name:
994
+ method_name = _common.decode(rpc_event.call_details.method)
995
+
996
+ handler_call_details = _HandlerCallDetails(
997
+ method_name,
998
+ rpc_event.invocation_metadata,
999
+ )
1000
+
1001
+ if interceptor_pipeline is not None:
1002
+ return state.context.run(
1003
+ interceptor_pipeline.execute, query_handlers, handler_call_details
1004
+ )
1005
+ return state.context.run(query_handlers, handler_call_details)
1006
+
1007
+
1008
+ def _reject_rpc(
1009
+ rpc_event: cygrpc.BaseEvent,
1010
+ rpc_state: _RPCState,
1011
+ status: cygrpc.StatusCode,
1012
+ details: bytes,
1013
+ ):
1014
+ operations = (
1015
+ _get_initial_metadata_operation(rpc_state, None),
1016
+ cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS),
1017
+ cygrpc.SendStatusFromServerOperation(
1018
+ None, status, details, _EMPTY_FLAGS
1019
+ ),
1020
+ )
1021
+ rpc_event.call.start_server_batch(
1022
+ operations,
1023
+ lambda _ignored_event: (
1024
+ rpc_state,
1025
+ (),
1026
+ ),
1027
+ )
1028
+
1029
+
1030
+ def _handle_with_method_handler(
1031
+ rpc_event: cygrpc.BaseEvent,
1032
+ state: _RPCState,
1033
+ method_handler: grpc.RpcMethodHandler,
1034
+ thread_pool: futures.ThreadPoolExecutor,
1035
+ ) -> futures.Future:
1036
+ with state.condition:
1037
+ rpc_event.call.start_server_batch(
1038
+ (cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS),),
1039
+ _receive_close_on_server(state),
1040
+ )
1041
+ state.due.add(_RECEIVE_CLOSE_ON_SERVER_TOKEN)
1042
+ if method_handler.request_streaming:
1043
+ if method_handler.response_streaming:
1044
+ return _handle_stream_stream(
1045
+ rpc_event, state, method_handler, thread_pool
1046
+ )
1047
+ return _handle_stream_unary(
1048
+ rpc_event, state, method_handler, thread_pool
1049
+ )
1050
+ if method_handler.response_streaming:
1051
+ return _handle_unary_stream(
1052
+ rpc_event, state, method_handler, thread_pool
1053
+ )
1054
+ return _handle_unary_unary(
1055
+ rpc_event, state, method_handler, thread_pool
1056
+ )
1057
+
1058
+
1059
+ def _handle_call(
1060
+ rpc_event: cygrpc.BaseEvent,
1061
+ method_with_handler: _Method,
1062
+ interceptor_pipeline: Optional[_interceptor._ServicePipeline],
1063
+ thread_pool: futures.ThreadPoolExecutor,
1064
+ concurrency_exceeded: bool,
1065
+ ) -> Tuple[Optional[_RPCState], Optional[futures.Future]]:
1066
+ """Handles RPC based on provided handlers.
1067
+
1068
+ When receiving a call event from Core, registered method will have its
1069
+ name as tag, we pass the tag as registered_method_name to this method,
1070
+ then we can find the handler in registered_method_handlers based on
1071
+ the method name.
1072
+
1073
+ For call event with unregistered method, the method name will be included
1074
+ in rpc_event.call_details.method and we need to query the generics handlers
1075
+ to find the actual handler.
1076
+ """
1077
+ if not rpc_event.success:
1078
+ return None, None
1079
+ if rpc_event.call_details.method or method_with_handler.name():
1080
+ rpc_state = _RPCState()
1081
+ try:
1082
+ method_handler = _find_method_handler(
1083
+ rpc_event,
1084
+ rpc_state,
1085
+ method_with_handler,
1086
+ interceptor_pipeline,
1087
+ )
1088
+ except Exception as exception: # pylint: disable=broad-except
1089
+ details = "Exception servicing handler: {}".format(exception)
1090
+ _LOGGER.exception(details)
1091
+ _reject_rpc(
1092
+ rpc_event,
1093
+ rpc_state,
1094
+ cygrpc.StatusCode.unknown,
1095
+ b"Error in service handler!",
1096
+ )
1097
+ return rpc_state, None
1098
+ if method_handler is None:
1099
+ _reject_rpc(
1100
+ rpc_event,
1101
+ rpc_state,
1102
+ cygrpc.StatusCode.unimplemented,
1103
+ b"Method not found!",
1104
+ )
1105
+ return rpc_state, None
1106
+ if concurrency_exceeded:
1107
+ _reject_rpc(
1108
+ rpc_event,
1109
+ rpc_state,
1110
+ cygrpc.StatusCode.resource_exhausted,
1111
+ b"Concurrent RPC limit exceeded!",
1112
+ )
1113
+ return rpc_state, None
1114
+ return (
1115
+ rpc_state,
1116
+ _handle_with_method_handler(
1117
+ rpc_event, rpc_state, method_handler, thread_pool
1118
+ ),
1119
+ )
1120
+ return None, None
1121
+
1122
+
1123
+ @enum.unique
1124
+ class _ServerStage(enum.Enum):
1125
+ STOPPED = "stopped"
1126
+ STARTED = "started"
1127
+ GRACE = "grace"
1128
+
1129
+
1130
+ class _ServerState(object):
1131
+ lock: threading.RLock
1132
+ completion_queue: cygrpc.CompletionQueue
1133
+ server: cygrpc.Server
1134
+ generic_handlers: List[grpc.GenericRpcHandler]
1135
+ registered_method_handlers: Dict[str, grpc.RpcMethodHandler]
1136
+ interceptor_pipeline: Optional[_interceptor._ServicePipeline]
1137
+ thread_pool: futures.ThreadPoolExecutor
1138
+ stage: _ServerStage
1139
+ termination_event: threading.Event
1140
+ shutdown_events: List[threading.Event]
1141
+ maximum_concurrent_rpcs: Optional[int]
1142
+ active_rpc_count: int
1143
+ rpc_states: Set[_RPCState]
1144
+ due: Set[str]
1145
+ server_deallocated: bool
1146
+
1147
+ # pylint: disable=too-many-arguments
1148
+ def __init__(
1149
+ self,
1150
+ completion_queue: cygrpc.CompletionQueue,
1151
+ server: cygrpc.Server,
1152
+ generic_handlers: Sequence[grpc.GenericRpcHandler],
1153
+ interceptor_pipeline: Optional[_interceptor._ServicePipeline],
1154
+ thread_pool: futures.ThreadPoolExecutor,
1155
+ maximum_concurrent_rpcs: Optional[int],
1156
+ ):
1157
+ self.lock = threading.RLock()
1158
+ self.completion_queue = completion_queue
1159
+ self.server = server
1160
+ self.generic_handlers = list(generic_handlers)
1161
+ self.interceptor_pipeline = interceptor_pipeline
1162
+ self.thread_pool = thread_pool
1163
+ self.stage = _ServerStage.STOPPED
1164
+ self.termination_event = threading.Event()
1165
+ self.shutdown_events = [self.termination_event]
1166
+ self.maximum_concurrent_rpcs = maximum_concurrent_rpcs
1167
+ self.active_rpc_count = 0
1168
+ self.registered_method_handlers = {}
1169
+
1170
+ # TODO(https://github.com/grpc/grpc/issues/6597): eliminate these fields.
1171
+ self.rpc_states = set()
1172
+ self.due = set()
1173
+
1174
+ # A "volatile" flag to interrupt the daemon serving thread
1175
+ self.server_deallocated = False
1176
+
1177
+
1178
+ def _add_generic_handlers(
1179
+ state: _ServerState, generic_handlers: Iterable[grpc.GenericRpcHandler]
1180
+ ) -> None:
1181
+ with state.lock:
1182
+ state.generic_handlers.extend(generic_handlers)
1183
+
1184
+
1185
+ def _add_registered_method_handlers(
1186
+ state: _ServerState, method_handlers: Dict[str, grpc.RpcMethodHandler]
1187
+ ) -> None:
1188
+ with state.lock:
1189
+ state.registered_method_handlers.update(method_handlers)
1190
+
1191
+
1192
+ def _add_insecure_port(state: _ServerState, address: bytes) -> int:
1193
+ with state.lock:
1194
+ return state.server.add_http2_port(address)
1195
+
1196
+
1197
+ def _add_secure_port(
1198
+ state: _ServerState,
1199
+ address: bytes,
1200
+ server_credentials: grpc.ServerCredentials,
1201
+ ) -> int:
1202
+ with state.lock:
1203
+ return state.server.add_http2_port(
1204
+ address, server_credentials._credentials
1205
+ )
1206
+
1207
+
1208
+ def _request_call(state: _ServerState) -> None:
1209
+ state.server.request_call(
1210
+ state.completion_queue, state.completion_queue, _REQUEST_CALL_TAG
1211
+ )
1212
+ state.due.add(_REQUEST_CALL_TAG)
1213
+
1214
+
1215
+ def _request_registered_call(state: _ServerState, method: str) -> None:
1216
+ registered_call_tag = method
1217
+ state.server.request_registered_call(
1218
+ state.completion_queue,
1219
+ state.completion_queue,
1220
+ method,
1221
+ registered_call_tag,
1222
+ )
1223
+ state.due.add(registered_call_tag)
1224
+
1225
+
1226
+ # TODO(https://github.com/grpc/grpc/issues/6597): delete this function.
1227
+ def _stop_serving(state: _ServerState) -> bool:
1228
+ if not state.rpc_states and not state.due:
1229
+ state.server.destroy()
1230
+ for shutdown_event in state.shutdown_events:
1231
+ shutdown_event.set()
1232
+ state.stage = _ServerStage.STOPPED
1233
+ return True
1234
+ return False
1235
+
1236
+
1237
+ def _on_call_completed(state: _ServerState) -> None:
1238
+ with state.lock:
1239
+ state.active_rpc_count -= 1
1240
+
1241
+
1242
+ # pylint: disable=too-many-branches
1243
+ def _process_event_and_continue(
1244
+ state: _ServerState, event: cygrpc.BaseEvent
1245
+ ) -> bool:
1246
+ should_continue = True
1247
+ if event.tag is _SHUTDOWN_TAG:
1248
+ with state.lock:
1249
+ state.due.remove(_SHUTDOWN_TAG)
1250
+ if _stop_serving(state):
1251
+ should_continue = False
1252
+ elif (
1253
+ event.tag is _REQUEST_CALL_TAG
1254
+ or event.tag in state.registered_method_handlers
1255
+ ):
1256
+ registered_method_name = None
1257
+ if event.tag in state.registered_method_handlers:
1258
+ registered_method_name = event.tag
1259
+ method_with_handler = _RegisteredMethod(
1260
+ registered_method_name,
1261
+ state.registered_method_handlers.get(
1262
+ registered_method_name, None
1263
+ ),
1264
+ )
1265
+ else:
1266
+ method_with_handler = _GenericMethod(
1267
+ state.generic_handlers,
1268
+ )
1269
+ with state.lock:
1270
+ state.due.remove(event.tag)
1271
+ concurrency_exceeded = (
1272
+ state.maximum_concurrent_rpcs is not None
1273
+ and state.active_rpc_count >= state.maximum_concurrent_rpcs
1274
+ )
1275
+ rpc_state, rpc_future = _handle_call(
1276
+ event,
1277
+ method_with_handler,
1278
+ state.interceptor_pipeline,
1279
+ state.thread_pool,
1280
+ concurrency_exceeded,
1281
+ )
1282
+ if rpc_state is not None:
1283
+ state.rpc_states.add(rpc_state)
1284
+ if rpc_future is not None:
1285
+ state.active_rpc_count += 1
1286
+ rpc_future.add_done_callback(
1287
+ lambda _unused_future: _on_call_completed(state)
1288
+ )
1289
+ if state.stage is _ServerStage.STARTED:
1290
+ if registered_method_name in state.registered_method_handlers:
1291
+ _request_registered_call(state, registered_method_name)
1292
+ else:
1293
+ _request_call(state)
1294
+ elif _stop_serving(state):
1295
+ should_continue = False
1296
+ else:
1297
+ rpc_state, callbacks = event.tag(event)
1298
+ for callback in callbacks:
1299
+ try:
1300
+ callback()
1301
+ except Exception: # pylint: disable=broad-except
1302
+ _LOGGER.exception("Exception calling callback!")
1303
+ if rpc_state is not None:
1304
+ with state.lock:
1305
+ state.rpc_states.remove(rpc_state)
1306
+ if _stop_serving(state):
1307
+ should_continue = False
1308
+ return should_continue
1309
+
1310
+
1311
+ def _serve(state: _ServerState) -> None:
1312
+ while True:
1313
+ timeout = time.time() + _DEALLOCATED_SERVER_CHECK_PERIOD_S
1314
+ event = state.completion_queue.poll(timeout)
1315
+ if state.server_deallocated:
1316
+ _begin_shutdown_once(state)
1317
+ is_timeout = (
1318
+ event.completion_type == cygrpc.CompletionType.queue_timeout
1319
+ )
1320
+ if not is_timeout and not _process_event_and_continue(state, event):
1321
+ return
1322
+ # We want to force the deletion of the previous event
1323
+ # ~before~ we poll again; if the event has a reference
1324
+ # to a shutdown Call object, this can induce spinlock.
1325
+ event = None
1326
+
1327
+
1328
+ def _begin_shutdown_once(state: _ServerState) -> None:
1329
+ with state.lock:
1330
+ if state.stage is _ServerStage.STARTED:
1331
+ state.server.shutdown(state.completion_queue, _SHUTDOWN_TAG)
1332
+ state.stage = _ServerStage.GRACE
1333
+ state.due.add(_SHUTDOWN_TAG)
1334
+
1335
+
1336
+ def _stop(state: _ServerState, grace: Optional[float]) -> threading.Event:
1337
+ with state.lock:
1338
+ if state.stage is _ServerStage.STOPPED:
1339
+ shutdown_event = threading.Event()
1340
+ shutdown_event.set()
1341
+ return shutdown_event
1342
+ _begin_shutdown_once(state)
1343
+ shutdown_event = threading.Event()
1344
+ state.shutdown_events.append(shutdown_event)
1345
+ if grace is None:
1346
+ state.server.cancel_all_calls()
1347
+ else:
1348
+
1349
+ def cancel_all_calls_after_grace():
1350
+ shutdown_event.wait(timeout=grace)
1351
+ with state.lock:
1352
+ state.server.cancel_all_calls()
1353
+
1354
+ thread = threading.Thread(target=cancel_all_calls_after_grace)
1355
+ thread.start()
1356
+ return shutdown_event
1357
+ shutdown_event.wait()
1358
+ return shutdown_event
1359
+
1360
+
1361
+ def _start(state: _ServerState) -> None:
1362
+ with state.lock:
1363
+ if state.stage is not _ServerStage.STOPPED:
1364
+ error_msg = "Cannot start already-started server!"
1365
+ raise ValueError(error_msg)
1366
+ state.server.start()
1367
+ state.stage = _ServerStage.STARTED
1368
+ # Request a call for each registered method so we can handle any of them.
1369
+ for method in state.registered_method_handlers:
1370
+ _request_registered_call(state, method)
1371
+ # Also request a call for non-registered method.
1372
+ _request_call(state)
1373
+ thread = threading.Thread(target=_serve, args=(state,))
1374
+ thread.daemon = True
1375
+ thread.start()
1376
+
1377
+
1378
+ def _validate_generic_rpc_handlers(
1379
+ generic_rpc_handlers: Iterable[grpc.GenericRpcHandler],
1380
+ ) -> None:
1381
+ for generic_rpc_handler in generic_rpc_handlers:
1382
+ service_attribute = getattr(generic_rpc_handler, "service", None)
1383
+ if service_attribute is None:
1384
+ error_msg = (
1385
+ f'"{generic_rpc_handler}" must conform to'
1386
+ 'grpc.GenericRpcHandler type but does not have "service" method!'
1387
+ )
1388
+ raise AttributeError(error_msg)
1389
+
1390
+
1391
+ def _augment_options(
1392
+ base_options: Sequence[ChannelArgumentType],
1393
+ compression: Optional[grpc.Compression],
1394
+ xds: bool,
1395
+ ) -> Sequence[ChannelArgumentType]:
1396
+ compression_option = _compression.create_channel_option(compression)
1397
+ maybe_server_call_tracer_factory_option = (
1398
+ _observability.create_server_call_tracer_factory_option(xds)
1399
+ )
1400
+ return (
1401
+ tuple(base_options)
1402
+ + compression_option
1403
+ + maybe_server_call_tracer_factory_option
1404
+ )
1405
+
1406
+
1407
+ class _Server(grpc.Server):
1408
+ _state: _ServerState
1409
+
1410
+ # pylint: disable=too-many-arguments
1411
+ def __init__(
1412
+ self,
1413
+ thread_pool: futures.ThreadPoolExecutor,
1414
+ generic_handlers: Sequence[grpc.GenericRpcHandler],
1415
+ interceptors: Sequence[grpc.ServerInterceptor],
1416
+ options: Sequence[ChannelArgumentType],
1417
+ maximum_concurrent_rpcs: Optional[int],
1418
+ compression: Optional[grpc.Compression],
1419
+ xds: bool,
1420
+ ):
1421
+ completion_queue = cygrpc.CompletionQueue()
1422
+ server = cygrpc.Server(_augment_options(options, compression, xds), xds)
1423
+ server.register_completion_queue(completion_queue)
1424
+ self._state = _ServerState(
1425
+ completion_queue,
1426
+ server,
1427
+ generic_handlers,
1428
+ _interceptor.service_pipeline(interceptors),
1429
+ thread_pool,
1430
+ maximum_concurrent_rpcs,
1431
+ )
1432
+ self._cy_server = server
1433
+
1434
+ def add_generic_rpc_handlers(
1435
+ self, generic_rpc_handlers: Iterable[grpc.GenericRpcHandler]
1436
+ ) -> None:
1437
+ _validate_generic_rpc_handlers(generic_rpc_handlers)
1438
+ _add_generic_handlers(self._state, generic_rpc_handlers)
1439
+
1440
+ def add_registered_method_handlers(
1441
+ self,
1442
+ service_name: str,
1443
+ method_handlers: Dict[str, grpc.RpcMethodHandler],
1444
+ ) -> None:
1445
+ # Can't register method once server started.
1446
+ with self._state.lock:
1447
+ if self._state.stage is _ServerStage.STARTED:
1448
+ return
1449
+
1450
+ # TODO(xuanwn): We should validate method_handlers first.
1451
+ method_to_handlers = {
1452
+ _common.fully_qualified_method(service_name, method): method_handler
1453
+ for method, method_handler in method_handlers.items()
1454
+ }
1455
+ for fully_qualified_method in method_to_handlers:
1456
+ self._cy_server.register_method(fully_qualified_method)
1457
+ _add_registered_method_handlers(self._state, method_to_handlers)
1458
+
1459
+ def add_insecure_port(self, address: str) -> int:
1460
+ return _common.validate_port_binding_result(
1461
+ address, _add_insecure_port(self._state, _common.encode(address))
1462
+ )
1463
+
1464
+ def add_secure_port(
1465
+ self, address: str, server_credentials: grpc.ServerCredentials
1466
+ ) -> int:
1467
+ return _common.validate_port_binding_result(
1468
+ address,
1469
+ _add_secure_port(
1470
+ self._state, _common.encode(address), server_credentials
1471
+ ),
1472
+ )
1473
+
1474
+ def start(self) -> None:
1475
+ _start(self._state)
1476
+
1477
+ def wait_for_termination(self, timeout: Optional[float] = None) -> bool:
1478
+ # NOTE(https://bugs.python.org/issue35935)
1479
+ # Remove this workaround once threading.Event.wait() is working with
1480
+ # CTRL+C across platforms.
1481
+ return _common.wait(
1482
+ self._state.termination_event.wait,
1483
+ self._state.termination_event.is_set,
1484
+ timeout=timeout,
1485
+ )
1486
+
1487
+ def stop(self, grace: Optional[float]) -> threading.Event:
1488
+ return _stop(self._state, grace)
1489
+
1490
+ def __del__(self):
1491
+ if hasattr(self, "_state"):
1492
+ # We can not grab a lock in __del__(), so set a flag to signal the
1493
+ # serving daemon thread (if it exists) to initiate shutdown.
1494
+ self._state.server_deallocated = True
1495
+
1496
+
1497
+ def create_server(
1498
+ thread_pool: futures.ThreadPoolExecutor,
1499
+ generic_rpc_handlers: Sequence[grpc.GenericRpcHandler],
1500
+ interceptors: Sequence[grpc.ServerInterceptor],
1501
+ options: Sequence[ChannelArgumentType],
1502
+ maximum_concurrent_rpcs: Optional[int],
1503
+ compression: Optional[grpc.Compression],
1504
+ xds: bool,
1505
+ ) -> _Server:
1506
+ _validate_generic_rpc_handlers(generic_rpc_handlers)
1507
+ return _Server(
1508
+ thread_pool,
1509
+ generic_rpc_handlers,
1510
+ interceptors,
1511
+ options,
1512
+ maximum_concurrent_rpcs,
1513
+ compression,
1514
+ xds,
1515
+ )
loan-advisor-agent/.venv/Lib/site-packages/grpc/_simple_stubs.py ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The 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
+ """Functions that obviate explicit stubs and explicit channels."""
15
+
16
+ import collections
17
+ import datetime
18
+ import logging
19
+ import os
20
+ import threading
21
+ from typing import (
22
+ Any,
23
+ AnyStr,
24
+ Callable,
25
+ Dict,
26
+ Iterator,
27
+ Optional,
28
+ Sequence,
29
+ Tuple,
30
+ TypeVar,
31
+ Union,
32
+ )
33
+
34
+ import grpc
35
+ from grpc.experimental import experimental_api
36
+
37
+ RequestType = TypeVar("RequestType")
38
+ ResponseType = TypeVar("ResponseType")
39
+
40
+ OptionsType = Sequence[Tuple[str, str]]
41
+ CacheKey = Tuple[
42
+ str,
43
+ OptionsType,
44
+ Optional[grpc.ChannelCredentials],
45
+ Optional[grpc.Compression],
46
+ ]
47
+
48
+ _LOGGER = logging.getLogger(__name__)
49
+
50
+ _EVICTION_PERIOD_KEY = "GRPC_PYTHON_MANAGED_CHANNEL_EVICTION_SECONDS"
51
+ if _EVICTION_PERIOD_KEY in os.environ:
52
+ _EVICTION_PERIOD = datetime.timedelta(
53
+ seconds=float(os.environ[_EVICTION_PERIOD_KEY])
54
+ )
55
+ _LOGGER.debug(
56
+ "Setting managed channel eviction period to %s", _EVICTION_PERIOD
57
+ )
58
+ else:
59
+ _EVICTION_PERIOD = datetime.timedelta(minutes=10)
60
+
61
+ _MAXIMUM_CHANNELS_KEY = "GRPC_PYTHON_MANAGED_CHANNEL_MAXIMUM"
62
+ if _MAXIMUM_CHANNELS_KEY in os.environ:
63
+ _MAXIMUM_CHANNELS = int(os.environ[_MAXIMUM_CHANNELS_KEY])
64
+ _LOGGER.debug("Setting maximum managed channels to %d", _MAXIMUM_CHANNELS)
65
+ else:
66
+ _MAXIMUM_CHANNELS = 2**8
67
+
68
+ _DEFAULT_TIMEOUT_KEY = "GRPC_PYTHON_DEFAULT_TIMEOUT_SECONDS"
69
+ if _DEFAULT_TIMEOUT_KEY in os.environ:
70
+ _DEFAULT_TIMEOUT = float(os.environ[_DEFAULT_TIMEOUT_KEY])
71
+ _LOGGER.debug("Setting default timeout seconds to %f", _DEFAULT_TIMEOUT)
72
+ else:
73
+ _DEFAULT_TIMEOUT = 60.0
74
+
75
+
76
+ def _create_channel(
77
+ target: str,
78
+ options: Sequence[Tuple[str, str]],
79
+ channel_credentials: Optional[grpc.ChannelCredentials],
80
+ compression: Optional[grpc.Compression],
81
+ ) -> grpc.Channel:
82
+ debug_msg = (
83
+ f"Creating secure channel with credentials '{channel_credentials}', "
84
+ f"options '{options}' and compression '{compression}'"
85
+ )
86
+ _LOGGER.debug(debug_msg)
87
+ return grpc.secure_channel(
88
+ target,
89
+ credentials=channel_credentials,
90
+ options=options,
91
+ compression=compression,
92
+ )
93
+
94
+
95
+ class ChannelCache:
96
+ # NOTE(rbellevi): Untyped due to reference cycle.
97
+ _singleton = None
98
+ _lock: threading.RLock = threading.RLock()
99
+ _condition: threading.Condition = threading.Condition(lock=_lock)
100
+ _eviction_ready: threading.Event = threading.Event()
101
+
102
+ _mapping: Dict[CacheKey, Tuple[grpc.Channel, datetime.datetime]]
103
+ _eviction_thread: threading.Thread
104
+
105
+ def __init__(self):
106
+ self._mapping = collections.OrderedDict()
107
+ self._eviction_thread = threading.Thread(
108
+ target=ChannelCache._perform_evictions, daemon=True
109
+ )
110
+ self._eviction_thread.start()
111
+
112
+ @staticmethod
113
+ def get():
114
+ with ChannelCache._lock:
115
+ if ChannelCache._singleton is None:
116
+ ChannelCache._singleton = ChannelCache()
117
+ ChannelCache._eviction_ready.wait()
118
+ return ChannelCache._singleton
119
+
120
+ def _evict_locked(self, key: CacheKey):
121
+ channel, _ = self._mapping.pop(key)
122
+ _LOGGER.debug(
123
+ "Evicting channel %s with configuration %s.", channel, key
124
+ )
125
+ channel.close()
126
+ del channel
127
+
128
+ @staticmethod
129
+ def _perform_evictions():
130
+ while True:
131
+ with ChannelCache._lock:
132
+ ChannelCache._eviction_ready.set()
133
+ if not ChannelCache._singleton._mapping:
134
+ ChannelCache._condition.wait()
135
+ elif len(ChannelCache._singleton._mapping) > _MAXIMUM_CHANNELS:
136
+ key = next(iter(ChannelCache._singleton._mapping.keys()))
137
+ ChannelCache._singleton._evict_locked(key)
138
+ # And immediately reevaluate.
139
+ else:
140
+ key, (_, eviction_time) = next(
141
+ iter(ChannelCache._singleton._mapping.items())
142
+ )
143
+ now = datetime.datetime.now()
144
+ if eviction_time <= now:
145
+ ChannelCache._singleton._evict_locked(key)
146
+ continue
147
+ time_to_eviction = (eviction_time - now).total_seconds()
148
+ # NOTE: We aim to *eventually* coalesce to a state in
149
+ # which no overdue channels are in the cache and the
150
+ # length of the cache is longer than _MAXIMUM_CHANNELS.
151
+ # We tolerate momentary states in which these two
152
+ # criteria are not met.
153
+ ChannelCache._condition.wait(timeout=time_to_eviction)
154
+
155
+ def get_channel(
156
+ self,
157
+ target: str,
158
+ options: Sequence[Tuple[str, str]],
159
+ channel_credentials: Optional[grpc.ChannelCredentials],
160
+ insecure: bool,
161
+ compression: Optional[grpc.Compression],
162
+ method: str,
163
+ _registered_method: bool,
164
+ ) -> Tuple[grpc.Channel, Optional[int]]:
165
+ """Get a channel from cache or creates a new channel.
166
+
167
+ This method also takes care of register method for channel,
168
+ which means we'll register a new call handle if we're calling a
169
+ non-registered method for an existing channel.
170
+
171
+ Returns:
172
+ A tuple with two items. The first item is the channel, second item is
173
+ the call handle if the method is registered, None if it's not registered.
174
+ """
175
+ if insecure and channel_credentials:
176
+ raise ValueError(
177
+ "The insecure option is mutually exclusive with "
178
+ + "the channel_credentials option. Please use one "
179
+ + "or the other."
180
+ )
181
+ if insecure:
182
+ channel_credentials = (
183
+ grpc.experimental.insecure_channel_credentials()
184
+ )
185
+ elif channel_credentials is None:
186
+ _LOGGER.debug("Defaulting to SSL channel credentials.")
187
+ channel_credentials = grpc.ssl_channel_credentials()
188
+ key = (target, options, channel_credentials, compression)
189
+ with self._lock:
190
+ channel_data = self._mapping.get(key, None)
191
+ call_handle = None
192
+ if channel_data is not None:
193
+ channel = channel_data[0]
194
+ # Register a new call handle if we're calling a registered method for an
195
+ # existing channel and this method is not registered.
196
+ if _registered_method:
197
+ call_handle = channel._get_registered_call_handle(method)
198
+ self._mapping.pop(key)
199
+ self._mapping[key] = (
200
+ channel,
201
+ datetime.datetime.now() + _EVICTION_PERIOD,
202
+ )
203
+ return channel, call_handle
204
+ channel = _create_channel(
205
+ target, options, channel_credentials, compression
206
+ )
207
+ if _registered_method:
208
+ call_handle = channel._get_registered_call_handle(method)
209
+ self._mapping[key] = (
210
+ channel,
211
+ datetime.datetime.now() + _EVICTION_PERIOD,
212
+ )
213
+ if (
214
+ len(self._mapping) == 1
215
+ or len(self._mapping) >= _MAXIMUM_CHANNELS
216
+ ):
217
+ self._condition.notify()
218
+ return channel, call_handle
219
+
220
+ def _test_only_channel_count(self) -> int:
221
+ with self._lock:
222
+ return len(self._mapping)
223
+
224
+
225
+ @experimental_api
226
+ # pylint: disable=too-many-locals
227
+ def unary_unary(
228
+ request: RequestType,
229
+ target: str,
230
+ method: str,
231
+ request_serializer: Optional[Callable[[Any], bytes]] = None,
232
+ response_deserializer: Optional[Callable[[bytes], Any]] = None,
233
+ options: Sequence[Tuple[AnyStr, AnyStr]] = (),
234
+ channel_credentials: Optional[grpc.ChannelCredentials] = None,
235
+ insecure: bool = False,
236
+ call_credentials: Optional[grpc.CallCredentials] = None,
237
+ compression: Optional[grpc.Compression] = None,
238
+ wait_for_ready: Optional[bool] = None,
239
+ timeout: Optional[float] = _DEFAULT_TIMEOUT,
240
+ metadata: Optional[Sequence[Tuple[str, Union[str, bytes]]]] = None,
241
+ _registered_method: Optional[bool] = False,
242
+ ) -> ResponseType:
243
+ """Invokes a unary-unary RPC without an explicitly specified channel.
244
+
245
+ THIS IS AN EXPERIMENTAL API.
246
+
247
+ This is backed by a per-process cache of channels. Channels are evicted
248
+ from the cache after a fixed period by a background. Channels will also be
249
+ evicted if more than a configured maximum accumulate.
250
+
251
+ The default eviction period is 10 minutes. One may set the environment
252
+ variable "GRPC_PYTHON_MANAGED_CHANNEL_EVICTION_SECONDS" to configure this.
253
+
254
+ The default maximum number of channels is 256. One may set the
255
+ environment variable "GRPC_PYTHON_MANAGED_CHANNEL_MAXIMUM" to configure
256
+ this.
257
+
258
+ Args:
259
+ request: An iterator that yields request values for the RPC.
260
+ target: The server address.
261
+ method: The name of the RPC method.
262
+ request_serializer: Optional :term:`serializer` for serializing the request
263
+ message. Request goes unserialized in case None is passed.
264
+ response_deserializer: Optional :term:`deserializer` for deserializing the response
265
+ message. Response goes undeserialized in case None is passed.
266
+ options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC Core
267
+ runtime) to configure the channel.
268
+ channel_credentials: A credential applied to the whole channel, e.g. the
269
+ return value of grpc.ssl_channel_credentials() or
270
+ grpc.insecure_channel_credentials().
271
+ insecure: If True, specifies channel_credentials as
272
+ :term:`grpc.insecure_channel_credentials()`. This option is mutually
273
+ exclusive with the `channel_credentials` option.
274
+ call_credentials: A call credential applied to each call individually,
275
+ e.g. the output of grpc.metadata_call_credentials() or
276
+ grpc.access_token_call_credentials().
277
+ compression: An optional value indicating the compression method to be
278
+ used over the lifetime of the channel, e.g. grpc.Compression.Gzip.
279
+ wait_for_ready: An optional flag indicating whether the RPC should fail
280
+ immediately if the connection is not ready at the time the RPC is
281
+ invoked, or if it should wait until the connection to the server
282
+ becomes ready. When using this option, the user will likely also want
283
+ to set a timeout. Defaults to True.
284
+ timeout: An optional duration of time in seconds to allow for the RPC,
285
+ after which an exception will be raised. If timeout is unspecified,
286
+ defaults to a timeout controlled by the
287
+ GRPC_PYTHON_DEFAULT_TIMEOUT_SECONDS environment variable. If that is
288
+ unset, defaults to 60 seconds. Supply a value of None to indicate that
289
+ no timeout should be enforced.
290
+ metadata: Optional metadata to send to the server.
291
+
292
+ Returns:
293
+ The response to the RPC.
294
+ """
295
+ channel, method_handle = ChannelCache.get().get_channel(
296
+ target,
297
+ options,
298
+ channel_credentials,
299
+ insecure,
300
+ compression,
301
+ method,
302
+ _registered_method,
303
+ )
304
+ multicallable = channel.unary_unary(
305
+ method, request_serializer, response_deserializer, method_handle
306
+ )
307
+ wait_for_ready = wait_for_ready if wait_for_ready is not None else True
308
+ return multicallable(
309
+ request,
310
+ metadata=metadata,
311
+ wait_for_ready=wait_for_ready,
312
+ credentials=call_credentials,
313
+ timeout=timeout,
314
+ )
315
+
316
+
317
+ @experimental_api
318
+ # pylint: disable=too-many-locals
319
+ def unary_stream(
320
+ request: RequestType,
321
+ target: str,
322
+ method: str,
323
+ request_serializer: Optional[Callable[[Any], bytes]] = None,
324
+ response_deserializer: Optional[Callable[[bytes], Any]] = None,
325
+ options: Sequence[Tuple[AnyStr, AnyStr]] = (),
326
+ channel_credentials: Optional[grpc.ChannelCredentials] = None,
327
+ insecure: bool = False,
328
+ call_credentials: Optional[grpc.CallCredentials] = None,
329
+ compression: Optional[grpc.Compression] = None,
330
+ wait_for_ready: Optional[bool] = None,
331
+ timeout: Optional[float] = _DEFAULT_TIMEOUT,
332
+ metadata: Optional[Sequence[Tuple[str, Union[str, bytes]]]] = None,
333
+ _registered_method: Optional[bool] = False,
334
+ ) -> Iterator[ResponseType]:
335
+ """Invokes a unary-stream RPC without an explicitly specified channel.
336
+
337
+ THIS IS AN EXPERIMENTAL API.
338
+
339
+ This is backed by a per-process cache of channels. Channels are evicted
340
+ from the cache after a fixed period by a background. Channels will also be
341
+ evicted if more than a configured maximum accumulate.
342
+
343
+ The default eviction period is 10 minutes. One may set the environment
344
+ variable "GRPC_PYTHON_MANAGED_CHANNEL_EVICTION_SECONDS" to configure this.
345
+
346
+ The default maximum number of channels is 256. One may set the
347
+ environment variable "GRPC_PYTHON_MANAGED_CHANNEL_MAXIMUM" to configure
348
+ this.
349
+
350
+ Args:
351
+ request: An iterator that yields request values for the RPC.
352
+ target: The server address.
353
+ method: The name of the RPC method.
354
+ request_serializer: Optional :term:`serializer` for serializing the request
355
+ message. Request goes unserialized in case None is passed.
356
+ response_deserializer: Optional :term:`deserializer` for deserializing the response
357
+ message. Response goes undeserialized in case None is passed.
358
+ options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC Core
359
+ runtime) to configure the channel.
360
+ channel_credentials: A credential applied to the whole channel, e.g. the
361
+ return value of grpc.ssl_channel_credentials().
362
+ insecure: If True, specifies channel_credentials as
363
+ :term:`grpc.insecure_channel_credentials()`. This option is mutually
364
+ exclusive with the `channel_credentials` option.
365
+ call_credentials: A call credential applied to each call individually,
366
+ e.g. the output of grpc.metadata_call_credentials() or
367
+ grpc.access_token_call_credentials().
368
+ compression: An optional value indicating the compression method to be
369
+ used over the lifetime of the channel, e.g. grpc.Compression.Gzip.
370
+ wait_for_ready: An optional flag indicating whether the RPC should fail
371
+ immediately if the connection is not ready at the time the RPC is
372
+ invoked, or if it should wait until the connection to the server
373
+ becomes ready. When using this option, the user will likely also want
374
+ to set a timeout. Defaults to True.
375
+ timeout: An optional duration of time in seconds to allow for the RPC,
376
+ after which an exception will be raised. If timeout is unspecified,
377
+ defaults to a timeout controlled by the
378
+ GRPC_PYTHON_DEFAULT_TIMEOUT_SECONDS environment variable. If that is
379
+ unset, defaults to 60 seconds. Supply a value of None to indicate that
380
+ no timeout should be enforced.
381
+ metadata: Optional metadata to send to the server.
382
+
383
+ Returns:
384
+ An iterator of responses.
385
+ """
386
+ channel, method_handle = ChannelCache.get().get_channel(
387
+ target,
388
+ options,
389
+ channel_credentials,
390
+ insecure,
391
+ compression,
392
+ method,
393
+ _registered_method,
394
+ )
395
+ multicallable = channel.unary_stream(
396
+ method, request_serializer, response_deserializer, method_handle
397
+ )
398
+ wait_for_ready = wait_for_ready if wait_for_ready is not None else True
399
+ return multicallable(
400
+ request,
401
+ metadata=metadata,
402
+ wait_for_ready=wait_for_ready,
403
+ credentials=call_credentials,
404
+ timeout=timeout,
405
+ )
406
+
407
+
408
+ @experimental_api
409
+ # pylint: disable=too-many-locals
410
+ def stream_unary(
411
+ request_iterator: Iterator[RequestType],
412
+ target: str,
413
+ method: str,
414
+ request_serializer: Optional[Callable[[Any], bytes]] = None,
415
+ response_deserializer: Optional[Callable[[bytes], Any]] = None,
416
+ options: Sequence[Tuple[AnyStr, AnyStr]] = (),
417
+ channel_credentials: Optional[grpc.ChannelCredentials] = None,
418
+ insecure: bool = False,
419
+ call_credentials: Optional[grpc.CallCredentials] = None,
420
+ compression: Optional[grpc.Compression] = None,
421
+ wait_for_ready: Optional[bool] = None,
422
+ timeout: Optional[float] = _DEFAULT_TIMEOUT,
423
+ metadata: Optional[Sequence[Tuple[str, Union[str, bytes]]]] = None,
424
+ _registered_method: Optional[bool] = False,
425
+ ) -> ResponseType:
426
+ """Invokes a stream-unary RPC without an explicitly specified channel.
427
+
428
+ THIS IS AN EXPERIMENTAL API.
429
+
430
+ This is backed by a per-process cache of channels. Channels are evicted
431
+ from the cache after a fixed period by a background. Channels will also be
432
+ evicted if more than a configured maximum accumulate.
433
+
434
+ The default eviction period is 10 minutes. One may set the environment
435
+ variable "GRPC_PYTHON_MANAGED_CHANNEL_EVICTION_SECONDS" to configure this.
436
+
437
+ The default maximum number of channels is 256. One may set the
438
+ environment variable "GRPC_PYTHON_MANAGED_CHANNEL_MAXIMUM" to configure
439
+ this.
440
+
441
+ Args:
442
+ request_iterator: An iterator that yields request values for the RPC.
443
+ target: The server address.
444
+ method: The name of the RPC method.
445
+ request_serializer: Optional :term:`serializer` for serializing the request
446
+ message. Request goes unserialized in case None is passed.
447
+ response_deserializer: Optional :term:`deserializer` for deserializing the response
448
+ message. Response goes undeserialized in case None is passed.
449
+ options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC Core
450
+ runtime) to configure the channel.
451
+ channel_credentials: A credential applied to the whole channel, e.g. the
452
+ return value of grpc.ssl_channel_credentials().
453
+ call_credentials: A call credential applied to each call individually,
454
+ e.g. the output of grpc.metadata_call_credentials() or
455
+ grpc.access_token_call_credentials().
456
+ insecure: If True, specifies channel_credentials as
457
+ :term:`grpc.insecure_channel_credentials()`. This option is mutually
458
+ exclusive with the `channel_credentials` option.
459
+ compression: An optional value indicating the compression method to be
460
+ used over the lifetime of the channel, e.g. grpc.Compression.Gzip.
461
+ wait_for_ready: An optional flag indicating whether the RPC should fail
462
+ immediately if the connection is not ready at the time the RPC is
463
+ invoked, or if it should wait until the connection to the server
464
+ becomes ready. When using this option, the user will likely also want
465
+ to set a timeout. Defaults to True.
466
+ timeout: An optional duration of time in seconds to allow for the RPC,
467
+ after which an exception will be raised. If timeout is unspecified,
468
+ defaults to a timeout controlled by the
469
+ GRPC_PYTHON_DEFAULT_TIMEOUT_SECONDS environment variable. If that is
470
+ unset, defaults to 60 seconds. Supply a value of None to indicate that
471
+ no timeout should be enforced.
472
+ metadata: Optional metadata to send to the server.
473
+
474
+ Returns:
475
+ The response to the RPC.
476
+ """
477
+ channel, method_handle = ChannelCache.get().get_channel(
478
+ target,
479
+ options,
480
+ channel_credentials,
481
+ insecure,
482
+ compression,
483
+ method,
484
+ _registered_method,
485
+ )
486
+ multicallable = channel.stream_unary(
487
+ method, request_serializer, response_deserializer, method_handle
488
+ )
489
+ wait_for_ready = wait_for_ready if wait_for_ready is not None else True
490
+ return multicallable(
491
+ request_iterator,
492
+ metadata=metadata,
493
+ wait_for_ready=wait_for_ready,
494
+ credentials=call_credentials,
495
+ timeout=timeout,
496
+ )
497
+
498
+
499
+ @experimental_api
500
+ # pylint: disable=too-many-locals
501
+ def stream_stream(
502
+ request_iterator: Iterator[RequestType],
503
+ target: str,
504
+ method: str,
505
+ request_serializer: Optional[Callable[[Any], bytes]] = None,
506
+ response_deserializer: Optional[Callable[[bytes], Any]] = None,
507
+ options: Sequence[Tuple[AnyStr, AnyStr]] = (),
508
+ channel_credentials: Optional[grpc.ChannelCredentials] = None,
509
+ insecure: bool = False,
510
+ call_credentials: Optional[grpc.CallCredentials] = None,
511
+ compression: Optional[grpc.Compression] = None,
512
+ wait_for_ready: Optional[bool] = None,
513
+ timeout: Optional[float] = _DEFAULT_TIMEOUT,
514
+ metadata: Optional[Sequence[Tuple[str, Union[str, bytes]]]] = None,
515
+ _registered_method: Optional[bool] = False,
516
+ ) -> Iterator[ResponseType]:
517
+ """Invokes a stream-stream RPC without an explicitly specified channel.
518
+
519
+ THIS IS AN EXPERIMENTAL API.
520
+
521
+ This is backed by a per-process cache of channels. Channels are evicted
522
+ from the cache after a fixed period by a background. Channels will also be
523
+ evicted if more than a configured maximum accumulate.
524
+
525
+ The default eviction period is 10 minutes. One may set the environment
526
+ variable "GRPC_PYTHON_MANAGED_CHANNEL_EVICTION_SECONDS" to configure this.
527
+
528
+ The default maximum number of channels is 256. One may set the
529
+ environment variable "GRPC_PYTHON_MANAGED_CHANNEL_MAXIMUM" to configure
530
+ this.
531
+
532
+ Args:
533
+ request_iterator: An iterator that yields request values for the RPC.
534
+ target: The server address.
535
+ method: The name of the RPC method.
536
+ request_serializer: Optional :term:`serializer` for serializing the request
537
+ message. Request goes unserialized in case None is passed.
538
+ response_deserializer: Optional :term:`deserializer` for deserializing the response
539
+ message. Response goes undeserialized in case None is passed.
540
+ options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC Core
541
+ runtime) to configure the channel.
542
+ channel_credentials: A credential applied to the whole channel, e.g. the
543
+ return value of grpc.ssl_channel_credentials().
544
+ call_credentials: A call credential applied to each call individually,
545
+ e.g. the output of grpc.metadata_call_credentials() or
546
+ grpc.access_token_call_credentials().
547
+ insecure: If True, specifies channel_credentials as
548
+ :term:`grpc.insecure_channel_credentials()`. This option is mutually
549
+ exclusive with the `channel_credentials` option.
550
+ compression: An optional value indicating the compression method to be
551
+ used over the lifetime of the channel, e.g. grpc.Compression.Gzip.
552
+ wait_for_ready: An optional flag indicating whether the RPC should fail
553
+ immediately if the connection is not ready at the time the RPC is
554
+ invoked, or if it should wait until the connection to the server
555
+ becomes ready. When using this option, the user will likely also want
556
+ to set a timeout. Defaults to True.
557
+ timeout: An optional duration of time in seconds to allow for the RPC,
558
+ after which an exception will be raised. If timeout is unspecified,
559
+ defaults to a timeout controlled by the
560
+ GRPC_PYTHON_DEFAULT_TIMEOUT_SECONDS environment variable. If that is
561
+ unset, defaults to 60 seconds. Supply a value of None to indicate that
562
+ no timeout should be enforced.
563
+ metadata: Optional metadata to send to the server.
564
+
565
+ Returns:
566
+ An iterator of responses.
567
+ """
568
+ channel, method_handle = ChannelCache.get().get_channel(
569
+ target,
570
+ options,
571
+ channel_credentials,
572
+ insecure,
573
+ compression,
574
+ method,
575
+ _registered_method,
576
+ )
577
+ multicallable = channel.stream_stream(
578
+ method, request_serializer, response_deserializer, method_handle
579
+ )
580
+ wait_for_ready = wait_for_ready if wait_for_ready is not None else True
581
+ return multicallable(
582
+ request_iterator,
583
+ metadata=metadata,
584
+ wait_for_ready=wait_for_ready,
585
+ credentials=call_credentials,
586
+ timeout=timeout,
587
+ )
loan-advisor-agent/.venv/Lib/site-packages/grpc/_typing.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 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
+ """Common types for gRPC Sync API"""
15
+
16
+ from typing import (
17
+ TYPE_CHECKING,
18
+ Any,
19
+ Callable,
20
+ Iterable,
21
+ Iterator,
22
+ Optional,
23
+ Sequence,
24
+ Tuple,
25
+ TypeVar,
26
+ Union,
27
+ )
28
+
29
+ from grpc._cython import cygrpc
30
+
31
+ if TYPE_CHECKING:
32
+ from grpc import ServicerContext
33
+ from grpc._server import _RPCState
34
+
35
+ RequestType = TypeVar("RequestType")
36
+ ResponseType = TypeVar("ResponseType")
37
+ SerializingFunction = Callable[[Any], bytes]
38
+ DeserializingFunction = Callable[[bytes], Any]
39
+ MetadataType = Sequence[Tuple[str, Union[str, bytes]]]
40
+ ChannelArgumentType = Tuple[str, Any]
41
+ DoneCallbackType = Callable[[Any], None]
42
+ NullaryCallbackType = Callable[[], None]
43
+ RequestIterableType = Iterable[Any]
44
+ ResponseIterableType = Iterable[Any]
45
+ UserTag = Callable[[cygrpc.BaseEvent], bool]
46
+ IntegratedCallFactory = Callable[
47
+ [
48
+ int,
49
+ bytes,
50
+ Optional[str],
51
+ Optional[float],
52
+ Optional[MetadataType],
53
+ Optional[cygrpc.CallCredentials],
54
+ Sequence[Sequence[cygrpc.Operation]],
55
+ UserTag,
56
+ Any,
57
+ Optional[int],
58
+ ],
59
+ cygrpc.IntegratedCall,
60
+ ]
61
+ ServerTagCallbackType = Tuple[
62
+ Optional["_RPCState"], Sequence[NullaryCallbackType]
63
+ ]
64
+ ServerCallbackTag = Callable[[cygrpc.BaseEvent], ServerTagCallbackType]
65
+ ArityAgnosticMethodHandler = Union[
66
+ Callable[
67
+ [RequestType, "ServicerContext", Callable[[ResponseType], None]],
68
+ ResponseType,
69
+ ],
70
+ Callable[
71
+ [RequestType, "ServicerContext", Callable[[ResponseType], None]],
72
+ Iterator[ResponseType],
73
+ ],
74
+ Callable[
75
+ [
76
+ Iterator[RequestType],
77
+ "ServicerContext",
78
+ Callable[[ResponseType], None],
79
+ ],
80
+ ResponseType,
81
+ ],
82
+ Callable[
83
+ [
84
+ Iterator[RequestType],
85
+ "ServicerContext",
86
+ Callable[[ResponseType], None],
87
+ ],
88
+ Iterator[ResponseType],
89
+ ],
90
+ Callable[[RequestType, "ServicerContext"], ResponseType],
91
+ Callable[[RequestType, "ServicerContext"], Iterator[ResponseType]],
92
+ Callable[[Iterator[RequestType], "ServicerContext"], ResponseType],
93
+ Callable[
94
+ [Iterator[RequestType], "ServicerContext"], Iterator[ResponseType]
95
+ ],
96
+ ]
loan-advisor-agent/.venv/Lib/site-packages/grpc/_utilities.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2015 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
+ """Internal utilities for gRPC Python."""
15
+
16
+ import collections
17
+ import logging
18
+ import threading
19
+ import time
20
+ from typing import Callable, Dict, Optional, Sequence
21
+
22
+ import grpc
23
+ from grpc import _common
24
+ from grpc._typing import DoneCallbackType
25
+
26
+ _LOGGER = logging.getLogger(__name__)
27
+
28
+ _DONE_CALLBACK_EXCEPTION_LOG_MESSAGE = (
29
+ 'Exception calling connectivity future "done" callback!'
30
+ )
31
+
32
+
33
+ class RpcMethodHandler(
34
+ collections.namedtuple(
35
+ "_RpcMethodHandler",
36
+ (
37
+ "request_streaming",
38
+ "response_streaming",
39
+ "request_deserializer",
40
+ "response_serializer",
41
+ "unary_unary",
42
+ "unary_stream",
43
+ "stream_unary",
44
+ "stream_stream",
45
+ ),
46
+ ),
47
+ grpc.RpcMethodHandler,
48
+ ):
49
+ pass
50
+
51
+
52
+ class DictionaryGenericHandler(grpc.ServiceRpcHandler):
53
+ _name: str
54
+ _method_handlers: Dict[str, grpc.RpcMethodHandler]
55
+
56
+ def __init__(
57
+ self, service: str, method_handlers: Dict[str, grpc.RpcMethodHandler]
58
+ ):
59
+ self._name = service
60
+ self._method_handlers = {
61
+ _common.fully_qualified_method(service, method): method_handler
62
+ for method, method_handler in method_handlers.items()
63
+ }
64
+
65
+ def service_name(self) -> str:
66
+ return self._name
67
+
68
+ def service(
69
+ self, handler_call_details: grpc.HandlerCallDetails
70
+ ) -> Optional[grpc.RpcMethodHandler]:
71
+ details_method = handler_call_details.method
72
+ return self._method_handlers.get(
73
+ details_method
74
+ ) # pytype: disable=attribute-error
75
+
76
+
77
+ class _ChannelReadyFuture(grpc.Future):
78
+ _condition: threading.Condition
79
+ _channel: grpc.Channel
80
+ _matured: bool
81
+ _cancelled: bool
82
+ _done_callbacks: Sequence[Callable]
83
+
84
+ def __init__(self, channel: grpc.Channel):
85
+ self._condition = threading.Condition()
86
+ self._channel = channel
87
+
88
+ self._matured = False
89
+ self._cancelled = False
90
+ self._done_callbacks = []
91
+
92
+ def _block(self, timeout: Optional[float]) -> None:
93
+ until = None if timeout is None else time.time() + timeout
94
+ with self._condition:
95
+ while True:
96
+ if self._cancelled:
97
+ raise grpc.FutureCancelledError()
98
+ if self._matured:
99
+ return
100
+ if until is None:
101
+ self._condition.wait()
102
+ else:
103
+ remaining = until - time.time()
104
+ if remaining < 0:
105
+ raise grpc.FutureTimeoutError()
106
+ self._condition.wait(timeout=remaining)
107
+
108
+ def _update(self, connectivity: Optional[grpc.ChannelConnectivity]) -> None:
109
+ with self._condition:
110
+ if (
111
+ not self._cancelled
112
+ and connectivity is grpc.ChannelConnectivity.READY
113
+ ):
114
+ self._matured = True
115
+ self._channel.unsubscribe(self._update)
116
+ self._condition.notify_all()
117
+ done_callbacks = tuple(self._done_callbacks)
118
+ self._done_callbacks = None
119
+ else:
120
+ return
121
+
122
+ for done_callback in done_callbacks:
123
+ try:
124
+ done_callback(self)
125
+ except Exception: # pylint: disable=broad-except
126
+ _LOGGER.exception(_DONE_CALLBACK_EXCEPTION_LOG_MESSAGE)
127
+
128
+ def cancel(self) -> bool:
129
+ with self._condition:
130
+ if not self._matured:
131
+ self._cancelled = True
132
+ self._channel.unsubscribe(self._update)
133
+ self._condition.notify_all()
134
+ done_callbacks = tuple(self._done_callbacks)
135
+ self._done_callbacks = None
136
+ else:
137
+ return False
138
+
139
+ for done_callback in done_callbacks:
140
+ try:
141
+ done_callback(self)
142
+ except Exception: # pylint: disable=broad-except
143
+ _LOGGER.exception(_DONE_CALLBACK_EXCEPTION_LOG_MESSAGE)
144
+
145
+ return True
146
+
147
+ def cancelled(self) -> bool:
148
+ with self._condition:
149
+ return self._cancelled
150
+
151
+ def running(self) -> bool:
152
+ with self._condition:
153
+ return not self._cancelled and not self._matured
154
+
155
+ def done(self) -> bool:
156
+ with self._condition:
157
+ return self._cancelled or self._matured
158
+
159
+ def result(self, timeout: Optional[float] = None) -> None:
160
+ self._block(timeout)
161
+
162
+ def exception(self, timeout: Optional[float] = None) -> None:
163
+ self._block(timeout)
164
+
165
+ def traceback(self, timeout: Optional[float] = None) -> None:
166
+ self._block(timeout)
167
+
168
+ def add_done_callback(self, fn: DoneCallbackType):
169
+ with self._condition:
170
+ if not self._cancelled and not self._matured:
171
+ self._done_callbacks.append(fn)
172
+ return
173
+
174
+ fn(self)
175
+
176
+ def start(self):
177
+ with self._condition:
178
+ self._channel.subscribe(self._update, try_to_connect=True)
179
+
180
+ def __del__(self):
181
+ with self._condition:
182
+ if not self._cancelled and not self._matured:
183
+ self._channel.unsubscribe(self._update)
184
+
185
+
186
+ def channel_ready_future(channel: grpc.Channel) -> _ChannelReadyFuture:
187
+ ready_future = _ChannelReadyFuture(channel)
188
+ ready_future.start()
189
+ return ready_future
190
+
191
+
192
+ def first_version_is_lower(version1: str, version2: str) -> bool:
193
+ """
194
+ Compares two versions in the format '1.60.1' or '1.60.1.dev0'.
195
+
196
+ This method will be used in all stubs generated by grpcio-tools to check whether
197
+ the stub version is compatible with the runtime grpcio.
198
+
199
+ Args:
200
+ version1: The first version string.
201
+ version2: The second version string.
202
+
203
+ Returns:
204
+ True if version1 is lower, False otherwise.
205
+ """
206
+ version1_list = version1.split(".")
207
+ version2_list = version2.split(".")
208
+
209
+ try:
210
+ for i in range(3):
211
+ if int(version1_list[i]) < int(version2_list[i]):
212
+ return True
213
+ if int(version1_list[i]) > int(version2_list[i]):
214
+ return False
215
+ except ValueError:
216
+ # Return false in case we can't convert version to int.
217
+ return False
218
+
219
+ # The version without dev0 will be considered lower.
220
+ return len(version1_list) < len(version2_list)
loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/__init__.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2019 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 Asynchronous Python API.
15
+
16
+ gRPC Async API objects may only be used on the thread on which they were
17
+ created. AsyncIO doesn't provide thread safety for most of its APIs.
18
+ """
19
+
20
+ from typing import Any, Optional, Sequence, Tuple
21
+
22
+ import grpc
23
+ from grpc._cython.cygrpc import AbortError
24
+ from grpc._cython.cygrpc import BaseError
25
+ from grpc._cython.cygrpc import EOF
26
+ from grpc._cython.cygrpc import InternalError
27
+ from grpc._cython.cygrpc import UsageError
28
+ from grpc._cython.cygrpc import init_grpc_aio
29
+ from grpc._cython.cygrpc import shutdown_grpc_aio
30
+
31
+ from ._base_call import Call
32
+ from ._base_call import RpcContext
33
+ from ._base_call import StreamStreamCall
34
+ from ._base_call import StreamUnaryCall
35
+ from ._base_call import UnaryStreamCall
36
+ from ._base_call import UnaryUnaryCall
37
+ from ._base_channel import Channel
38
+ from ._base_channel import StreamStreamMultiCallable
39
+ from ._base_channel import StreamUnaryMultiCallable
40
+ from ._base_channel import UnaryStreamMultiCallable
41
+ from ._base_channel import UnaryUnaryMultiCallable
42
+ from ._base_server import Server
43
+ from ._base_server import ServicerContext
44
+ from ._call import AioRpcError
45
+ from ._channel import insecure_channel
46
+ from ._channel import secure_channel
47
+ from ._interceptor import ClientCallDetails
48
+ from ._interceptor import ClientInterceptor
49
+ from ._interceptor import InterceptedUnaryUnaryCall
50
+ from ._interceptor import ServerInterceptor
51
+ from ._interceptor import StreamStreamClientInterceptor
52
+ from ._interceptor import StreamUnaryClientInterceptor
53
+ from ._interceptor import UnaryStreamClientInterceptor
54
+ from ._interceptor import UnaryUnaryClientInterceptor
55
+ from ._metadata import Metadata
56
+ from ._server import server
57
+ from ._typing import ChannelArgumentType
58
+
59
+ ################################### __all__ #################################
60
+
61
+ __all__ = (
62
+ "EOF",
63
+ "AbortError",
64
+ "AioRpcError",
65
+ "BaseError",
66
+ "Call",
67
+ "Channel",
68
+ "ClientCallDetails",
69
+ "ClientInterceptor",
70
+ "InterceptedUnaryUnaryCall",
71
+ "InternalError",
72
+ "Metadata",
73
+ "RpcContext",
74
+ "Server",
75
+ "ServerInterceptor",
76
+ "ServicerContext",
77
+ "StreamStreamCall",
78
+ "StreamStreamClientInterceptor",
79
+ "StreamStreamMultiCallable",
80
+ "StreamUnaryCall",
81
+ "StreamUnaryClientInterceptor",
82
+ "StreamUnaryMultiCallable",
83
+ "UnaryStreamCall",
84
+ "UnaryStreamClientInterceptor",
85
+ "UnaryStreamMultiCallable",
86
+ "UnaryUnaryCall",
87
+ "UnaryUnaryClientInterceptor",
88
+ "UnaryUnaryMultiCallable",
89
+ "UsageError",
90
+ "init_grpc_aio",
91
+ "insecure_channel",
92
+ "secure_channel",
93
+ "server",
94
+ "shutdown_grpc_aio",
95
+ )
loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (2.16 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/__pycache__/_base_call.cpython-312.pyc ADDED
Binary file (8.94 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/__pycache__/_base_channel.cpython-312.pyc ADDED
Binary file (16 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/__pycache__/_base_server.cpython-312.pyc ADDED
Binary file (15.9 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/__pycache__/_call.cpython-312.pyc ADDED
Binary file (35.5 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/__pycache__/_channel.cpython-312.pyc ADDED
Binary file (21.8 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/__pycache__/_interceptor.cpython-312.pyc ADDED
Binary file (47.6 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/__pycache__/_metadata.cpython-312.pyc ADDED
Binary file (8.03 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/__pycache__/_server.cpython-312.pyc ADDED
Binary file (10.3 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/__pycache__/_typing.cpython-312.pyc ADDED
Binary file (1.14 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/__pycache__/_utils.cpython-312.pyc ADDED
Binary file (569 Bytes). View file
 
loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/_base_call.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2019 The 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
+ """Abstract base classes for client-side Call objects.
15
+
16
+ Call objects represents the RPC itself, and offer methods to access / modify
17
+ its information. They also offer methods to manipulate the life-cycle of the
18
+ RPC, e.g. cancellation.
19
+ """
20
+
21
+ from abc import ABCMeta
22
+ from abc import abstractmethod
23
+ from typing import Any, AsyncIterator, Generator, Generic, Optional, Union
24
+
25
+ import grpc
26
+
27
+ from ._metadata import Metadata
28
+ from ._typing import DoneCallbackType
29
+ from ._typing import EOFType
30
+ from ._typing import RequestType
31
+ from ._typing import ResponseType
32
+
33
+ __all__ = "Call", "RpcContext", "UnaryStreamCall", "UnaryUnaryCall"
34
+
35
+
36
+ class RpcContext(metaclass=ABCMeta):
37
+ """Provides RPC-related information and action."""
38
+
39
+ @abstractmethod
40
+ def cancelled(self) -> bool:
41
+ """Return True if the RPC is cancelled.
42
+
43
+ The RPC is cancelled when the cancellation was requested with cancel().
44
+
45
+ Returns:
46
+ A bool indicates whether the RPC is cancelled or not.
47
+ """
48
+
49
+ @abstractmethod
50
+ def done(self) -> bool:
51
+ """Return True if the RPC is done.
52
+
53
+ An RPC is done if the RPC is completed, cancelled or aborted.
54
+
55
+ Returns:
56
+ A bool indicates if the RPC is done.
57
+ """
58
+
59
+ @abstractmethod
60
+ def time_remaining(self) -> Optional[float]:
61
+ """Describes the length of allowed time remaining for the RPC.
62
+
63
+ Returns:
64
+ A nonnegative float indicating the length of allowed time in seconds
65
+ remaining for the RPC to complete before it is considered to have
66
+ timed out, or None if no deadline was specified for the RPC.
67
+ """
68
+
69
+ @abstractmethod
70
+ def cancel(self) -> bool:
71
+ """Cancels the RPC.
72
+
73
+ Idempotent and has no effect if the RPC has already terminated.
74
+
75
+ Returns:
76
+ A bool indicates if the cancellation is performed or not.
77
+ """
78
+
79
+ @abstractmethod
80
+ def add_done_callback(self, callback: DoneCallbackType) -> None:
81
+ """Registers a callback to be called on RPC termination.
82
+
83
+ Args:
84
+ callback: A callable object will be called with the call object as
85
+ its only argument.
86
+ """
87
+
88
+
89
+ class Call(RpcContext, metaclass=ABCMeta):
90
+ """The abstract base class of an RPC on the client-side."""
91
+
92
+ @abstractmethod
93
+ async def initial_metadata(self) -> Metadata:
94
+ """Accesses the initial metadata sent by the server.
95
+
96
+ Returns:
97
+ The initial :term:`metadata`.
98
+ """
99
+
100
+ @abstractmethod
101
+ async def trailing_metadata(self) -> Metadata:
102
+ """Accesses the trailing metadata sent by the server.
103
+
104
+ Returns:
105
+ The trailing :term:`metadata`.
106
+ """
107
+
108
+ @abstractmethod
109
+ async def code(self) -> grpc.StatusCode:
110
+ """Accesses the status code sent by the server.
111
+
112
+ Returns:
113
+ The StatusCode value for the RPC.
114
+ """
115
+
116
+ @abstractmethod
117
+ async def details(self) -> str:
118
+ """Accesses the details sent by the server.
119
+
120
+ Returns:
121
+ The details string of the RPC.
122
+ """
123
+
124
+ @abstractmethod
125
+ async def wait_for_connection(self) -> None:
126
+ """Waits until connected to peer and raises aio.AioRpcError if failed.
127
+
128
+ This is an EXPERIMENTAL method.
129
+
130
+ This method ensures the RPC has been successfully connected. Otherwise,
131
+ an AioRpcError will be raised to explain the reason of the connection
132
+ failure.
133
+
134
+ This method is recommended for building retry mechanisms.
135
+ """
136
+
137
+
138
+ class UnaryUnaryCall(
139
+ Generic[RequestType, ResponseType], Call, metaclass=ABCMeta
140
+ ):
141
+ """The abstract base class of a unary-unary RPC on the client-side."""
142
+
143
+ @abstractmethod
144
+ def __await__(self) -> Generator[Any, None, ResponseType]:
145
+ """Await the response message to be ready.
146
+
147
+ Returns:
148
+ The response message of the RPC.
149
+ """
150
+
151
+
152
+ class UnaryStreamCall(
153
+ Generic[RequestType, ResponseType], Call, metaclass=ABCMeta
154
+ ):
155
+ @abstractmethod
156
+ def __aiter__(self) -> AsyncIterator[ResponseType]:
157
+ """Returns the async iterator representation that yields messages.
158
+
159
+ Under the hood, it is calling the "read" method.
160
+
161
+ Returns:
162
+ An async iterator object that yields messages.
163
+ """
164
+
165
+ @abstractmethod
166
+ async def read(self) -> Union[EOFType, ResponseType]:
167
+ """Reads one message from the stream.
168
+
169
+ Read operations must be serialized when called from multiple
170
+ coroutines.
171
+
172
+ Note that the iterator and read/write APIs may not be mixed on
173
+ a single RPC.
174
+
175
+ Returns:
176
+ A response message, or an `grpc.aio.EOF` to indicate the end of the
177
+ stream.
178
+ """
179
+
180
+
181
+ class StreamUnaryCall(
182
+ Generic[RequestType, ResponseType], Call, metaclass=ABCMeta
183
+ ):
184
+ @abstractmethod
185
+ async def write(self, request: RequestType) -> None:
186
+ """Writes one message to the stream.
187
+
188
+ Note that the iterator and read/write APIs may not be mixed on
189
+ a single RPC.
190
+
191
+ Raises:
192
+ An RpcError exception if the write failed.
193
+ """
194
+
195
+ @abstractmethod
196
+ async def done_writing(self) -> None:
197
+ """Notifies server that the client is done sending messages.
198
+
199
+ After done_writing is called, any additional invocation to the write
200
+ function will fail. This function is idempotent.
201
+ """
202
+
203
+ @abstractmethod
204
+ def __await__(self) -> Generator[Any, None, ResponseType]:
205
+ """Await the response message to be ready.
206
+
207
+ Returns:
208
+ The response message of the stream.
209
+ """
210
+
211
+
212
+ class StreamStreamCall(
213
+ Generic[RequestType, ResponseType], Call, metaclass=ABCMeta
214
+ ):
215
+ @abstractmethod
216
+ def __aiter__(self) -> AsyncIterator[ResponseType]:
217
+ """Returns the async iterator representation that yields messages.
218
+
219
+ Under the hood, it is calling the "read" method.
220
+
221
+ Returns:
222
+ An async iterator object that yields messages.
223
+ """
224
+
225
+ @abstractmethod
226
+ async def read(self) -> Union[EOFType, ResponseType]:
227
+ """Reads one message from the stream.
228
+
229
+ Read operations must be serialized when called from multiple
230
+ coroutines.
231
+
232
+ Note that the iterator and read/write APIs may not be mixed on
233
+ a single RPC.
234
+
235
+ Returns:
236
+ A response message, or an `grpc.aio.EOF` to indicate the end of the
237
+ stream.
238
+ """
239
+
240
+ @abstractmethod
241
+ async def write(self, request: RequestType) -> None:
242
+ """Writes one message to the stream.
243
+
244
+ Note that the iterator and read/write APIs may not be mixed on
245
+ a single RPC.
246
+
247
+ Raises:
248
+ An RpcError exception if the write failed.
249
+ """
250
+
251
+ @abstractmethod
252
+ async def done_writing(self) -> None:
253
+ """Notifies server that the client is done sending messages.
254
+
255
+ After done_writing is called, any additional invocation to the write
256
+ function will fail. This function is idempotent.
257
+ """
loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/_base_channel.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The 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
+ """Abstract base classes for Channel objects and Multicallable objects."""
15
+
16
+ import abc
17
+ from typing import Generic, Optional
18
+
19
+ import grpc
20
+
21
+ from . import _base_call
22
+ from ._typing import DeserializingFunction
23
+ from ._typing import MetadataType
24
+ from ._typing import RequestIterableType
25
+ from ._typing import RequestType
26
+ from ._typing import ResponseType
27
+ from ._typing import SerializingFunction
28
+
29
+
30
+ class UnaryUnaryMultiCallable(Generic[RequestType, ResponseType], abc.ABC):
31
+ """Enables asynchronous invocation of a unary-call RPC."""
32
+
33
+ @abc.abstractmethod
34
+ def __call__(
35
+ self,
36
+ request: RequestType,
37
+ *,
38
+ timeout: Optional[float] = None,
39
+ metadata: Optional[MetadataType] = None,
40
+ credentials: Optional[grpc.CallCredentials] = None,
41
+ wait_for_ready: Optional[bool] = None,
42
+ compression: Optional[grpc.Compression] = None,
43
+ ) -> _base_call.UnaryUnaryCall[RequestType, ResponseType]:
44
+ """Asynchronously invokes the underlying RPC.
45
+
46
+ Args:
47
+ request: The request value for the RPC.
48
+ timeout: An optional duration of time in seconds to allow
49
+ for the RPC.
50
+ metadata: Optional :term:`metadata` to be transmitted to the
51
+ service-side of the RPC.
52
+ credentials: An optional CallCredentials for the RPC. Only valid for
53
+ secure Channel.
54
+ wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
55
+ compression: An element of grpc.Compression, e.g.
56
+ grpc.Compression.Gzip.
57
+
58
+ Returns:
59
+ A UnaryUnaryCall object.
60
+
61
+ Raises:
62
+ RpcError: Indicates that the RPC terminated with non-OK status. The
63
+ raised RpcError will also be a Call for the RPC affording the RPC's
64
+ metadata, status code, and details.
65
+ """
66
+
67
+
68
+ class UnaryStreamMultiCallable(Generic[RequestType, ResponseType], abc.ABC):
69
+ """Enables asynchronous invocation of a server-streaming RPC."""
70
+
71
+ @abc.abstractmethod
72
+ def __call__(
73
+ self,
74
+ request: RequestType,
75
+ *,
76
+ timeout: Optional[float] = None,
77
+ metadata: Optional[MetadataType] = None,
78
+ credentials: Optional[grpc.CallCredentials] = None,
79
+ wait_for_ready: Optional[bool] = None,
80
+ compression: Optional[grpc.Compression] = None,
81
+ ) -> _base_call.UnaryStreamCall[RequestType, ResponseType]:
82
+ """Asynchronously invokes the underlying RPC.
83
+
84
+ Args:
85
+ request: The request value for the RPC.
86
+ timeout: An optional duration of time in seconds to allow
87
+ for the RPC.
88
+ metadata: Optional :term:`metadata` to be transmitted to the
89
+ service-side of the RPC.
90
+ credentials: An optional CallCredentials for the RPC. Only valid for
91
+ secure Channel.
92
+ wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
93
+ compression: An element of grpc.Compression, e.g.
94
+ grpc.Compression.Gzip.
95
+
96
+ Returns:
97
+ A UnaryStreamCall object.
98
+
99
+ Raises:
100
+ RpcError: Indicates that the RPC terminated with non-OK status. The
101
+ raised RpcError will also be a Call for the RPC affording the RPC's
102
+ metadata, status code, and details.
103
+ """
104
+
105
+
106
+ class StreamUnaryMultiCallable(abc.ABC):
107
+ """Enables asynchronous invocation of a client-streaming RPC."""
108
+
109
+ @abc.abstractmethod
110
+ def __call__(
111
+ self,
112
+ request_iterator: Optional[RequestIterableType] = None,
113
+ timeout: Optional[float] = None,
114
+ metadata: Optional[MetadataType] = None,
115
+ credentials: Optional[grpc.CallCredentials] = None,
116
+ wait_for_ready: Optional[bool] = None,
117
+ compression: Optional[grpc.Compression] = None,
118
+ ) -> _base_call.StreamUnaryCall:
119
+ """Asynchronously invokes the underlying RPC.
120
+
121
+ Args:
122
+ request_iterator: An optional async iterable or iterable of request
123
+ messages for the RPC.
124
+ timeout: An optional duration of time in seconds to allow
125
+ for the RPC.
126
+ metadata: Optional :term:`metadata` to be transmitted to the
127
+ service-side of the RPC.
128
+ credentials: An optional CallCredentials for the RPC. Only valid for
129
+ secure Channel.
130
+ wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
131
+ compression: An element of grpc.Compression, e.g.
132
+ grpc.Compression.Gzip.
133
+
134
+ Returns:
135
+ A StreamUnaryCall object.
136
+
137
+ Raises:
138
+ RpcError: Indicates that the RPC terminated with non-OK status. The
139
+ raised RpcError will also be a Call for the RPC affording the RPC's
140
+ metadata, status code, and details.
141
+ """
142
+
143
+
144
+ class StreamStreamMultiCallable(abc.ABC):
145
+ """Enables asynchronous invocation of a bidirectional-streaming RPC."""
146
+
147
+ @abc.abstractmethod
148
+ def __call__(
149
+ self,
150
+ request_iterator: Optional[RequestIterableType] = None,
151
+ timeout: Optional[float] = None,
152
+ metadata: Optional[MetadataType] = None,
153
+ credentials: Optional[grpc.CallCredentials] = None,
154
+ wait_for_ready: Optional[bool] = None,
155
+ compression: Optional[grpc.Compression] = None,
156
+ ) -> _base_call.StreamStreamCall:
157
+ """Asynchronously invokes the underlying RPC.
158
+
159
+ Args:
160
+ request_iterator: An optional async iterable or iterable of request
161
+ messages for the RPC.
162
+ timeout: An optional duration of time in seconds to allow
163
+ for the RPC.
164
+ metadata: Optional :term:`metadata` to be transmitted to the
165
+ service-side of the RPC.
166
+ credentials: An optional CallCredentials for the RPC. Only valid for
167
+ secure Channel.
168
+ wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
169
+ compression: An element of grpc.Compression, e.g.
170
+ grpc.Compression.Gzip.
171
+
172
+ Returns:
173
+ A StreamStreamCall object.
174
+
175
+ Raises:
176
+ RpcError: Indicates that the RPC terminated with non-OK status. The
177
+ raised RpcError will also be a Call for the RPC affording the RPC's
178
+ metadata, status code, and details.
179
+ """
180
+
181
+
182
+ class Channel(abc.ABC):
183
+ """Enables asynchronous RPC invocation as a client.
184
+
185
+ Channel objects implement the Asynchronous Context Manager (aka. async
186
+ with) type, although they are not supported to be entered and exited
187
+ multiple times.
188
+ """
189
+
190
+ @abc.abstractmethod
191
+ async def __aenter__(self):
192
+ """Starts an asynchronous context manager.
193
+
194
+ Returns:
195
+ Channel the channel that was instantiated.
196
+ """
197
+
198
+ @abc.abstractmethod
199
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
200
+ """Finishes the asynchronous context manager by closing the channel.
201
+
202
+ Still active RPCs will be cancelled.
203
+ """
204
+
205
+ @abc.abstractmethod
206
+ async def close(self, grace: Optional[float] = None):
207
+ """Closes this Channel and releases all resources held by it.
208
+
209
+ This method immediately stops the channel from executing new RPCs in
210
+ all cases.
211
+
212
+ If a grace period is specified, this method waits until all active
213
+ RPCs are finished or until the grace period is reached. RPCs that haven't
214
+ been terminated within the grace period are aborted.
215
+ If a grace period is not specified (by passing None for grace),
216
+ all existing RPCs are cancelled immediately.
217
+
218
+ This method is idempotent.
219
+ """
220
+
221
+ @abc.abstractmethod
222
+ def get_state(
223
+ self, try_to_connect: bool = False
224
+ ) -> grpc.ChannelConnectivity:
225
+ """Checks the connectivity state of a channel.
226
+
227
+ This is an EXPERIMENTAL API.
228
+
229
+ If the channel reaches a stable connectivity state, it is guaranteed
230
+ that the return value of this function will eventually converge to that
231
+ state.
232
+
233
+ Args:
234
+ try_to_connect: a bool indicate whether the Channel should try to
235
+ connect to peer or not.
236
+
237
+ Returns: A ChannelConnectivity object.
238
+ """
239
+
240
+ @abc.abstractmethod
241
+ async def wait_for_state_change(
242
+ self,
243
+ last_observed_state: grpc.ChannelConnectivity,
244
+ ) -> None:
245
+ """Waits for a change in connectivity state.
246
+
247
+ This is an EXPERIMENTAL API.
248
+
249
+ The function blocks until there is a change in the channel connectivity
250
+ state from the "last_observed_state". If the state is already
251
+ different, this function will return immediately.
252
+
253
+ There is an inherent race between the invocation of
254
+ "Channel.wait_for_state_change" and "Channel.get_state". The state can
255
+ change arbitrary many times during the race, so there is no way to
256
+ observe every state transition.
257
+
258
+ If there is a need to put a timeout for this function, please refer to
259
+ "asyncio.wait_for".
260
+
261
+ Args:
262
+ last_observed_state: A grpc.ChannelConnectivity object representing
263
+ the last known state.
264
+ """
265
+
266
+ @abc.abstractmethod
267
+ async def channel_ready(self) -> None:
268
+ """Creates a coroutine that blocks until the Channel is READY."""
269
+
270
+ @abc.abstractmethod
271
+ def unary_unary(
272
+ self,
273
+ method: str,
274
+ request_serializer: Optional[SerializingFunction] = None,
275
+ response_deserializer: Optional[DeserializingFunction] = None,
276
+ _registered_method: Optional[bool] = False,
277
+ ) -> UnaryUnaryMultiCallable:
278
+ """Creates a UnaryUnaryMultiCallable for a unary-unary method.
279
+
280
+ Args:
281
+ method: The name of the RPC method.
282
+ request_serializer: Optional :term:`serializer` for serializing the request
283
+ message. Request goes unserialized in case None is passed.
284
+ response_deserializer: Optional :term:`deserializer` for deserializing the
285
+ response message. Response goes undeserialized in case None
286
+ is passed.
287
+ _registered_method: Implementation Private. Optional: A bool representing
288
+ whether the method is registered.
289
+
290
+ Returns:
291
+ A UnaryUnaryMultiCallable value for the named unary-unary method.
292
+ """
293
+
294
+ @abc.abstractmethod
295
+ def unary_stream(
296
+ self,
297
+ method: str,
298
+ request_serializer: Optional[SerializingFunction] = None,
299
+ response_deserializer: Optional[DeserializingFunction] = None,
300
+ _registered_method: Optional[bool] = False,
301
+ ) -> UnaryStreamMultiCallable:
302
+ """Creates a UnaryStreamMultiCallable for a unary-stream method.
303
+
304
+ Args:
305
+ method: The name of the RPC method.
306
+ request_serializer: Optional :term:`serializer` for serializing the request
307
+ message. Request goes unserialized in case None is passed.
308
+ response_deserializer: Optional :term:`deserializer` for deserializing the
309
+ response message. Response goes undeserialized in case None
310
+ is passed.
311
+ _registered_method: Implementation Private. Optional: A bool representing
312
+ whether the method is registered.
313
+
314
+ Returns:
315
+ A UnaryStreamMultiCallable value for the named unary-stream method.
316
+ """
317
+
318
+ @abc.abstractmethod
319
+ def stream_unary(
320
+ self,
321
+ method: str,
322
+ request_serializer: Optional[SerializingFunction] = None,
323
+ response_deserializer: Optional[DeserializingFunction] = None,
324
+ _registered_method: Optional[bool] = False,
325
+ ) -> StreamUnaryMultiCallable:
326
+ """Creates a StreamUnaryMultiCallable for a stream-unary method.
327
+
328
+ Args:
329
+ method: The name of the RPC method.
330
+ request_serializer: Optional :term:`serializer` for serializing the request
331
+ message. Request goes unserialized in case None is passed.
332
+ response_deserializer: Optional :term:`deserializer` for deserializing the
333
+ response message. Response goes undeserialized in case None
334
+ is passed.
335
+ _registered_method: Implementation Private. Optional: A bool representing
336
+ whether the method is registered.
337
+
338
+ Returns:
339
+ A StreamUnaryMultiCallable value for the named stream-unary method.
340
+ """
341
+
342
+ @abc.abstractmethod
343
+ def stream_stream(
344
+ self,
345
+ method: str,
346
+ request_serializer: Optional[SerializingFunction] = None,
347
+ response_deserializer: Optional[DeserializingFunction] = None,
348
+ _registered_method: Optional[bool] = False,
349
+ ) -> StreamStreamMultiCallable:
350
+ """Creates a StreamStreamMultiCallable for a stream-stream method.
351
+
352
+ Args:
353
+ method: The name of the RPC method.
354
+ request_serializer: Optional :term:`serializer` for serializing the request
355
+ message. Request goes unserialized in case None is passed.
356
+ response_deserializer: Optional :term:`deserializer` for deserializing the
357
+ response message. Response goes undeserialized in case None
358
+ is passed.
359
+ _registered_method: Implementation Private. Optional: A bool representing
360
+ whether the method is registered.
361
+
362
+ Returns:
363
+ A StreamStreamMultiCallable value for the named stream-stream method.
364
+ """
loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/_base_server.py ADDED
@@ -0,0 +1,387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The 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
+ """Abstract base classes for server-side classes."""
15
+
16
+ import abc
17
+ from typing import Generic, Iterable, Mapping, NoReturn, Optional, Sequence
18
+
19
+ import grpc
20
+
21
+ from ._metadata import Metadata # pylint: disable=unused-import
22
+ from ._typing import DoneCallbackType
23
+ from ._typing import MetadataType
24
+ from ._typing import RequestType
25
+ from ._typing import ResponseType
26
+
27
+
28
+ class Server(abc.ABC):
29
+ """Serves RPCs."""
30
+
31
+ @abc.abstractmethod
32
+ def add_generic_rpc_handlers(
33
+ self, generic_rpc_handlers: Sequence[grpc.GenericRpcHandler]
34
+ ) -> None:
35
+ """Registers GenericRpcHandlers with this Server.
36
+
37
+ This method is only safe to call before the server is started.
38
+
39
+ Args:
40
+ generic_rpc_handlers: A sequence of GenericRpcHandlers that will be
41
+ used to service RPCs.
42
+ """
43
+
44
+ @abc.abstractmethod
45
+ def add_insecure_port(self, address: str) -> int:
46
+ """Opens an insecure port for accepting RPCs.
47
+
48
+ A port is a communication endpoint that used by networking protocols,
49
+ like TCP and UDP. To date, we only support TCP.
50
+
51
+ This method may only be called before starting the server.
52
+
53
+ Args:
54
+ address: The address for which to open a port. If the port is 0,
55
+ or not specified in the address, then the gRPC runtime will choose a port.
56
+
57
+ Returns:
58
+ An integer port on which the server will accept RPC requests.
59
+ """
60
+
61
+ @abc.abstractmethod
62
+ def add_secure_port(
63
+ self, address: str, server_credentials: grpc.ServerCredentials
64
+ ) -> int:
65
+ """Opens a secure port for accepting RPCs.
66
+
67
+ A port is a communication endpoint that used by networking protocols,
68
+ like TCP and UDP. To date, we only support TCP.
69
+
70
+ This method may only be called before starting the server.
71
+
72
+ Args:
73
+ address: The address for which to open a port.
74
+ if the port is 0, or not specified in the address, then the gRPC
75
+ runtime will choose a port.
76
+ server_credentials: A ServerCredentials object.
77
+
78
+ Returns:
79
+ An integer port on which the server will accept RPC requests.
80
+ """
81
+
82
+ @abc.abstractmethod
83
+ async def start(self) -> None:
84
+ """Starts this Server.
85
+
86
+ This method may only be called once. (i.e. it is not idempotent).
87
+ """
88
+
89
+ @abc.abstractmethod
90
+ async def stop(self, grace: Optional[float]) -> None:
91
+ """Stops this Server.
92
+
93
+ This method immediately stops the server from servicing new RPCs in
94
+ all cases.
95
+
96
+ If a grace period is specified, this method waits until all active
97
+ RPCs are finished or until the grace period is reached. RPCs that haven't
98
+ been terminated within the grace period are aborted.
99
+ If a grace period is not specified (by passing None for grace), all
100
+ existing RPCs are aborted immediately and this method blocks until
101
+ the last RPC handler terminates.
102
+
103
+ This method is idempotent and may be called at any time. Passing a
104
+ smaller grace value in a subsequent call will have the effect of
105
+ stopping the Server sooner (passing None will have the effect of
106
+ stopping the server immediately). Passing a larger grace value in a
107
+ subsequent call will not have the effect of stopping the server later
108
+ (i.e. the most restrictive grace value is used).
109
+
110
+ Args:
111
+ grace: A duration of time in seconds or None.
112
+ """
113
+
114
+ @abc.abstractmethod
115
+ async def wait_for_termination(
116
+ self, timeout: Optional[float] = None
117
+ ) -> bool:
118
+ """Continues current coroutine once the server stops.
119
+
120
+ This is an EXPERIMENTAL API.
121
+
122
+ The wait will not consume computational resources during blocking, and
123
+ it will block until one of the two following conditions are met:
124
+
125
+ 1) The server is stopped or terminated;
126
+ 2) A timeout occurs if timeout is not `None`.
127
+
128
+ The timeout argument works in the same way as `threading.Event.wait()`.
129
+ https://docs.python.org/3/library/threading.html#threading.Event.wait
130
+
131
+ Args:
132
+ timeout: A floating point number specifying a timeout for the
133
+ operation in seconds.
134
+
135
+ Returns:
136
+ A bool indicates if the operation times out.
137
+ """
138
+
139
+ def add_registered_method_handlers( # noqa: B027
140
+ self, service_name, method_handlers
141
+ ):
142
+ """Registers GenericRpcHandlers with this Server.
143
+
144
+ This method is only safe to call before the server is started.
145
+
146
+ Args:
147
+ service_name: The service name.
148
+ method_handlers: A dictionary that maps method names to corresponding
149
+ RpcMethodHandler.
150
+ """
151
+
152
+
153
+ # pylint: disable=too-many-public-methods
154
+ class ServicerContext(Generic[RequestType, ResponseType], abc.ABC):
155
+ """A context object passed to method implementations."""
156
+
157
+ @abc.abstractmethod
158
+ async def read(self) -> RequestType:
159
+ """Reads one message from the RPC.
160
+
161
+ Only one read operation is allowed simultaneously.
162
+
163
+ Returns:
164
+ A response message of the RPC.
165
+
166
+ Raises:
167
+ An RpcError exception if the read failed.
168
+ """
169
+
170
+ @abc.abstractmethod
171
+ async def write(self, message: ResponseType) -> None:
172
+ """Writes one message to the RPC.
173
+
174
+ Only one write operation is allowed simultaneously.
175
+
176
+ Raises:
177
+ An RpcError exception if the write failed.
178
+ """
179
+
180
+ @abc.abstractmethod
181
+ async def send_initial_metadata(
182
+ self, initial_metadata: MetadataType
183
+ ) -> None:
184
+ """Sends the initial metadata value to the client.
185
+
186
+ This method need not be called by implementations if they have no
187
+ metadata to add to what the gRPC runtime will transmit.
188
+
189
+ Args:
190
+ initial_metadata: The initial :term:`metadata`.
191
+ """
192
+
193
+ @abc.abstractmethod
194
+ async def abort(
195
+ self,
196
+ code: grpc.StatusCode,
197
+ details: str = "",
198
+ trailing_metadata: MetadataType = (),
199
+ ) -> NoReturn:
200
+ """Raises an exception to terminate the RPC with a non-OK status.
201
+
202
+ The code and details passed as arguments will supersede any existing
203
+ ones.
204
+
205
+ Args:
206
+ code: A StatusCode object to be sent to the client.
207
+ It must not be StatusCode.OK.
208
+ details: A UTF-8-encodable string to be sent to the client upon
209
+ termination of the RPC.
210
+ trailing_metadata: A sequence of tuple represents the trailing
211
+ :term:`metadata`.
212
+
213
+ Raises:
214
+ Exception: An exception is always raised to signal the abortion the
215
+ RPC to the gRPC runtime.
216
+ """
217
+
218
+ @abc.abstractmethod
219
+ def set_trailing_metadata(self, trailing_metadata: MetadataType) -> None:
220
+ """Sends the trailing metadata for the RPC.
221
+
222
+ This method need not be called by implementations if they have no
223
+ metadata to add to what the gRPC runtime will transmit.
224
+
225
+ Args:
226
+ trailing_metadata: The trailing :term:`metadata`.
227
+ """
228
+
229
+ @abc.abstractmethod
230
+ def invocation_metadata(self) -> Optional[MetadataType]:
231
+ """Accesses the metadata sent by the client.
232
+
233
+ Returns:
234
+ The invocation :term:`metadata`.
235
+ """
236
+
237
+ @abc.abstractmethod
238
+ def set_code(self, code: grpc.StatusCode) -> None:
239
+ """Sets the value to be used as status code upon RPC completion.
240
+
241
+ This method need not be called by method implementations if they wish
242
+ the gRPC runtime to determine the status code of the RPC.
243
+
244
+ Args:
245
+ code: A StatusCode object to be sent to the client.
246
+ """
247
+
248
+ @abc.abstractmethod
249
+ def set_details(self, details: str) -> None:
250
+ """Sets the value to be used the as detail string upon RPC completion.
251
+
252
+ This method need not be called by method implementations if they have
253
+ no details to transmit.
254
+
255
+ Args:
256
+ details: A UTF-8-encodable string to be sent to the client upon
257
+ termination of the RPC.
258
+ """
259
+
260
+ @abc.abstractmethod
261
+ def set_compression(self, compression: grpc.Compression) -> None:
262
+ """Set the compression algorithm to be used for the entire call.
263
+
264
+ Args:
265
+ compression: An element of grpc.compression, e.g.
266
+ grpc.compression.Gzip.
267
+ """
268
+
269
+ @abc.abstractmethod
270
+ def disable_next_message_compression(self) -> None:
271
+ """Disables compression for the next response message.
272
+
273
+ This method will override any compression configuration set during
274
+ server creation or set on the call.
275
+ """
276
+
277
+ @abc.abstractmethod
278
+ def peer(self) -> str:
279
+ """Identifies the peer that invoked the RPC being serviced.
280
+
281
+ Returns:
282
+ A string identifying the peer that invoked the RPC being serviced.
283
+ The string format is determined by gRPC runtime.
284
+ """
285
+
286
+ @abc.abstractmethod
287
+ def peer_identities(self) -> Optional[Iterable[bytes]]:
288
+ """Gets one or more peer identity(s).
289
+
290
+ Equivalent to
291
+ servicer_context.auth_context().get(servicer_context.peer_identity_key())
292
+
293
+ Returns:
294
+ An iterable of the identities, or None if the call is not
295
+ authenticated. Each identity is returned as a raw bytes type.
296
+ """
297
+
298
+ @abc.abstractmethod
299
+ def peer_identity_key(self) -> Optional[str]:
300
+ """The auth property used to identify the peer.
301
+
302
+ For example, "x509_common_name" or "x509_subject_alternative_name" are
303
+ used to identify an SSL peer.
304
+
305
+ Returns:
306
+ The auth property (string) that indicates the
307
+ peer identity, or None if the call is not authenticated.
308
+ """
309
+
310
+ @abc.abstractmethod
311
+ def auth_context(self) -> Mapping[str, Iterable[bytes]]:
312
+ """Gets the auth context for the call.
313
+
314
+ Returns:
315
+ A map of strings to an iterable of bytes for each auth property.
316
+ """
317
+
318
+ def time_remaining(self) -> float:
319
+ """Describes the length of allowed time remaining for the RPC.
320
+
321
+ Returns:
322
+ A nonnegative float indicating the length of allowed time in seconds
323
+ remaining for the RPC to complete before it is considered to have
324
+ timed out, or None if no deadline was specified for the RPC.
325
+ """
326
+
327
+ def trailing_metadata(self):
328
+ """Access value to be used as trailing metadata upon RPC completion.
329
+
330
+ This is an EXPERIMENTAL API.
331
+
332
+ Returns:
333
+ The trailing :term:`metadata` for the RPC.
334
+ """
335
+ raise NotImplementedError()
336
+
337
+ def code(self):
338
+ """Accesses the value to be used as status code upon RPC completion.
339
+
340
+ This is an EXPERIMENTAL API.
341
+
342
+ Returns:
343
+ The StatusCode value for the RPC.
344
+ """
345
+ raise NotImplementedError()
346
+
347
+ def details(self):
348
+ """Accesses the value to be used as detail string upon RPC completion.
349
+
350
+ This is an EXPERIMENTAL API.
351
+
352
+ Returns:
353
+ The details string of the RPC.
354
+ """
355
+ raise NotImplementedError()
356
+
357
+ def add_done_callback(self, callback: DoneCallbackType) -> None:
358
+ """Registers a callback to be called on RPC termination.
359
+
360
+ This is an EXPERIMENTAL API.
361
+
362
+ Args:
363
+ callback: A callable object will be called with the servicer context
364
+ object as its only argument.
365
+ """
366
+
367
+ def cancelled(self) -> bool:
368
+ """Return True if the RPC is cancelled.
369
+
370
+ The RPC is cancelled when the cancellation was requested with cancel().
371
+
372
+ This is an EXPERIMENTAL API.
373
+
374
+ Returns:
375
+ A bool indicates whether the RPC is cancelled or not.
376
+ """
377
+
378
+ def done(self) -> bool:
379
+ """Return True if the RPC is done.
380
+
381
+ An RPC is done if the RPC is completed, cancelled or aborted.
382
+
383
+ This is an EXPERIMENTAL API.
384
+
385
+ Returns:
386
+ A bool indicates if the RPC is done.
387
+ """
loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/_call.py ADDED
@@ -0,0 +1,759 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2019 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
+ """Invocation-side implementation of gRPC Asyncio Python."""
15
+
16
+ import asyncio
17
+ import enum
18
+ from functools import partial
19
+ import inspect
20
+ import logging
21
+ import traceback
22
+ from typing import (
23
+ Any,
24
+ AsyncIterator,
25
+ Generator,
26
+ Generic,
27
+ Optional,
28
+ Tuple,
29
+ Union,
30
+ )
31
+
32
+ import grpc
33
+ from grpc import _common
34
+ from grpc._cython import cygrpc
35
+
36
+ from . import _base_call
37
+ from ._metadata import Metadata
38
+ from ._typing import DeserializingFunction
39
+ from ._typing import DoneCallbackType
40
+ from ._typing import EOFType
41
+ from ._typing import MetadataType
42
+ from ._typing import MetadatumType
43
+ from ._typing import RequestIterableType
44
+ from ._typing import RequestType
45
+ from ._typing import ResponseType
46
+ from ._typing import SerializingFunction
47
+
48
+ __all__ = "AioRpcError", "Call", "UnaryStreamCall", "UnaryUnaryCall"
49
+
50
+ _LOCAL_CANCELLATION_DETAILS = "Locally cancelled by application!"
51
+ _GC_CANCELLATION_DETAILS = "Cancelled upon garbage collection!"
52
+ _RPC_ALREADY_FINISHED_DETAILS = "RPC already finished."
53
+ _RPC_HALF_CLOSED_DETAILS = 'RPC is half closed after calling "done_writing".'
54
+ _API_STYLE_ERROR = (
55
+ "The iterator and read/write APIs may not be mixed on a single RPC."
56
+ )
57
+
58
+ _OK_CALL_REPRESENTATION = (
59
+ '<{} of RPC that terminated with:\n\tstatus = {}\n\tdetails = "{}"\n>'
60
+ )
61
+
62
+ _NON_OK_CALL_REPRESENTATION = (
63
+ "<{} of RPC that terminated with:\n"
64
+ "\tstatus = {}\n"
65
+ '\tdetails = "{}"\n'
66
+ '\tdebug_error_string = "{}"\n'
67
+ ">"
68
+ )
69
+
70
+ _LOGGER = logging.getLogger(__name__)
71
+
72
+
73
+ class AioRpcError(grpc.RpcError):
74
+ """An implementation of RpcError to be used by the asynchronous API.
75
+
76
+ Raised RpcError is a snapshot of the final status of the RPC, values are
77
+ determined. Hence, its methods no longer needs to be coroutines.
78
+ """
79
+
80
+ _code: grpc.StatusCode
81
+ _details: Optional[str]
82
+ _initial_metadata: Optional[Metadata]
83
+ _trailing_metadata: Optional[Metadata]
84
+ _debug_error_string: Optional[str]
85
+
86
+ def __init__(
87
+ self,
88
+ code: grpc.StatusCode,
89
+ initial_metadata: Metadata,
90
+ trailing_metadata: Metadata,
91
+ details: Optional[str] = None,
92
+ debug_error_string: Optional[str] = None,
93
+ ) -> None:
94
+ """Constructor.
95
+
96
+ Args:
97
+ code: The status code with which the RPC has been finalized.
98
+ initial_metadata: Optional initial metadata that could be sent by the
99
+ Server.
100
+ trailing_metadata: Optional metadata that could be sent by the Server.
101
+ details: Optional details explaining the reason of the error.
102
+ debug_error_string: Optional string
103
+ """
104
+ super().__init__()
105
+ self._code = code
106
+ self._details = details
107
+ self._initial_metadata = initial_metadata
108
+ self._trailing_metadata = trailing_metadata
109
+ self._debug_error_string = debug_error_string
110
+
111
+ def code(self) -> grpc.StatusCode:
112
+ """Accesses the status code sent by the server.
113
+
114
+ Returns:
115
+ The `grpc.StatusCode` status code.
116
+ """
117
+ return self._code
118
+
119
+ def details(self) -> Optional[str]:
120
+ """Accesses the details sent by the server.
121
+
122
+ Returns:
123
+ The description of the error.
124
+ """
125
+ return self._details
126
+
127
+ def initial_metadata(self) -> Metadata:
128
+ """Accesses the initial metadata sent by the server.
129
+
130
+ Returns:
131
+ The initial metadata received.
132
+ """
133
+ return self._initial_metadata
134
+
135
+ def trailing_metadata(self) -> Metadata:
136
+ """Accesses the trailing metadata sent by the server.
137
+
138
+ Returns:
139
+ The trailing metadata received.
140
+ """
141
+ return self._trailing_metadata
142
+
143
+ def debug_error_string(self) -> str:
144
+ """Accesses the debug error string sent by the server.
145
+
146
+ Returns:
147
+ The debug error string received.
148
+ """
149
+ return self._debug_error_string
150
+
151
+ def _repr(self) -> str:
152
+ """Assembles the error string for the RPC error."""
153
+ return _NON_OK_CALL_REPRESENTATION.format(
154
+ self.__class__.__name__,
155
+ self._code,
156
+ self._details,
157
+ self._debug_error_string,
158
+ )
159
+
160
+ def __repr__(self) -> str:
161
+ return self._repr()
162
+
163
+ def __str__(self) -> str:
164
+ return self._repr()
165
+
166
+ def __reduce__(self):
167
+ return (
168
+ type(self),
169
+ (
170
+ self._code,
171
+ self._initial_metadata,
172
+ self._trailing_metadata,
173
+ self._details,
174
+ self._debug_error_string,
175
+ ),
176
+ )
177
+
178
+
179
+ def _create_rpc_error(
180
+ initial_metadata: MetadataType,
181
+ status: cygrpc.AioRpcStatus,
182
+ ) -> AioRpcError:
183
+ return AioRpcError(
184
+ _common.CYGRPC_STATUS_CODE_TO_STATUS_CODE[status.code()],
185
+ Metadata._create(initial_metadata),
186
+ Metadata.from_tuple(status.trailing_metadata()),
187
+ details=status.details(),
188
+ debug_error_string=status.debug_error_string(),
189
+ )
190
+
191
+
192
+ class Call:
193
+ """Base implementation of client RPC Call object.
194
+
195
+ Implements logic around final status, metadata and cancellation.
196
+ """
197
+
198
+ _loop: asyncio.AbstractEventLoop
199
+ _code: grpc.StatusCode
200
+ _cython_call: cygrpc._AioCall
201
+ _metadata: Tuple[MetadatumType, ...]
202
+ _request_serializer: Optional[SerializingFunction]
203
+ _response_deserializer: Optional[DeserializingFunction]
204
+
205
+ def __init__(
206
+ self,
207
+ cython_call: cygrpc._AioCall,
208
+ metadata: Metadata,
209
+ request_serializer: Optional[SerializingFunction],
210
+ response_deserializer: Optional[DeserializingFunction],
211
+ loop: asyncio.AbstractEventLoop,
212
+ ) -> None:
213
+ self._loop = loop
214
+ self._cython_call = cython_call
215
+ self._metadata = tuple(metadata)
216
+ self._request_serializer = request_serializer
217
+ self._response_deserializer = response_deserializer
218
+
219
+ def __del__(self) -> None:
220
+ # The '_cython_call' object might be destructed before Call object
221
+ if hasattr(self, "_cython_call") and not self._cython_call.done():
222
+ self._cancel(_GC_CANCELLATION_DETAILS)
223
+
224
+ def cancelled(self) -> bool:
225
+ return self._cython_call.cancelled()
226
+
227
+ def _cancel(self, details: str) -> bool:
228
+ """Forwards the application cancellation reasoning."""
229
+ if not self._cython_call.done():
230
+ self._cython_call.cancel(details)
231
+ return True
232
+ return False
233
+
234
+ def cancel(self) -> bool:
235
+ return self._cancel(_LOCAL_CANCELLATION_DETAILS)
236
+
237
+ def done(self) -> bool:
238
+ return self._cython_call.done()
239
+
240
+ def add_done_callback(self, callback: DoneCallbackType) -> None:
241
+ cb = partial(callback, self)
242
+ self._cython_call.add_done_callback(cb)
243
+
244
+ def time_remaining(self) -> Optional[float]:
245
+ return self._cython_call.time_remaining()
246
+
247
+ async def initial_metadata(self) -> Metadata:
248
+ raw_metadata_tuple = await self._cython_call.initial_metadata()
249
+ return Metadata.from_tuple(raw_metadata_tuple)
250
+
251
+ async def trailing_metadata(self) -> Metadata:
252
+ raw_metadata_tuple = (
253
+ await self._cython_call.status()
254
+ ).trailing_metadata()
255
+ if not raw_metadata_tuple:
256
+ return Metadata()
257
+ return Metadata.from_tuple(raw_metadata_tuple)
258
+
259
+ async def code(self) -> grpc.StatusCode:
260
+ cygrpc_code = (await self._cython_call.status()).code()
261
+ return _common.CYGRPC_STATUS_CODE_TO_STATUS_CODE[cygrpc_code]
262
+
263
+ async def details(self) -> str:
264
+ return (await self._cython_call.status()).details()
265
+
266
+ async def debug_error_string(self) -> str:
267
+ return (await self._cython_call.status()).debug_error_string()
268
+
269
+ async def _raise_for_status(self) -> None:
270
+ if self._cython_call.is_locally_cancelled():
271
+ raise asyncio.CancelledError()
272
+ code = await self.code()
273
+ if code != grpc.StatusCode.OK:
274
+ raise _create_rpc_error(
275
+ await self.initial_metadata(),
276
+ await self._cython_call.status(),
277
+ )
278
+
279
+ def _repr(self) -> str:
280
+ return repr(self._cython_call)
281
+
282
+ def __repr__(self) -> str:
283
+ return self._repr()
284
+
285
+ def __str__(self) -> str:
286
+ return self._repr()
287
+
288
+
289
+ class _APIStyle(enum.IntEnum):
290
+ UNKNOWN = 0
291
+ ASYNC_GENERATOR = 1
292
+ READER_WRITER = 2
293
+
294
+
295
+ class _UnaryResponseMixin(Call, Generic[ResponseType]):
296
+ _call_response: asyncio.Task
297
+
298
+ def _init_unary_response_mixin(self, response_task: asyncio.Task):
299
+ self._call_response = response_task
300
+
301
+ def cancel(self) -> bool:
302
+ if super().cancel():
303
+ self._call_response.cancel()
304
+ return True
305
+ return False
306
+
307
+ def __await__(self) -> Generator[Any, None, ResponseType]:
308
+ """Wait till the ongoing RPC request finishes."""
309
+ try:
310
+ response = yield from self._call_response
311
+ except asyncio.CancelledError:
312
+ # Even if we caught all other CancelledError, there is still
313
+ # this corner case. If the application cancels immediately after
314
+ # the Call object is created, we will observe this
315
+ # `CancelledError`.
316
+ if not self.cancelled():
317
+ self.cancel()
318
+ raise
319
+
320
+ # NOTE(lidiz) If we raise RpcError in the task, and users doesn't
321
+ # 'await' on it. AsyncIO will log 'Task exception was never retrieved'.
322
+ # Instead, if we move the exception raising here, the spam stops.
323
+ # Unfortunately, there can only be one 'yield from' in '__await__'. So,
324
+ # we need to access the private instance variable.
325
+ if response is cygrpc.EOF:
326
+ if self._cython_call.is_locally_cancelled():
327
+ raise asyncio.CancelledError()
328
+ else:
329
+ raise _create_rpc_error(
330
+ self._cython_call._initial_metadata,
331
+ self._cython_call._status,
332
+ )
333
+ else:
334
+ return response
335
+
336
+
337
+ class _StreamResponseMixin(Call):
338
+ _message_aiter: AsyncIterator[ResponseType]
339
+ _preparation: asyncio.Task
340
+ _response_style: _APIStyle
341
+
342
+ def _init_stream_response_mixin(self, preparation: asyncio.Task):
343
+ self._message_aiter = None
344
+ self._preparation = preparation
345
+ self._response_style = _APIStyle.UNKNOWN
346
+
347
+ def _update_response_style(self, style: _APIStyle):
348
+ if self._response_style is _APIStyle.UNKNOWN:
349
+ self._response_style = style
350
+ elif self._response_style is not style:
351
+ raise cygrpc.UsageError(_API_STYLE_ERROR)
352
+
353
+ def cancel(self) -> bool:
354
+ if super().cancel():
355
+ self._preparation.cancel()
356
+ return True
357
+ return False
358
+
359
+ async def _fetch_stream_responses(self) -> ResponseType:
360
+ message = await self._read()
361
+ while message is not cygrpc.EOF:
362
+ yield message
363
+ message = await self._read()
364
+
365
+ # If the read operation failed, Core should explain why.
366
+ await self._raise_for_status()
367
+
368
+ def __aiter__(self) -> AsyncIterator[ResponseType]:
369
+ self._update_response_style(_APIStyle.ASYNC_GENERATOR)
370
+ if self._message_aiter is None:
371
+ self._message_aiter = self._fetch_stream_responses()
372
+ return self._message_aiter
373
+
374
+ async def _read(self) -> ResponseType:
375
+ # Wait for the request being sent
376
+ await self._preparation
377
+
378
+ # Reads response message from Core
379
+ try:
380
+ raw_response = await self._cython_call.receive_serialized_message()
381
+ except asyncio.CancelledError:
382
+ if not self.cancelled():
383
+ self.cancel()
384
+ raise
385
+
386
+ if raw_response is cygrpc.EOF:
387
+ return cygrpc.EOF
388
+ return _common.deserialize(raw_response, self._response_deserializer)
389
+
390
+ async def read(self) -> Union[EOFType, ResponseType]:
391
+ if self.done():
392
+ await self._raise_for_status()
393
+ return cygrpc.EOF
394
+ self._update_response_style(_APIStyle.READER_WRITER)
395
+
396
+ response_message = await self._read()
397
+
398
+ if response_message is cygrpc.EOF:
399
+ # If the read operation failed, Core should explain why.
400
+ await self._raise_for_status()
401
+ return response_message
402
+
403
+
404
+ class _StreamRequestMixin(Call):
405
+ _metadata_sent: asyncio.Event
406
+ _done_writing_flag: bool
407
+ _async_request_poller: Optional[asyncio.Task]
408
+ _request_style: _APIStyle
409
+
410
+ def _init_stream_request_mixin(
411
+ self, request_iterator: Optional[RequestIterableType]
412
+ ):
413
+ self._metadata_sent = asyncio.Event()
414
+ self._done_writing_flag = False
415
+
416
+ # If user passes in an async iterator, create a consumer Task.
417
+ if request_iterator is not None:
418
+ self._async_request_poller = self._loop.create_task(
419
+ self._consume_request_iterator(request_iterator)
420
+ )
421
+ self._request_style = _APIStyle.ASYNC_GENERATOR
422
+ else:
423
+ self._async_request_poller = None
424
+ self._request_style = _APIStyle.READER_WRITER
425
+
426
+ def _raise_for_different_style(self, style: _APIStyle):
427
+ if self._request_style is not style:
428
+ raise cygrpc.UsageError(_API_STYLE_ERROR)
429
+
430
+ def cancel(self) -> bool:
431
+ if super().cancel():
432
+ if self._async_request_poller is not None:
433
+ self._async_request_poller.cancel()
434
+ return True
435
+ return False
436
+
437
+ def _metadata_sent_observer(self):
438
+ self._metadata_sent.set()
439
+
440
+ async def _consume_request_iterator(
441
+ self, request_iterator: RequestIterableType
442
+ ) -> None:
443
+ try:
444
+ if inspect.isasyncgen(request_iterator) or hasattr(
445
+ request_iterator, "__aiter__"
446
+ ):
447
+ async for request in request_iterator:
448
+ try:
449
+ await self._write(request)
450
+ except AioRpcError as rpc_error:
451
+ _LOGGER.debug(
452
+ (
453
+ "Exception while consuming the"
454
+ " request_iterator: %s"
455
+ ),
456
+ rpc_error,
457
+ )
458
+ return
459
+ else:
460
+ for request in request_iterator:
461
+ try:
462
+ await self._write(request)
463
+ except AioRpcError as rpc_error:
464
+ _LOGGER.debug(
465
+ (
466
+ "Exception while consuming the"
467
+ " request_iterator: %s"
468
+ ),
469
+ rpc_error,
470
+ )
471
+ return
472
+
473
+ await self._done_writing()
474
+ except: # pylint: disable=bare-except # noqa: E722
475
+ # Client iterators can raise exceptions, which we should handle by
476
+ # cancelling the RPC and logging the client's error. No exceptions
477
+ # should escape this function.
478
+ _LOGGER.debug(
479
+ "Client request_iterator raised exception:\n%s",
480
+ traceback.format_exc(),
481
+ )
482
+ self.cancel()
483
+
484
+ async def _write(self, request: RequestType) -> None:
485
+ if self.done():
486
+ raise asyncio.InvalidStateError(_RPC_ALREADY_FINISHED_DETAILS)
487
+ if self._done_writing_flag:
488
+ raise asyncio.InvalidStateError(_RPC_HALF_CLOSED_DETAILS)
489
+ if not self._metadata_sent.is_set():
490
+ await self._metadata_sent.wait()
491
+ if self.done():
492
+ await self._raise_for_status()
493
+
494
+ serialized_request = _common.serialize(
495
+ request, self._request_serializer
496
+ )
497
+ try:
498
+ await self._cython_call.send_serialized_message(serialized_request)
499
+ except cygrpc.InternalError as err:
500
+ self._cython_call.set_internal_error(str(err))
501
+ await self._raise_for_status()
502
+ except asyncio.CancelledError:
503
+ if not self.cancelled():
504
+ self.cancel()
505
+ raise
506
+
507
+ async def _done_writing(self) -> None:
508
+ if self.done():
509
+ # If the RPC is finished, do nothing.
510
+ return
511
+ if not self._done_writing_flag:
512
+ # If the done writing is not sent before, try to send it.
513
+ self._done_writing_flag = True
514
+ try:
515
+ await self._cython_call.send_receive_close()
516
+ except asyncio.CancelledError:
517
+ if not self.cancelled():
518
+ self.cancel()
519
+ raise
520
+
521
+ async def write(self, request: RequestType) -> None:
522
+ self._raise_for_different_style(_APIStyle.READER_WRITER)
523
+ await self._write(request)
524
+
525
+ async def done_writing(self) -> None:
526
+ """Signal peer that client is done writing.
527
+
528
+ This method is idempotent.
529
+ """
530
+ self._raise_for_different_style(_APIStyle.READER_WRITER)
531
+ await self._done_writing()
532
+
533
+ async def wait_for_connection(self) -> None:
534
+ await self._metadata_sent.wait()
535
+ if self.done():
536
+ await self._raise_for_status()
537
+
538
+
539
+ class UnaryUnaryCall(_UnaryResponseMixin, Call, _base_call.UnaryUnaryCall):
540
+ """Object for managing unary-unary RPC calls.
541
+
542
+ Returned when an instance of `UnaryUnaryMultiCallable` object is called.
543
+ """
544
+
545
+ _request: RequestType
546
+ _invocation_task: asyncio.Task
547
+
548
+ # pylint: disable=too-many-arguments
549
+ def __init__(
550
+ self,
551
+ request: RequestType,
552
+ deadline: Optional[float],
553
+ metadata: Metadata,
554
+ credentials: Optional[grpc.CallCredentials],
555
+ wait_for_ready: Optional[bool],
556
+ channel: cygrpc.AioChannel,
557
+ method: bytes,
558
+ request_serializer: Optional[SerializingFunction],
559
+ response_deserializer: Optional[DeserializingFunction],
560
+ loop: asyncio.AbstractEventLoop,
561
+ ) -> None:
562
+ super().__init__(
563
+ channel.call(method, deadline, credentials, wait_for_ready),
564
+ metadata,
565
+ request_serializer,
566
+ response_deserializer,
567
+ loop,
568
+ )
569
+ self._request = request
570
+ self._context = cygrpc.build_census_context()
571
+ self._invocation_task = loop.create_task(self._invoke())
572
+ self._init_unary_response_mixin(self._invocation_task)
573
+
574
+ async def _invoke(self) -> ResponseType:
575
+ serialized_request = _common.serialize(
576
+ self._request, self._request_serializer
577
+ )
578
+
579
+ # NOTE(lidiz) asyncio.CancelledError is not a good transport for status,
580
+ # because the asyncio.Task class do not cache the exception object.
581
+ # https://github.com/python/cpython/blob/edad4d89e357c92f70c0324b937845d652b20afd/Lib/asyncio/tasks.py#L785
582
+ try:
583
+ serialized_response = await self._cython_call.unary_unary(
584
+ serialized_request, self._metadata, self._context
585
+ )
586
+ except asyncio.CancelledError:
587
+ if not self.cancelled():
588
+ self.cancel()
589
+
590
+ if self._cython_call.is_ok():
591
+ return _common.deserialize(
592
+ serialized_response, self._response_deserializer
593
+ )
594
+ return cygrpc.EOF
595
+
596
+ async def wait_for_connection(self) -> None:
597
+ await self._invocation_task
598
+ if self.done():
599
+ await self._raise_for_status()
600
+
601
+
602
+ class UnaryStreamCall(_StreamResponseMixin, Call, _base_call.UnaryStreamCall):
603
+ """Object for managing unary-stream RPC calls.
604
+
605
+ Returned when an instance of `UnaryStreamMultiCallable` object is called.
606
+ """
607
+
608
+ _request: RequestType
609
+ _send_unary_request_task: asyncio.Task
610
+
611
+ # pylint: disable=too-many-arguments
612
+ def __init__(
613
+ self,
614
+ request: RequestType,
615
+ deadline: Optional[float],
616
+ metadata: Metadata,
617
+ credentials: Optional[grpc.CallCredentials],
618
+ wait_for_ready: Optional[bool],
619
+ channel: cygrpc.AioChannel,
620
+ method: bytes,
621
+ request_serializer: Optional[SerializingFunction],
622
+ response_deserializer: Optional[DeserializingFunction],
623
+ loop: asyncio.AbstractEventLoop,
624
+ ) -> None:
625
+ super().__init__(
626
+ channel.call(method, deadline, credentials, wait_for_ready),
627
+ metadata,
628
+ request_serializer,
629
+ response_deserializer,
630
+ loop,
631
+ )
632
+ self._request = request
633
+ self._context = cygrpc.build_census_context()
634
+ self._send_unary_request_task = loop.create_task(
635
+ self._send_unary_request()
636
+ )
637
+ self._init_stream_response_mixin(self._send_unary_request_task)
638
+
639
+ async def _send_unary_request(self) -> ResponseType:
640
+ serialized_request = _common.serialize(
641
+ self._request, self._request_serializer
642
+ )
643
+ try:
644
+ await self._cython_call.initiate_unary_stream(
645
+ serialized_request, self._metadata, self._context
646
+ )
647
+ except asyncio.CancelledError:
648
+ if not self.cancelled():
649
+ self.cancel()
650
+ raise
651
+
652
+ async def wait_for_connection(self) -> None:
653
+ await self._send_unary_request_task
654
+ if self.done():
655
+ await self._raise_for_status()
656
+
657
+
658
+ # pylint: disable=too-many-ancestors
659
+ class StreamUnaryCall(
660
+ _StreamRequestMixin, _UnaryResponseMixin, Call, _base_call.StreamUnaryCall
661
+ ):
662
+ """Object for managing stream-unary RPC calls.
663
+
664
+ Returned when an instance of `StreamUnaryMultiCallable` object is called.
665
+ """
666
+
667
+ # pylint: disable=too-many-arguments
668
+ def __init__(
669
+ self,
670
+ request_iterator: Optional[RequestIterableType],
671
+ deadline: Optional[float],
672
+ metadata: Metadata,
673
+ credentials: Optional[grpc.CallCredentials],
674
+ wait_for_ready: Optional[bool],
675
+ channel: cygrpc.AioChannel,
676
+ method: bytes,
677
+ request_serializer: Optional[SerializingFunction],
678
+ response_deserializer: Optional[DeserializingFunction],
679
+ loop: asyncio.AbstractEventLoop,
680
+ ) -> None:
681
+ super().__init__(
682
+ channel.call(method, deadline, credentials, wait_for_ready),
683
+ metadata,
684
+ request_serializer,
685
+ response_deserializer,
686
+ loop,
687
+ )
688
+
689
+ self._context = cygrpc.build_census_context()
690
+ self._init_stream_request_mixin(request_iterator)
691
+ self._init_unary_response_mixin(loop.create_task(self._conduct_rpc()))
692
+
693
+ async def _conduct_rpc(self) -> ResponseType:
694
+ try:
695
+ serialized_response = await self._cython_call.stream_unary(
696
+ self._metadata, self._metadata_sent_observer, self._context
697
+ )
698
+ except asyncio.CancelledError:
699
+ if not self.cancelled():
700
+ self.cancel()
701
+ raise
702
+
703
+ if self._cython_call.is_ok():
704
+ return _common.deserialize(
705
+ serialized_response, self._response_deserializer
706
+ )
707
+ return cygrpc.EOF
708
+
709
+
710
+ class StreamStreamCall(
711
+ _StreamRequestMixin, _StreamResponseMixin, Call, _base_call.StreamStreamCall
712
+ ):
713
+ """Object for managing stream-stream RPC calls.
714
+
715
+ Returned when an instance of `StreamStreamMultiCallable` object is called.
716
+ """
717
+
718
+ _initializer: asyncio.Task
719
+
720
+ # pylint: disable=too-many-arguments
721
+ def __init__(
722
+ self,
723
+ request_iterator: Optional[RequestIterableType],
724
+ deadline: Optional[float],
725
+ metadata: Metadata,
726
+ credentials: Optional[grpc.CallCredentials],
727
+ wait_for_ready: Optional[bool],
728
+ channel: cygrpc.AioChannel,
729
+ method: bytes,
730
+ request_serializer: Optional[SerializingFunction],
731
+ response_deserializer: Optional[DeserializingFunction],
732
+ loop: asyncio.AbstractEventLoop,
733
+ ) -> None:
734
+ super().__init__(
735
+ channel.call(method, deadline, credentials, wait_for_ready),
736
+ metadata,
737
+ request_serializer,
738
+ response_deserializer,
739
+ loop,
740
+ )
741
+ self._context = cygrpc.build_census_context()
742
+ self._initializer = self._loop.create_task(self._prepare_rpc())
743
+ self._init_stream_request_mixin(request_iterator)
744
+ self._init_stream_response_mixin(self._initializer)
745
+
746
+ async def _prepare_rpc(self):
747
+ """Prepares the RPC for receiving/sending messages.
748
+
749
+ All other operations around the stream should only happen after the
750
+ completion of this method.
751
+ """
752
+ try:
753
+ await self._cython_call.initiate_stream_stream(
754
+ self._metadata, self._metadata_sent_observer, self._context
755
+ )
756
+ except asyncio.CancelledError:
757
+ if not self.cancelled():
758
+ self.cancel()
759
+ # No need to raise RpcError here, because no one will `await` this task.
loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/_channel.py ADDED
@@ -0,0 +1,625 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2019 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
+ """Invocation-side implementation of gRPC Asyncio Python."""
15
+
16
+ import asyncio
17
+ import sys
18
+ from typing import Any, Iterable, List, Optional, Sequence
19
+
20
+ import grpc
21
+ from grpc import _common
22
+ from grpc import _compression
23
+ from grpc import _grpcio_metadata
24
+ from grpc._cython import cygrpc
25
+
26
+ from . import _base_call
27
+ from . import _base_channel
28
+ from ._call import StreamStreamCall
29
+ from ._call import StreamUnaryCall
30
+ from ._call import UnaryStreamCall
31
+ from ._call import UnaryUnaryCall
32
+ from ._interceptor import ClientInterceptor
33
+ from ._interceptor import InterceptedStreamStreamCall
34
+ from ._interceptor import InterceptedStreamUnaryCall
35
+ from ._interceptor import InterceptedUnaryStreamCall
36
+ from ._interceptor import InterceptedUnaryUnaryCall
37
+ from ._interceptor import StreamStreamClientInterceptor
38
+ from ._interceptor import StreamUnaryClientInterceptor
39
+ from ._interceptor import UnaryStreamClientInterceptor
40
+ from ._interceptor import UnaryUnaryClientInterceptor
41
+ from ._metadata import Metadata
42
+ from ._typing import ChannelArgumentType
43
+ from ._typing import DeserializingFunction
44
+ from ._typing import MetadataType
45
+ from ._typing import RequestIterableType
46
+ from ._typing import RequestType
47
+ from ._typing import ResponseType
48
+ from ._typing import SerializingFunction
49
+ from ._utils import _timeout_to_deadline
50
+
51
+ _USER_AGENT = "grpc-python-asyncio/{}".format(_grpcio_metadata.__version__)
52
+
53
+ if sys.version_info[1] < 7:
54
+
55
+ def _all_tasks() -> Iterable[asyncio.Task]:
56
+ return asyncio.Task.all_tasks() # pylint: disable=no-member
57
+
58
+ else:
59
+
60
+ def _all_tasks() -> Iterable[asyncio.Task]:
61
+ return asyncio.all_tasks()
62
+
63
+
64
+ def _augment_channel_arguments(
65
+ base_options: ChannelArgumentType, compression: Optional[grpc.Compression]
66
+ ):
67
+ compression_channel_argument = _compression.create_channel_option(
68
+ compression
69
+ )
70
+ user_agent_channel_argument = (
71
+ (
72
+ cygrpc.ChannelArgKey.primary_user_agent_string,
73
+ _USER_AGENT,
74
+ ),
75
+ )
76
+ return (
77
+ tuple(base_options)
78
+ + compression_channel_argument
79
+ + user_agent_channel_argument
80
+ )
81
+
82
+
83
+ class _BaseMultiCallable:
84
+ """Base class of all multi callable objects.
85
+
86
+ Handles the initialization logic and stores common attributes.
87
+ """
88
+
89
+ _loop: asyncio.AbstractEventLoop
90
+ _channel: cygrpc.AioChannel
91
+ _method: bytes
92
+ _request_serializer: Optional[SerializingFunction]
93
+ _response_deserializer: Optional[DeserializingFunction]
94
+ _interceptors: Optional[Sequence[ClientInterceptor]]
95
+ _references: List[Any]
96
+ _loop: asyncio.AbstractEventLoop
97
+
98
+ # pylint: disable=too-many-arguments
99
+ def __init__(
100
+ self,
101
+ channel: cygrpc.AioChannel,
102
+ method: bytes,
103
+ request_serializer: Optional[SerializingFunction],
104
+ response_deserializer: Optional[DeserializingFunction],
105
+ interceptors: Optional[Sequence[ClientInterceptor]],
106
+ references: List[Any],
107
+ loop: asyncio.AbstractEventLoop,
108
+ ) -> None:
109
+ self._loop = loop
110
+ self._channel = channel
111
+ self._method = method
112
+ self._request_serializer = request_serializer
113
+ self._response_deserializer = response_deserializer
114
+ self._interceptors = interceptors
115
+ self._references = references
116
+
117
+ @staticmethod
118
+ def _init_metadata(
119
+ metadata: Optional[MetadataType] = None,
120
+ compression: Optional[grpc.Compression] = None,
121
+ ) -> Metadata:
122
+ """Based on the provided values for <metadata> or <compression> initialise the final
123
+ metadata, as it should be used for the current call.
124
+ """
125
+ metadata = metadata or Metadata()
126
+ if not isinstance(metadata, Metadata) and isinstance(
127
+ metadata, Sequence
128
+ ):
129
+ metadata = Metadata.from_tuple(tuple(metadata))
130
+ if compression:
131
+ metadata = Metadata(
132
+ *_compression.augment_metadata(metadata, compression)
133
+ )
134
+ return metadata
135
+
136
+
137
+ class UnaryUnaryMultiCallable(
138
+ _BaseMultiCallable, _base_channel.UnaryUnaryMultiCallable
139
+ ):
140
+ def __call__(
141
+ self,
142
+ request: RequestType,
143
+ *,
144
+ timeout: Optional[float] = None,
145
+ metadata: Optional[MetadataType] = None,
146
+ credentials: Optional[grpc.CallCredentials] = None,
147
+ wait_for_ready: Optional[bool] = None,
148
+ compression: Optional[grpc.Compression] = None,
149
+ ) -> _base_call.UnaryUnaryCall[RequestType, ResponseType]:
150
+ metadata = self._init_metadata(metadata, compression)
151
+ if not self._interceptors:
152
+ call = UnaryUnaryCall(
153
+ request,
154
+ _timeout_to_deadline(timeout),
155
+ metadata,
156
+ credentials,
157
+ wait_for_ready,
158
+ self._channel,
159
+ self._method,
160
+ self._request_serializer,
161
+ self._response_deserializer,
162
+ self._loop,
163
+ )
164
+ else:
165
+ call = InterceptedUnaryUnaryCall(
166
+ self._interceptors,
167
+ request,
168
+ timeout,
169
+ metadata,
170
+ credentials,
171
+ wait_for_ready,
172
+ self._channel,
173
+ self._method,
174
+ self._request_serializer,
175
+ self._response_deserializer,
176
+ self._loop,
177
+ )
178
+
179
+ return call
180
+
181
+
182
+ class UnaryStreamMultiCallable(
183
+ _BaseMultiCallable, _base_channel.UnaryStreamMultiCallable
184
+ ):
185
+ def __call__(
186
+ self,
187
+ request: RequestType,
188
+ *,
189
+ timeout: Optional[float] = None,
190
+ metadata: Optional[MetadataType] = None,
191
+ credentials: Optional[grpc.CallCredentials] = None,
192
+ wait_for_ready: Optional[bool] = None,
193
+ compression: Optional[grpc.Compression] = None,
194
+ ) -> _base_call.UnaryStreamCall[RequestType, ResponseType]:
195
+ metadata = self._init_metadata(metadata, compression)
196
+
197
+ if not self._interceptors:
198
+ call = UnaryStreamCall(
199
+ request,
200
+ _timeout_to_deadline(timeout),
201
+ metadata,
202
+ credentials,
203
+ wait_for_ready,
204
+ self._channel,
205
+ self._method,
206
+ self._request_serializer,
207
+ self._response_deserializer,
208
+ self._loop,
209
+ )
210
+ else:
211
+ call = InterceptedUnaryStreamCall(
212
+ self._interceptors,
213
+ request,
214
+ timeout,
215
+ metadata,
216
+ credentials,
217
+ wait_for_ready,
218
+ self._channel,
219
+ self._method,
220
+ self._request_serializer,
221
+ self._response_deserializer,
222
+ self._loop,
223
+ )
224
+
225
+ return call
226
+
227
+
228
+ class StreamUnaryMultiCallable(
229
+ _BaseMultiCallable, _base_channel.StreamUnaryMultiCallable
230
+ ):
231
+ def __call__(
232
+ self,
233
+ request_iterator: Optional[RequestIterableType] = None,
234
+ timeout: Optional[float] = None,
235
+ metadata: Optional[MetadataType] = None,
236
+ credentials: Optional[grpc.CallCredentials] = None,
237
+ wait_for_ready: Optional[bool] = None,
238
+ compression: Optional[grpc.Compression] = None,
239
+ ) -> _base_call.StreamUnaryCall:
240
+ metadata = self._init_metadata(metadata, compression)
241
+
242
+ if not self._interceptors:
243
+ call = StreamUnaryCall(
244
+ request_iterator,
245
+ _timeout_to_deadline(timeout),
246
+ metadata,
247
+ credentials,
248
+ wait_for_ready,
249
+ self._channel,
250
+ self._method,
251
+ self._request_serializer,
252
+ self._response_deserializer,
253
+ self._loop,
254
+ )
255
+ else:
256
+ call = InterceptedStreamUnaryCall(
257
+ self._interceptors,
258
+ request_iterator,
259
+ timeout,
260
+ metadata,
261
+ credentials,
262
+ wait_for_ready,
263
+ self._channel,
264
+ self._method,
265
+ self._request_serializer,
266
+ self._response_deserializer,
267
+ self._loop,
268
+ )
269
+
270
+ return call
271
+
272
+
273
+ class StreamStreamMultiCallable(
274
+ _BaseMultiCallable, _base_channel.StreamStreamMultiCallable
275
+ ):
276
+ def __call__(
277
+ self,
278
+ request_iterator: Optional[RequestIterableType] = None,
279
+ timeout: Optional[float] = None,
280
+ metadata: Optional[MetadataType] = None,
281
+ credentials: Optional[grpc.CallCredentials] = None,
282
+ wait_for_ready: Optional[bool] = None,
283
+ compression: Optional[grpc.Compression] = None,
284
+ ) -> _base_call.StreamStreamCall:
285
+ metadata = self._init_metadata(metadata, compression)
286
+
287
+ if not self._interceptors:
288
+ call = StreamStreamCall(
289
+ request_iterator,
290
+ _timeout_to_deadline(timeout),
291
+ metadata,
292
+ credentials,
293
+ wait_for_ready,
294
+ self._channel,
295
+ self._method,
296
+ self._request_serializer,
297
+ self._response_deserializer,
298
+ self._loop,
299
+ )
300
+ else:
301
+ call = InterceptedStreamStreamCall(
302
+ self._interceptors,
303
+ request_iterator,
304
+ timeout,
305
+ metadata,
306
+ credentials,
307
+ wait_for_ready,
308
+ self._channel,
309
+ self._method,
310
+ self._request_serializer,
311
+ self._response_deserializer,
312
+ self._loop,
313
+ )
314
+
315
+ return call
316
+
317
+
318
+ class Channel(_base_channel.Channel):
319
+ _loop: asyncio.AbstractEventLoop
320
+ _channel: cygrpc.AioChannel
321
+ _unary_unary_interceptors: List[UnaryUnaryClientInterceptor]
322
+ _unary_stream_interceptors: List[UnaryStreamClientInterceptor]
323
+ _stream_unary_interceptors: List[StreamUnaryClientInterceptor]
324
+ _stream_stream_interceptors: List[StreamStreamClientInterceptor]
325
+
326
+ def __init__(
327
+ self,
328
+ target: str,
329
+ options: ChannelArgumentType,
330
+ credentials: Optional[cygrpc.ChannelCredentials],
331
+ compression: Optional[grpc.Compression],
332
+ interceptors: Optional[Sequence[ClientInterceptor]],
333
+ ):
334
+ """Constructor.
335
+
336
+ Args:
337
+ target: The target to which to connect.
338
+ options: Configuration options for the channel.
339
+ credentials: A cygrpc.ChannelCredentials or None.
340
+ compression: An optional value indicating the compression method to be
341
+ used over the lifetime of the channel.
342
+ interceptors: An optional list of interceptors that would be used for
343
+ intercepting any RPC executed with that channel.
344
+ """
345
+ self._unary_unary_interceptors = []
346
+ self._unary_stream_interceptors = []
347
+ self._stream_unary_interceptors = []
348
+ self._stream_stream_interceptors = []
349
+
350
+ if interceptors is not None:
351
+ for interceptor in interceptors:
352
+ if isinstance(interceptor, UnaryUnaryClientInterceptor):
353
+ self._unary_unary_interceptors.append(interceptor)
354
+ elif isinstance(interceptor, UnaryStreamClientInterceptor):
355
+ self._unary_stream_interceptors.append(interceptor)
356
+ elif isinstance(interceptor, StreamUnaryClientInterceptor):
357
+ self._stream_unary_interceptors.append(interceptor)
358
+ elif isinstance(interceptor, StreamStreamClientInterceptor):
359
+ self._stream_stream_interceptors.append(interceptor)
360
+ else:
361
+ raise ValueError( # noqa: TRY004
362
+ "Interceptor {} must be ".format(interceptor)
363
+ + "{} or ".format(UnaryUnaryClientInterceptor.__name__)
364
+ + "{} or ".format(UnaryStreamClientInterceptor.__name__)
365
+ + "{} or ".format(StreamUnaryClientInterceptor.__name__)
366
+ + "{}. ".format(StreamStreamClientInterceptor.__name__)
367
+ )
368
+
369
+ self._loop = cygrpc.get_working_loop()
370
+ self._channel = cygrpc.AioChannel(
371
+ _common.encode(target),
372
+ _augment_channel_arguments(options, compression),
373
+ credentials,
374
+ self._loop,
375
+ )
376
+
377
+ async def __aenter__(self):
378
+ return self
379
+
380
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
381
+ await self._close(None)
382
+
383
+ async def _close(self, grace): # pylint: disable=too-many-branches
384
+ if self._channel.closed():
385
+ return
386
+
387
+ # No new calls will be accepted by the Cython channel.
388
+ self._channel.closing()
389
+
390
+ # Iterate through running tasks
391
+ tasks = _all_tasks()
392
+ calls = []
393
+ call_tasks = []
394
+ for task in tasks:
395
+ try:
396
+ stack = task.get_stack(limit=1)
397
+ except AttributeError as attribute_error:
398
+ # NOTE(lidiz) tl;dr: If the Task is created with a CPython
399
+ # object, it will trigger AttributeError.
400
+ #
401
+ # In the global finalizer, the event loop schedules
402
+ # a CPython PyAsyncGenAThrow object.
403
+ # https://github.com/python/cpython/blob/00e45877e33d32bb61aa13a2033e3bba370bda4d/Lib/asyncio/base_events.py#L484
404
+ #
405
+ # However, the PyAsyncGenAThrow object is written in C and
406
+ # failed to include the normal Python frame objects. Hence,
407
+ # this exception is a false negative, and it is safe to ignore
408
+ # the failure. It is fixed by https://github.com/python/cpython/pull/18669,
409
+ # but not available until 3.9 or 3.8.3. So, we have to keep it
410
+ # for a while.
411
+ # TODO(lidiz): drop this hack after 3.8 deprecation
412
+ if "frame" in str(attribute_error):
413
+ continue
414
+ raise
415
+
416
+ # If the Task is created by a C-extension, the stack will be empty.
417
+ if not stack:
418
+ continue
419
+
420
+ # Locate ones created by `aio.Call`.
421
+ frame = stack[0]
422
+ candidate = frame.f_locals.get("self")
423
+ # Explicitly check for a non-null candidate instead of the more pythonic 'if candidate:'
424
+ # because doing 'if candidate:' assumes that the coroutine implements '__bool__' which
425
+ # might not always be the case.
426
+ if candidate is not None and isinstance(candidate, _base_call.Call):
427
+ if hasattr(candidate, "_channel"):
428
+ # For intercepted Call object
429
+ if candidate._channel is not self._channel:
430
+ continue
431
+ elif hasattr(candidate, "_cython_call"):
432
+ # For normal Call object
433
+ if candidate._cython_call._channel is not self._channel:
434
+ continue
435
+ else:
436
+ # Unidentified Call object
437
+ error_msg = f"Unrecognized call object: {candidate}"
438
+ raise cygrpc.InternalError(error_msg)
439
+
440
+ calls.append(candidate)
441
+ call_tasks.append(task)
442
+
443
+ # If needed, try to wait for them to finish.
444
+ # Call objects are not always awaitables.
445
+ if grace and call_tasks:
446
+ await asyncio.wait(call_tasks, timeout=grace)
447
+
448
+ # Time to cancel existing calls.
449
+ for call in calls:
450
+ call.cancel()
451
+
452
+ # Destroy the channel
453
+ self._channel.close()
454
+
455
+ async def close(self, grace: Optional[float] = None):
456
+ await self._close(grace)
457
+
458
+ def __del__(self):
459
+ if hasattr(self, "_channel") and not self._channel.closed():
460
+ self._channel.close()
461
+
462
+ def get_state(
463
+ self, try_to_connect: bool = False
464
+ ) -> grpc.ChannelConnectivity:
465
+ result = self._channel.check_connectivity_state(try_to_connect)
466
+ return _common.CYGRPC_CONNECTIVITY_STATE_TO_CHANNEL_CONNECTIVITY[result]
467
+
468
+ async def wait_for_state_change(
469
+ self,
470
+ last_observed_state: grpc.ChannelConnectivity,
471
+ ) -> None:
472
+ assert await self._channel.watch_connectivity_state(
473
+ last_observed_state.value[0], None
474
+ )
475
+
476
+ async def channel_ready(self) -> None:
477
+ state = self.get_state(try_to_connect=True)
478
+ while state != grpc.ChannelConnectivity.READY:
479
+ await self.wait_for_state_change(state)
480
+ state = self.get_state(try_to_connect=True)
481
+
482
+ # TODO(xuanwn): Implement this method after we have
483
+ # observability for Asyncio.
484
+ def _get_registered_call_handle(self, method: str) -> int:
485
+ pass
486
+
487
+ # TODO(xuanwn): Implement _registered_method after we have
488
+ # observability for Asyncio.
489
+ # pylint: disable=arguments-differ,unused-argument
490
+ def unary_unary(
491
+ self,
492
+ method: str,
493
+ request_serializer: Optional[SerializingFunction] = None,
494
+ response_deserializer: Optional[DeserializingFunction] = None,
495
+ _registered_method: Optional[bool] = False,
496
+ ) -> UnaryUnaryMultiCallable:
497
+ return UnaryUnaryMultiCallable(
498
+ self._channel,
499
+ _common.encode(method),
500
+ request_serializer,
501
+ response_deserializer,
502
+ self._unary_unary_interceptors,
503
+ [self],
504
+ self._loop,
505
+ )
506
+
507
+ # TODO(xuanwn): Implement _registered_method after we have
508
+ # observability for Asyncio.
509
+ # pylint: disable=arguments-differ,unused-argument
510
+ def unary_stream(
511
+ self,
512
+ method: str,
513
+ request_serializer: Optional[SerializingFunction] = None,
514
+ response_deserializer: Optional[DeserializingFunction] = None,
515
+ _registered_method: Optional[bool] = False,
516
+ ) -> UnaryStreamMultiCallable:
517
+ return UnaryStreamMultiCallable(
518
+ self._channel,
519
+ _common.encode(method),
520
+ request_serializer,
521
+ response_deserializer,
522
+ self._unary_stream_interceptors,
523
+ [self],
524
+ self._loop,
525
+ )
526
+
527
+ # TODO(xuanwn): Implement _registered_method after we have
528
+ # observability for Asyncio.
529
+ # pylint: disable=arguments-differ,unused-argument
530
+ def stream_unary(
531
+ self,
532
+ method: str,
533
+ request_serializer: Optional[SerializingFunction] = None,
534
+ response_deserializer: Optional[DeserializingFunction] = None,
535
+ _registered_method: Optional[bool] = False,
536
+ ) -> StreamUnaryMultiCallable:
537
+ return StreamUnaryMultiCallable(
538
+ self._channel,
539
+ _common.encode(method),
540
+ request_serializer,
541
+ response_deserializer,
542
+ self._stream_unary_interceptors,
543
+ [self],
544
+ self._loop,
545
+ )
546
+
547
+ # TODO(xuanwn): Implement _registered_method after we have
548
+ # observability for Asyncio.
549
+ # pylint: disable=arguments-differ,unused-argument
550
+ def stream_stream(
551
+ self,
552
+ method: str,
553
+ request_serializer: Optional[SerializingFunction] = None,
554
+ response_deserializer: Optional[DeserializingFunction] = None,
555
+ _registered_method: Optional[bool] = False,
556
+ ) -> StreamStreamMultiCallable:
557
+ return StreamStreamMultiCallable(
558
+ self._channel,
559
+ _common.encode(method),
560
+ request_serializer,
561
+ response_deserializer,
562
+ self._stream_stream_interceptors,
563
+ [self],
564
+ self._loop,
565
+ )
566
+
567
+
568
+ def insecure_channel(
569
+ target: str,
570
+ options: Optional[ChannelArgumentType] = None,
571
+ compression: Optional[grpc.Compression] = None,
572
+ interceptors: Optional[Sequence[ClientInterceptor]] = None,
573
+ ):
574
+ """Creates an insecure asynchronous Channel to a server.
575
+
576
+ Args:
577
+ target: The server address
578
+ options: An optional list of key-value pairs (:term:`channel_arguments`
579
+ in gRPC Core runtime) to configure the channel.
580
+ compression: An optional value indicating the compression method to be
581
+ used over the lifetime of the channel.
582
+ interceptors: An optional sequence of interceptors that will be executed for
583
+ any call executed with this channel.
584
+
585
+ Returns:
586
+ A Channel.
587
+ """
588
+ return Channel(
589
+ target,
590
+ () if options is None else options,
591
+ None,
592
+ compression,
593
+ interceptors,
594
+ )
595
+
596
+
597
+ def secure_channel(
598
+ target: str,
599
+ credentials: grpc.ChannelCredentials,
600
+ options: Optional[ChannelArgumentType] = None,
601
+ compression: Optional[grpc.Compression] = None,
602
+ interceptors: Optional[Sequence[ClientInterceptor]] = None,
603
+ ):
604
+ """Creates a secure asynchronous Channel to a server.
605
+
606
+ Args:
607
+ target: The server address.
608
+ credentials: A ChannelCredentials instance.
609
+ options: An optional list of key-value pairs (:term:`channel_arguments`
610
+ in gRPC Core runtime) to configure the channel.
611
+ compression: An optional value indicating the compression method to be
612
+ used over the lifetime of the channel.
613
+ interceptors: An optional sequence of interceptors that will be executed for
614
+ any call executed with this channel.
615
+
616
+ Returns:
617
+ An aio.Channel.
618
+ """
619
+ return Channel(
620
+ target,
621
+ () if options is None else options,
622
+ credentials._credentials,
623
+ compression,
624
+ interceptors,
625
+ )
loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/_interceptor.py ADDED
@@ -0,0 +1,1177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2019 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
+ """Interceptors implementation of gRPC Asyncio Python."""
15
+ from __future__ import annotations
16
+
17
+ from abc import ABCMeta
18
+ from abc import abstractmethod
19
+ import asyncio
20
+ import collections
21
+ import functools
22
+ from typing import (
23
+ AsyncIterable,
24
+ AsyncIterator,
25
+ Awaitable,
26
+ Callable,
27
+ List,
28
+ Optional,
29
+ Sequence,
30
+ Union,
31
+ )
32
+
33
+ import grpc
34
+ from grpc._cython import cygrpc
35
+
36
+ from . import _base_call
37
+ from ._call import AioRpcError
38
+ from ._call import StreamStreamCall
39
+ from ._call import StreamUnaryCall
40
+ from ._call import UnaryStreamCall
41
+ from ._call import UnaryUnaryCall
42
+ from ._call import _API_STYLE_ERROR
43
+ from ._call import _RPC_ALREADY_FINISHED_DETAILS
44
+ from ._call import _RPC_HALF_CLOSED_DETAILS
45
+ from ._metadata import Metadata
46
+ from ._typing import DeserializingFunction
47
+ from ._typing import DoneCallbackType
48
+ from ._typing import EOFType
49
+ from ._typing import RequestIterableType
50
+ from ._typing import RequestType
51
+ from ._typing import ResponseIterableType
52
+ from ._typing import ResponseType
53
+ from ._typing import SerializingFunction
54
+ from ._utils import _timeout_to_deadline
55
+
56
+ _LOCAL_CANCELLATION_DETAILS = "Locally cancelled by application!"
57
+
58
+
59
+ class ServerInterceptor(metaclass=ABCMeta):
60
+ """Affords intercepting incoming RPCs on the service-side.
61
+
62
+ This is an EXPERIMENTAL API.
63
+ """
64
+
65
+ @abstractmethod
66
+ async def intercept_service(
67
+ self,
68
+ continuation: Callable[
69
+ [grpc.HandlerCallDetails], Awaitable[grpc.RpcMethodHandler]
70
+ ],
71
+ handler_call_details: grpc.HandlerCallDetails,
72
+ ) -> grpc.RpcMethodHandler:
73
+ """Intercepts incoming RPCs before handing them over to a handler.
74
+
75
+ State can be passed from an interceptor to downstream interceptors
76
+ via contextvars. The first interceptor is called from an empty
77
+ contextvars.Context, and the same Context is used for downstream
78
+ interceptors and for the final handler call. Note that there are no
79
+ guarantees that interceptors and handlers will be called from the
80
+ same thread.
81
+
82
+ Args:
83
+ continuation: A function that takes a HandlerCallDetails and
84
+ proceeds to invoke the next interceptor in the chain, if any,
85
+ or the RPC handler lookup logic, with the call details passed
86
+ as an argument, and returns an RpcMethodHandler instance if
87
+ the RPC is considered serviced, or None otherwise.
88
+ handler_call_details: A HandlerCallDetails describing the RPC.
89
+
90
+ Returns:
91
+ An RpcMethodHandler with which the RPC may be serviced if the
92
+ interceptor chooses to service this RPC, or None otherwise.
93
+ """
94
+
95
+
96
+ class ClientCallDetails(
97
+ collections.namedtuple(
98
+ "ClientCallDetails",
99
+ ("method", "timeout", "metadata", "credentials", "wait_for_ready"),
100
+ ),
101
+ grpc.ClientCallDetails,
102
+ ):
103
+ """Describes an RPC to be invoked.
104
+
105
+ This is an EXPERIMENTAL API.
106
+
107
+ Args:
108
+ method: The method name of the RPC.
109
+ timeout: An optional duration of time in seconds to allow for the RPC.
110
+ metadata: Optional metadata to be transmitted to the service-side of
111
+ the RPC.
112
+ credentials: An optional CallCredentials for the RPC.
113
+ wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
114
+ """
115
+
116
+ method: bytes
117
+ timeout: Optional[float]
118
+ metadata: Optional[Metadata]
119
+ credentials: Optional[grpc.CallCredentials]
120
+ wait_for_ready: Optional[bool]
121
+
122
+
123
+ class ClientInterceptor(metaclass=ABCMeta):
124
+ """Base class used for all Aio Client Interceptor classes"""
125
+
126
+
127
+ class UnaryUnaryClientInterceptor(ClientInterceptor, metaclass=ABCMeta):
128
+ """Affords intercepting unary-unary invocations."""
129
+
130
+ @abstractmethod
131
+ async def intercept_unary_unary(
132
+ self,
133
+ continuation: Callable[
134
+ [ClientCallDetails, RequestType], UnaryUnaryCall
135
+ ],
136
+ client_call_details: ClientCallDetails,
137
+ request: RequestType,
138
+ ) -> Union[UnaryUnaryCall, ResponseType]:
139
+ """Intercepts a unary-unary invocation asynchronously.
140
+
141
+ Args:
142
+ continuation: A coroutine that proceeds with the invocation by
143
+ executing the next interceptor in the chain or invoking the
144
+ actual RPC on the underlying Channel. It is the interceptor's
145
+ responsibility to call it if it decides to move the RPC forward.
146
+ The interceptor can use
147
+ `call = await continuation(client_call_details, request)`
148
+ to continue with the RPC. `continuation` returns the call to the
149
+ RPC.
150
+ client_call_details: A ClientCallDetails object describing the
151
+ outgoing RPC.
152
+ request: The request value for the RPC.
153
+
154
+ Returns:
155
+ An object with the RPC response.
156
+
157
+ Raises:
158
+ AioRpcError: Indicating that the RPC terminated with non-OK status.
159
+ asyncio.CancelledError: Indicating that the RPC was canceled.
160
+ """
161
+
162
+
163
+ class UnaryStreamClientInterceptor(ClientInterceptor, metaclass=ABCMeta):
164
+ """Affords intercepting unary-stream invocations."""
165
+
166
+ @abstractmethod
167
+ async def intercept_unary_stream(
168
+ self,
169
+ continuation: Callable[
170
+ [ClientCallDetails, RequestType], UnaryStreamCall
171
+ ],
172
+ client_call_details: ClientCallDetails,
173
+ request: RequestType,
174
+ ) -> Union[ResponseIterableType, UnaryStreamCall]:
175
+ """Intercepts a unary-stream invocation asynchronously.
176
+
177
+ The function could return the call object or an asynchronous
178
+ iterator, in case of being an asyncrhonous iterator this will
179
+ become the source of the reads done by the caller.
180
+
181
+ Args:
182
+ continuation: A coroutine that proceeds with the invocation by
183
+ executing the next interceptor in the chain or invoking the
184
+ actual RPC on the underlying Channel. It is the interceptor's
185
+ responsibility to call it if it decides to move the RPC forward.
186
+ The interceptor can use
187
+ `call = await continuation(client_call_details, request)`
188
+ to continue with the RPC. `continuation` returns the call to the
189
+ RPC.
190
+ client_call_details: A ClientCallDetails object describing the
191
+ outgoing RPC.
192
+ request: The request value for the RPC.
193
+
194
+ Returns:
195
+ The RPC Call or an asynchronous iterator.
196
+
197
+ Raises:
198
+ AioRpcError: Indicating that the RPC terminated with non-OK status.
199
+ asyncio.CancelledError: Indicating that the RPC was canceled.
200
+ """
201
+
202
+
203
+ class StreamUnaryClientInterceptor(ClientInterceptor, metaclass=ABCMeta):
204
+ """Affords intercepting stream-unary invocations."""
205
+
206
+ @abstractmethod
207
+ async def intercept_stream_unary(
208
+ self,
209
+ continuation: Callable[
210
+ [ClientCallDetails, RequestType], StreamUnaryCall
211
+ ],
212
+ client_call_details: ClientCallDetails,
213
+ request_iterator: RequestIterableType,
214
+ ) -> StreamUnaryCall:
215
+ """Intercepts a stream-unary invocation asynchronously.
216
+
217
+ Within the interceptor the usage of the call methods like `write` or
218
+ even awaiting the call should be done carefully, since the caller
219
+ could be expecting an untouched call, for example for start writing
220
+ messages to it.
221
+
222
+ Args:
223
+ continuation: A coroutine that proceeds with the invocation by
224
+ executing the next interceptor in the chain or invoking the
225
+ actual RPC on the underlying Channel. It is the interceptor's
226
+ responsibility to call it if it decides to move the RPC forward.
227
+ The interceptor can use
228
+ `call = await continuation(client_call_details, request_iterator)`
229
+ to continue with the RPC. `continuation` returns the call to the
230
+ RPC.
231
+ client_call_details: A ClientCallDetails object describing the
232
+ outgoing RPC.
233
+ request_iterator: The request iterator that will produce requests
234
+ for the RPC.
235
+
236
+ Returns:
237
+ The RPC Call.
238
+
239
+ Raises:
240
+ AioRpcError: Indicating that the RPC terminated with non-OK status.
241
+ asyncio.CancelledError: Indicating that the RPC was canceled.
242
+ """
243
+
244
+
245
+ class StreamStreamClientInterceptor(ClientInterceptor, metaclass=ABCMeta):
246
+ """Affords intercepting stream-stream invocations."""
247
+
248
+ @abstractmethod
249
+ async def intercept_stream_stream(
250
+ self,
251
+ continuation: Callable[
252
+ [ClientCallDetails, RequestType], StreamStreamCall
253
+ ],
254
+ client_call_details: ClientCallDetails,
255
+ request_iterator: RequestIterableType,
256
+ ) -> Union[ResponseIterableType, StreamStreamCall]:
257
+ """Intercepts a stream-stream invocation asynchronously.
258
+
259
+ Within the interceptor the usage of the call methods like `write` or
260
+ even awaiting the call should be done carefully, since the caller
261
+ could be expecting an untouched call, for example for start writing
262
+ messages to it.
263
+
264
+ The function could return the call object or an asynchronous
265
+ iterator, in case of being an asyncrhonous iterator this will
266
+ become the source of the reads done by the caller.
267
+
268
+ Args:
269
+ continuation: A coroutine that proceeds with the invocation by
270
+ executing the next interceptor in the chain or invoking the
271
+ actual RPC on the underlying Channel. It is the interceptor's
272
+ responsibility to call it if it decides to move the RPC forward.
273
+ The interceptor can use
274
+ `call = await continuation(client_call_details, request_iterator)`
275
+ to continue with the RPC. `continuation` returns the call to the
276
+ RPC.
277
+ client_call_details: A ClientCallDetails object describing the
278
+ outgoing RPC.
279
+ request_iterator: The request iterator that will produce requests
280
+ for the RPC.
281
+
282
+ Returns:
283
+ The RPC Call or an asynchronous iterator.
284
+
285
+ Raises:
286
+ AioRpcError: Indicating that the RPC terminated with non-OK status.
287
+ asyncio.CancelledError: Indicating that the RPC was canceled.
288
+ """
289
+
290
+
291
+ class InterceptedCall:
292
+ """Base implementation for all intercepted call arities.
293
+
294
+ Interceptors might have some work to do before the RPC invocation with
295
+ the capacity of changing the invocation parameters, and some work to do
296
+ after the RPC invocation with the capacity for accessing to the wrapped
297
+ `UnaryUnaryCall`.
298
+
299
+ It handles also early and later cancellations, when the RPC has not even
300
+ started and the execution is still held by the interceptors or when the
301
+ RPC has finished but again the execution is still held by the interceptors.
302
+
303
+ Once the RPC is finally executed, all methods are finally done against the
304
+ intercepted call, being at the same time the same call returned to the
305
+ interceptors.
306
+
307
+ As a base class for all of the interceptors implements the logic around
308
+ final status, metadata and cancellation.
309
+ """
310
+
311
+ _interceptors_task: asyncio.Task
312
+ _pending_add_done_callbacks: Sequence[DoneCallbackType]
313
+
314
+ def __init__(self, interceptors_task: asyncio.Task) -> None:
315
+ self._interceptors_task = interceptors_task
316
+ self._pending_add_done_callbacks = []
317
+ self._interceptors_task.add_done_callback(
318
+ self._fire_or_add_pending_done_callbacks
319
+ )
320
+
321
+ def __del__(self):
322
+ self.cancel()
323
+
324
+ def _fire_or_add_pending_done_callbacks(
325
+ self, interceptors_task: asyncio.Task
326
+ ) -> None:
327
+ if not self._pending_add_done_callbacks:
328
+ return
329
+
330
+ call_completed = False
331
+
332
+ try:
333
+ call = interceptors_task.result()
334
+ if call.done():
335
+ call_completed = True
336
+ except (AioRpcError, asyncio.CancelledError):
337
+ call_completed = True
338
+
339
+ if call_completed:
340
+ for callback in self._pending_add_done_callbacks:
341
+ callback(self)
342
+ else:
343
+ for callback in self._pending_add_done_callbacks:
344
+ callback = functools.partial(
345
+ self._wrap_add_done_callback, callback
346
+ )
347
+ call.add_done_callback(callback)
348
+
349
+ self._pending_add_done_callbacks = []
350
+
351
+ def _wrap_add_done_callback(
352
+ self, callback: DoneCallbackType, unused_call: _base_call.Call
353
+ ) -> None:
354
+ callback(self)
355
+
356
+ def cancel(self) -> bool:
357
+ if not self._interceptors_task.done():
358
+ # There is no yet the intercepted call available,
359
+ # Trying to cancel it by using the generic Asyncio
360
+ # cancellation method.
361
+ return self._interceptors_task.cancel()
362
+
363
+ try:
364
+ call = self._interceptors_task.result()
365
+ except AioRpcError:
366
+ return False
367
+ except asyncio.CancelledError:
368
+ return False
369
+
370
+ return call.cancel()
371
+
372
+ def cancelled(self) -> bool:
373
+ if not self._interceptors_task.done():
374
+ return False
375
+
376
+ try:
377
+ call = self._interceptors_task.result()
378
+ except AioRpcError as err:
379
+ return err.code() == grpc.StatusCode.CANCELLED
380
+ except asyncio.CancelledError:
381
+ return True
382
+
383
+ return call.cancelled()
384
+
385
+ def done(self) -> bool:
386
+ if not self._interceptors_task.done():
387
+ return False
388
+
389
+ try:
390
+ call = self._interceptors_task.result()
391
+ except (AioRpcError, asyncio.CancelledError):
392
+ return True
393
+
394
+ return call.done()
395
+
396
+ def add_done_callback(self, callback: DoneCallbackType) -> None:
397
+ if not self._interceptors_task.done():
398
+ self._pending_add_done_callbacks.append(callback)
399
+ return
400
+
401
+ try:
402
+ call = self._interceptors_task.result()
403
+ except (AioRpcError, asyncio.CancelledError):
404
+ callback(self)
405
+ return
406
+
407
+ if call.done():
408
+ callback(self)
409
+ else:
410
+ callback = functools.partial(self._wrap_add_done_callback, callback)
411
+ call.add_done_callback(callback)
412
+
413
+ def time_remaining(self) -> Optional[float]:
414
+ raise NotImplementedError()
415
+
416
+ async def initial_metadata(self) -> Optional[Metadata]:
417
+ try:
418
+ call = await self._interceptors_task
419
+ except AioRpcError as err:
420
+ return err.initial_metadata()
421
+ except asyncio.CancelledError:
422
+ return None
423
+
424
+ return await call.initial_metadata()
425
+
426
+ async def trailing_metadata(self) -> Optional[Metadata]:
427
+ try:
428
+ call = await self._interceptors_task
429
+ except AioRpcError as err:
430
+ return err.trailing_metadata()
431
+ except asyncio.CancelledError:
432
+ return None
433
+
434
+ return await call.trailing_metadata()
435
+
436
+ async def code(self) -> grpc.StatusCode:
437
+ try:
438
+ call = await self._interceptors_task
439
+ except AioRpcError as err:
440
+ return err.code()
441
+ except asyncio.CancelledError:
442
+ return grpc.StatusCode.CANCELLED
443
+
444
+ return await call.code()
445
+
446
+ async def details(self) -> str:
447
+ try:
448
+ call = await self._interceptors_task
449
+ except AioRpcError as err:
450
+ return err.details()
451
+ except asyncio.CancelledError:
452
+ return _LOCAL_CANCELLATION_DETAILS
453
+
454
+ return await call.details()
455
+
456
+ async def debug_error_string(self) -> Optional[str]:
457
+ try:
458
+ call = await self._interceptors_task
459
+ except AioRpcError as err:
460
+ return err.debug_error_string()
461
+ except asyncio.CancelledError:
462
+ return ""
463
+
464
+ return await call.debug_error_string()
465
+
466
+ async def wait_for_connection(self) -> None:
467
+ call = await self._interceptors_task
468
+ return await call.wait_for_connection()
469
+
470
+
471
+ class _InterceptedUnaryResponseMixin:
472
+ def __await__(self):
473
+ call = yield from self._interceptors_task.__await__()
474
+ response = yield from call.__await__()
475
+ return response
476
+
477
+
478
+ class _InterceptedStreamResponseMixin:
479
+ _response_aiter: Optional[AsyncIterable[ResponseType]]
480
+
481
+ def _init_stream_response_mixin(self) -> None:
482
+ # Is initialized later, otherwise if the iterator is not finally
483
+ # consumed a logging warning is emitted by Asyncio.
484
+ self._response_aiter = None
485
+
486
+ async def _wait_for_interceptor_task_response_iterator(
487
+ self,
488
+ ) -> ResponseType:
489
+ call = await self._interceptors_task
490
+ async for response in call:
491
+ yield response
492
+
493
+ def __aiter__(self) -> AsyncIterator[ResponseType]:
494
+ if self._response_aiter is None:
495
+ self._response_aiter = (
496
+ self._wait_for_interceptor_task_response_iterator()
497
+ )
498
+ return self._response_aiter
499
+
500
+ async def read(self) -> Union[EOFType, ResponseType]:
501
+ if self._response_aiter is None:
502
+ self._response_aiter = (
503
+ self._wait_for_interceptor_task_response_iterator()
504
+ )
505
+ try:
506
+ return await self._response_aiter.asend(None)
507
+ except StopAsyncIteration:
508
+ return cygrpc.EOF
509
+
510
+
511
+ class _InterceptedStreamRequestMixin:
512
+ _write_to_iterator_async_gen: Optional[AsyncIterable[RequestType]]
513
+ _write_to_iterator_queue: Optional[asyncio.Queue]
514
+ _status_code_task: Optional[asyncio.Task]
515
+
516
+ _FINISH_ITERATOR_SENTINEL = object()
517
+
518
+ def _init_stream_request_mixin(
519
+ self, request_iterator: Optional[RequestIterableType]
520
+ ) -> RequestIterableType:
521
+ if request_iterator is None:
522
+ # We provide our own request iterator which is a proxy
523
+ # of the futures writes that will be done by the caller.
524
+ self._write_to_iterator_queue = asyncio.Queue(maxsize=1)
525
+ self._write_to_iterator_async_gen = (
526
+ self._proxy_writes_as_request_iterator()
527
+ )
528
+ self._status_code_task = None
529
+ request_iterator = self._write_to_iterator_async_gen
530
+ else:
531
+ self._write_to_iterator_queue = None
532
+
533
+ return request_iterator
534
+
535
+ async def _proxy_writes_as_request_iterator(self):
536
+ await self._interceptors_task
537
+
538
+ while True:
539
+ value = await self._write_to_iterator_queue.get()
540
+ if (
541
+ value
542
+ is _InterceptedStreamRequestMixin._FINISH_ITERATOR_SENTINEL
543
+ ):
544
+ break
545
+ yield value
546
+
547
+ async def _write_to_iterator_queue_interruptible(
548
+ self,
549
+ request: RequestType,
550
+ call: _base_call.Call,
551
+ ):
552
+ # Write the specified 'request' to the request iterator queue using the
553
+ # specified 'call' to allow for interruption of the write in the case
554
+ # of abrupt termination of the call.
555
+ if self._status_code_task is None:
556
+ self._status_code_task = self._loop.create_task(call.code())
557
+
558
+ await asyncio.wait(
559
+ (
560
+ self._loop.create_task(
561
+ self._write_to_iterator_queue.put(request)
562
+ ),
563
+ self._status_code_task,
564
+ ),
565
+ return_when=asyncio.FIRST_COMPLETED,
566
+ )
567
+
568
+ async def write(self, request: RequestType) -> None:
569
+ # If no queue was created it means that requests
570
+ # should be expected through an iterators provided
571
+ # by the caller.
572
+ if self._write_to_iterator_queue is None:
573
+ raise cygrpc.UsageError(_API_STYLE_ERROR)
574
+
575
+ try:
576
+ call = await self._interceptors_task
577
+ except (asyncio.CancelledError, AioRpcError):
578
+ raise asyncio.InvalidStateError(_RPC_ALREADY_FINISHED_DETAILS)
579
+
580
+ if call.done():
581
+ raise asyncio.InvalidStateError(_RPC_ALREADY_FINISHED_DETAILS)
582
+ if call._done_writing_flag:
583
+ raise asyncio.InvalidStateError(_RPC_HALF_CLOSED_DETAILS)
584
+
585
+ await self._write_to_iterator_queue_interruptible(request, call)
586
+
587
+ if call.done():
588
+ raise asyncio.InvalidStateError(_RPC_ALREADY_FINISHED_DETAILS)
589
+
590
+ async def done_writing(self) -> None:
591
+ """Signal peer that client is done writing.
592
+
593
+ This method is idempotent.
594
+ """
595
+ # If no queue was created it means that requests
596
+ # should be expected through an iterators provided
597
+ # by the caller.
598
+ if self._write_to_iterator_queue is None:
599
+ raise cygrpc.UsageError(_API_STYLE_ERROR)
600
+
601
+ try:
602
+ call = await self._interceptors_task
603
+ except asyncio.CancelledError:
604
+ raise asyncio.InvalidStateError(_RPC_ALREADY_FINISHED_DETAILS)
605
+
606
+ await self._write_to_iterator_queue_interruptible(
607
+ _InterceptedStreamRequestMixin._FINISH_ITERATOR_SENTINEL, call
608
+ )
609
+
610
+
611
+ class InterceptedUnaryUnaryCall(
612
+ _InterceptedUnaryResponseMixin, InterceptedCall, _base_call.UnaryUnaryCall
613
+ ):
614
+ """Used for running a `UnaryUnaryCall` wrapped by interceptors.
615
+
616
+ For the `__await__` method is it is proxied to the intercepted call only when
617
+ the interceptor task is finished.
618
+ """
619
+
620
+ _loop: asyncio.AbstractEventLoop
621
+ _channel: cygrpc.AioChannel
622
+
623
+ # pylint: disable=too-many-arguments
624
+ def __init__(
625
+ self,
626
+ interceptors: Sequence[UnaryUnaryClientInterceptor],
627
+ request: RequestType,
628
+ timeout: Optional[float],
629
+ metadata: Metadata,
630
+ credentials: Optional[grpc.CallCredentials],
631
+ wait_for_ready: Optional[bool],
632
+ channel: cygrpc.AioChannel,
633
+ method: bytes,
634
+ request_serializer: Optional[SerializingFunction],
635
+ response_deserializer: Optional[DeserializingFunction],
636
+ loop: asyncio.AbstractEventLoop,
637
+ ) -> None:
638
+ self._loop = loop
639
+ self._channel = channel
640
+ interceptors_task = loop.create_task(
641
+ self._invoke(
642
+ interceptors,
643
+ method,
644
+ timeout,
645
+ metadata,
646
+ credentials,
647
+ wait_for_ready,
648
+ request,
649
+ request_serializer,
650
+ response_deserializer,
651
+ )
652
+ )
653
+ super().__init__(interceptors_task)
654
+
655
+ # pylint: disable=too-many-arguments
656
+ async def _invoke(
657
+ self,
658
+ interceptors: Sequence[UnaryUnaryClientInterceptor],
659
+ method: bytes,
660
+ timeout: Optional[float],
661
+ metadata: Optional[Metadata],
662
+ credentials: Optional[grpc.CallCredentials],
663
+ wait_for_ready: Optional[bool],
664
+ request: RequestType,
665
+ request_serializer: Optional[SerializingFunction],
666
+ response_deserializer: Optional[DeserializingFunction],
667
+ ) -> Union[UnaryUnaryCall, UnaryUnaryCallResponse]:
668
+ """Run the RPC call wrapped in interceptors"""
669
+
670
+ async def _run_interceptor(
671
+ interceptors: List[UnaryUnaryClientInterceptor],
672
+ client_call_details: ClientCallDetails,
673
+ request: RequestType,
674
+ ) -> Union[UnaryUnaryCall, UnaryUnaryCallResponse]:
675
+ if interceptors:
676
+ continuation = functools.partial(
677
+ _run_interceptor, interceptors[1:]
678
+ )
679
+ call_or_response = await interceptors[0].intercept_unary_unary(
680
+ continuation, client_call_details, request
681
+ )
682
+
683
+ if isinstance(call_or_response, _base_call.UnaryUnaryCall):
684
+ return call_or_response
685
+ return UnaryUnaryCallResponse(call_or_response)
686
+
687
+ return UnaryUnaryCall(
688
+ request,
689
+ _timeout_to_deadline(client_call_details.timeout),
690
+ client_call_details.metadata,
691
+ client_call_details.credentials,
692
+ client_call_details.wait_for_ready,
693
+ self._channel,
694
+ client_call_details.method,
695
+ request_serializer,
696
+ response_deserializer,
697
+ self._loop,
698
+ )
699
+
700
+ client_call_details = ClientCallDetails(
701
+ method, timeout, metadata, credentials, wait_for_ready
702
+ )
703
+ return await _run_interceptor(
704
+ list(interceptors), client_call_details, request
705
+ )
706
+
707
+ def time_remaining(self) -> Optional[float]:
708
+ raise NotImplementedError()
709
+
710
+
711
+ class InterceptedUnaryStreamCall(
712
+ _InterceptedStreamResponseMixin, InterceptedCall, _base_call.UnaryStreamCall
713
+ ):
714
+ """Used for running a `UnaryStreamCall` wrapped by interceptors."""
715
+
716
+ _loop: asyncio.AbstractEventLoop
717
+ _channel: cygrpc.AioChannel
718
+ _last_returned_call_from_interceptors = Optional[_base_call.UnaryStreamCall]
719
+
720
+ # pylint: disable=too-many-arguments
721
+ def __init__(
722
+ self,
723
+ interceptors: Sequence[UnaryStreamClientInterceptor],
724
+ request: RequestType,
725
+ timeout: Optional[float],
726
+ metadata: Metadata,
727
+ credentials: Optional[grpc.CallCredentials],
728
+ wait_for_ready: Optional[bool],
729
+ channel: cygrpc.AioChannel,
730
+ method: bytes,
731
+ request_serializer: Optional[SerializingFunction],
732
+ response_deserializer: Optional[DeserializingFunction],
733
+ loop: asyncio.AbstractEventLoop,
734
+ ) -> None:
735
+ self._loop = loop
736
+ self._channel = channel
737
+ self._init_stream_response_mixin()
738
+ self._last_returned_call_from_interceptors = None
739
+ interceptors_task = loop.create_task(
740
+ self._invoke(
741
+ interceptors,
742
+ method,
743
+ timeout,
744
+ metadata,
745
+ credentials,
746
+ wait_for_ready,
747
+ request,
748
+ request_serializer,
749
+ response_deserializer,
750
+ )
751
+ )
752
+ super().__init__(interceptors_task)
753
+
754
+ # pylint: disable=too-many-arguments
755
+ async def _invoke(
756
+ self,
757
+ interceptors: Sequence[UnaryStreamClientInterceptor],
758
+ method: bytes,
759
+ timeout: Optional[float],
760
+ metadata: Optional[Metadata],
761
+ credentials: Optional[grpc.CallCredentials],
762
+ wait_for_ready: Optional[bool],
763
+ request: RequestType,
764
+ request_serializer: Optional[SerializingFunction],
765
+ response_deserializer: Optional[DeserializingFunction],
766
+ ) -> Union[UnaryStreamCall, UnaryStreamCallResponseIterator]:
767
+ """Run the RPC call wrapped in interceptors"""
768
+
769
+ async def _run_interceptor(
770
+ interceptors: List[UnaryStreamClientInterceptor],
771
+ client_call_details: ClientCallDetails,
772
+ request: RequestType,
773
+ ) -> Union[UnaryStreamCall, UnaryStreamCallResponseIterator]:
774
+ if interceptors:
775
+ continuation = functools.partial(
776
+ _run_interceptor, interceptors[1:]
777
+ )
778
+
779
+ call_or_response_iterator = await interceptors[
780
+ 0
781
+ ].intercept_unary_stream(
782
+ continuation, client_call_details, request
783
+ )
784
+
785
+ if isinstance(
786
+ call_or_response_iterator, _base_call.UnaryStreamCall
787
+ ):
788
+ self._last_returned_call_from_interceptors = (
789
+ call_or_response_iterator
790
+ )
791
+ else:
792
+ self._last_returned_call_from_interceptors = (
793
+ UnaryStreamCallResponseIterator(
794
+ self._last_returned_call_from_interceptors,
795
+ call_or_response_iterator,
796
+ )
797
+ )
798
+ return self._last_returned_call_from_interceptors
799
+ self._last_returned_call_from_interceptors = UnaryStreamCall(
800
+ request,
801
+ _timeout_to_deadline(client_call_details.timeout),
802
+ client_call_details.metadata,
803
+ client_call_details.credentials,
804
+ client_call_details.wait_for_ready,
805
+ self._channel,
806
+ client_call_details.method,
807
+ request_serializer,
808
+ response_deserializer,
809
+ self._loop,
810
+ )
811
+
812
+ return self._last_returned_call_from_interceptors
813
+
814
+ client_call_details = ClientCallDetails(
815
+ method, timeout, metadata, credentials, wait_for_ready
816
+ )
817
+ return await _run_interceptor(
818
+ list(interceptors), client_call_details, request
819
+ )
820
+
821
+ def time_remaining(self) -> Optional[float]:
822
+ raise NotImplementedError()
823
+
824
+
825
+ class InterceptedStreamUnaryCall(
826
+ _InterceptedUnaryResponseMixin,
827
+ _InterceptedStreamRequestMixin,
828
+ InterceptedCall,
829
+ _base_call.StreamUnaryCall,
830
+ ):
831
+ """Used for running a `StreamUnaryCall` wrapped by interceptors.
832
+
833
+ For the `__await__` method is it is proxied to the intercepted call only when
834
+ the interceptor task is finished.
835
+ """
836
+
837
+ _loop: asyncio.AbstractEventLoop
838
+ _channel: cygrpc.AioChannel
839
+
840
+ # pylint: disable=too-many-arguments
841
+ def __init__(
842
+ self,
843
+ interceptors: Sequence[StreamUnaryClientInterceptor],
844
+ request_iterator: Optional[RequestIterableType],
845
+ timeout: Optional[float],
846
+ metadata: Metadata,
847
+ credentials: Optional[grpc.CallCredentials],
848
+ wait_for_ready: Optional[bool],
849
+ channel: cygrpc.AioChannel,
850
+ method: bytes,
851
+ request_serializer: Optional[SerializingFunction],
852
+ response_deserializer: Optional[DeserializingFunction],
853
+ loop: asyncio.AbstractEventLoop,
854
+ ) -> None:
855
+ self._loop = loop
856
+ self._channel = channel
857
+ request_iterator = self._init_stream_request_mixin(request_iterator)
858
+ interceptors_task = loop.create_task(
859
+ self._invoke(
860
+ interceptors,
861
+ method,
862
+ timeout,
863
+ metadata,
864
+ credentials,
865
+ wait_for_ready,
866
+ request_iterator,
867
+ request_serializer,
868
+ response_deserializer,
869
+ )
870
+ )
871
+ super().__init__(interceptors_task)
872
+
873
+ # pylint: disable=too-many-arguments
874
+ async def _invoke(
875
+ self,
876
+ interceptors: Sequence[StreamUnaryClientInterceptor],
877
+ method: bytes,
878
+ timeout: Optional[float],
879
+ metadata: Optional[Metadata],
880
+ credentials: Optional[grpc.CallCredentials],
881
+ wait_for_ready: Optional[bool],
882
+ request_iterator: RequestIterableType,
883
+ request_serializer: Optional[SerializingFunction],
884
+ response_deserializer: Optional[DeserializingFunction],
885
+ ) -> StreamUnaryCall:
886
+ """Run the RPC call wrapped in interceptors"""
887
+
888
+ async def _run_interceptor(
889
+ interceptors: Sequence[StreamUnaryClientInterceptor],
890
+ client_call_details: ClientCallDetails,
891
+ request_iterator: RequestIterableType,
892
+ ) -> _base_call.StreamUnaryCall:
893
+ if interceptors:
894
+ continuation = functools.partial(
895
+ _run_interceptor, interceptors[1:]
896
+ )
897
+
898
+ return await interceptors[0].intercept_stream_unary(
899
+ continuation, client_call_details, request_iterator
900
+ )
901
+ return StreamUnaryCall(
902
+ request_iterator,
903
+ _timeout_to_deadline(client_call_details.timeout),
904
+ client_call_details.metadata,
905
+ client_call_details.credentials,
906
+ client_call_details.wait_for_ready,
907
+ self._channel,
908
+ client_call_details.method,
909
+ request_serializer,
910
+ response_deserializer,
911
+ self._loop,
912
+ )
913
+
914
+ client_call_details = ClientCallDetails(
915
+ method, timeout, metadata, credentials, wait_for_ready
916
+ )
917
+ return await _run_interceptor(
918
+ list(interceptors), client_call_details, request_iterator
919
+ )
920
+
921
+ def time_remaining(self) -> Optional[float]:
922
+ raise NotImplementedError()
923
+
924
+
925
+ class InterceptedStreamStreamCall(
926
+ _InterceptedStreamResponseMixin,
927
+ _InterceptedStreamRequestMixin,
928
+ InterceptedCall,
929
+ _base_call.StreamStreamCall,
930
+ ):
931
+ """Used for running a `StreamStreamCall` wrapped by interceptors."""
932
+
933
+ _loop: asyncio.AbstractEventLoop
934
+ _channel: cygrpc.AioChannel
935
+ _last_returned_call_from_interceptors = Optional[
936
+ _base_call.StreamStreamCall
937
+ ]
938
+
939
+ # pylint: disable=too-many-arguments
940
+ def __init__(
941
+ self,
942
+ interceptors: Sequence[StreamStreamClientInterceptor],
943
+ request_iterator: Optional[RequestIterableType],
944
+ timeout: Optional[float],
945
+ metadata: Metadata,
946
+ credentials: Optional[grpc.CallCredentials],
947
+ wait_for_ready: Optional[bool],
948
+ channel: cygrpc.AioChannel,
949
+ method: bytes,
950
+ request_serializer: Optional[SerializingFunction],
951
+ response_deserializer: Optional[DeserializingFunction],
952
+ loop: asyncio.AbstractEventLoop,
953
+ ) -> None:
954
+ self._loop = loop
955
+ self._channel = channel
956
+ self._init_stream_response_mixin()
957
+ request_iterator = self._init_stream_request_mixin(request_iterator)
958
+ self._last_returned_call_from_interceptors = None
959
+ interceptors_task = loop.create_task(
960
+ self._invoke(
961
+ interceptors,
962
+ method,
963
+ timeout,
964
+ metadata,
965
+ credentials,
966
+ wait_for_ready,
967
+ request_iterator,
968
+ request_serializer,
969
+ response_deserializer,
970
+ )
971
+ )
972
+ super().__init__(interceptors_task)
973
+
974
+ # pylint: disable=too-many-arguments
975
+ async def _invoke(
976
+ self,
977
+ interceptors: Sequence[StreamStreamClientInterceptor],
978
+ method: bytes,
979
+ timeout: Optional[float],
980
+ metadata: Optional[Metadata],
981
+ credentials: Optional[grpc.CallCredentials],
982
+ wait_for_ready: Optional[bool],
983
+ request_iterator: RequestIterableType,
984
+ request_serializer: Optional[SerializingFunction],
985
+ response_deserializer: Optional[DeserializingFunction],
986
+ ) -> Union[StreamStreamCall, StreamStreamCallResponseIterator]:
987
+ """Run the RPC call wrapped in interceptors"""
988
+
989
+ async def _run_interceptor(
990
+ interceptors: List[StreamStreamClientInterceptor],
991
+ client_call_details: ClientCallDetails,
992
+ request_iterator: RequestIterableType,
993
+ ) -> Union[StreamStreamCall, StreamStreamCallResponseIterator]:
994
+ if interceptors:
995
+ continuation = functools.partial(
996
+ _run_interceptor, interceptors[1:]
997
+ )
998
+
999
+ call_or_response_iterator = await interceptors[
1000
+ 0
1001
+ ].intercept_stream_stream(
1002
+ continuation, client_call_details, request_iterator
1003
+ )
1004
+
1005
+ if isinstance(
1006
+ call_or_response_iterator, _base_call.StreamStreamCall
1007
+ ):
1008
+ self._last_returned_call_from_interceptors = (
1009
+ call_or_response_iterator
1010
+ )
1011
+ else:
1012
+ self._last_returned_call_from_interceptors = (
1013
+ StreamStreamCallResponseIterator(
1014
+ self._last_returned_call_from_interceptors,
1015
+ call_or_response_iterator,
1016
+ )
1017
+ )
1018
+ return self._last_returned_call_from_interceptors
1019
+ self._last_returned_call_from_interceptors = StreamStreamCall(
1020
+ request_iterator,
1021
+ _timeout_to_deadline(client_call_details.timeout),
1022
+ client_call_details.metadata,
1023
+ client_call_details.credentials,
1024
+ client_call_details.wait_for_ready,
1025
+ self._channel,
1026
+ client_call_details.method,
1027
+ request_serializer,
1028
+ response_deserializer,
1029
+ self._loop,
1030
+ )
1031
+ return self._last_returned_call_from_interceptors
1032
+
1033
+ client_call_details = ClientCallDetails(
1034
+ method, timeout, metadata, credentials, wait_for_ready
1035
+ )
1036
+ return await _run_interceptor(
1037
+ list(interceptors), client_call_details, request_iterator
1038
+ )
1039
+
1040
+ def time_remaining(self) -> Optional[float]:
1041
+ raise NotImplementedError()
1042
+
1043
+
1044
+ class UnaryUnaryCallResponse(_base_call.UnaryUnaryCall):
1045
+ """Final UnaryUnaryCall class finished with a response."""
1046
+
1047
+ _response: ResponseType
1048
+
1049
+ def __init__(self, response: ResponseType) -> None:
1050
+ self._response = response
1051
+
1052
+ def cancel(self) -> bool:
1053
+ return False
1054
+
1055
+ def cancelled(self) -> bool:
1056
+ return False
1057
+
1058
+ def done(self) -> bool:
1059
+ return True
1060
+
1061
+ def add_done_callback(self, unused_callback) -> None:
1062
+ raise NotImplementedError()
1063
+
1064
+ def time_remaining(self) -> Optional[float]:
1065
+ raise NotImplementedError()
1066
+
1067
+ async def initial_metadata(self) -> Optional[Metadata]:
1068
+ return None
1069
+
1070
+ async def trailing_metadata(self) -> Optional[Metadata]:
1071
+ return None
1072
+
1073
+ async def code(self) -> grpc.StatusCode:
1074
+ return grpc.StatusCode.OK
1075
+
1076
+ async def details(self) -> str:
1077
+ return ""
1078
+
1079
+ async def debug_error_string(self) -> Optional[str]:
1080
+ return None
1081
+
1082
+ def __await__(self):
1083
+ if False: # pylint: disable=using-constant-test
1084
+ # This code path is never used, but a yield statement is needed
1085
+ # for telling the interpreter that __await__ is a generator.
1086
+ yield None
1087
+ return self._response
1088
+
1089
+ async def wait_for_connection(self) -> None:
1090
+ pass
1091
+
1092
+
1093
+ class _StreamCallResponseIterator:
1094
+ _call: Union[_base_call.UnaryStreamCall, _base_call.StreamStreamCall]
1095
+ _response_iterator: AsyncIterable[ResponseType]
1096
+
1097
+ def __init__(
1098
+ self,
1099
+ call: Union[_base_call.UnaryStreamCall, _base_call.StreamStreamCall],
1100
+ response_iterator: AsyncIterable[ResponseType],
1101
+ ) -> None:
1102
+ self._response_iterator = response_iterator
1103
+ self._call = call
1104
+
1105
+ def cancel(self) -> bool:
1106
+ return self._call.cancel()
1107
+
1108
+ def cancelled(self) -> bool:
1109
+ return self._call.cancelled()
1110
+
1111
+ def done(self) -> bool:
1112
+ return self._call.done()
1113
+
1114
+ def add_done_callback(self, callback) -> None:
1115
+ self._call.add_done_callback(callback)
1116
+
1117
+ def time_remaining(self) -> Optional[float]:
1118
+ return self._call.time_remaining()
1119
+
1120
+ async def initial_metadata(self) -> Optional[Metadata]:
1121
+ return await self._call.initial_metadata()
1122
+
1123
+ async def trailing_metadata(self) -> Optional[Metadata]:
1124
+ return await self._call.trailing_metadata()
1125
+
1126
+ async def code(self) -> grpc.StatusCode:
1127
+ return await self._call.code()
1128
+
1129
+ async def details(self) -> str:
1130
+ return await self._call.details()
1131
+
1132
+ async def debug_error_string(self) -> Optional[str]:
1133
+ return await self._call.debug_error_string()
1134
+
1135
+ def __aiter__(self):
1136
+ return self._response_iterator.__aiter__()
1137
+
1138
+ async def wait_for_connection(self) -> None:
1139
+ return await self._call.wait_for_connection()
1140
+
1141
+
1142
+ class UnaryStreamCallResponseIterator(
1143
+ _StreamCallResponseIterator, _base_call.UnaryStreamCall
1144
+ ):
1145
+ """UnaryStreamCall class which uses an alternative response iterator."""
1146
+
1147
+ async def read(self) -> Union[EOFType, ResponseType]:
1148
+ # Behind the scenes everything goes through the
1149
+ # async iterator. So this path should not be reached.
1150
+ raise NotImplementedError()
1151
+
1152
+
1153
+ class StreamStreamCallResponseIterator(
1154
+ _StreamCallResponseIterator, _base_call.StreamStreamCall
1155
+ ):
1156
+ """StreamStreamCall class which uses an alternative response iterator."""
1157
+
1158
+ async def read(self) -> Union[EOFType, ResponseType]:
1159
+ # Behind the scenes everything goes through the
1160
+ # async iterator. So this path should not be reached.
1161
+ raise NotImplementedError()
1162
+
1163
+ async def write(self, request: RequestType) -> None:
1164
+ # Behind the scenes everything goes through the
1165
+ # async iterator provided by the InterceptedStreamStreamCall.
1166
+ # So this path should not be reached.
1167
+ raise NotImplementedError()
1168
+
1169
+ async def done_writing(self) -> None:
1170
+ # Behind the scenes everything goes through the
1171
+ # async iterator provided by the InterceptedStreamStreamCall.
1172
+ # So this path should not be reached.
1173
+ raise NotImplementedError()
1174
+
1175
+ @property
1176
+ def _done_writing_flag(self) -> bool:
1177
+ return self._call._done_writing_flag
loan-advisor-agent/.venv/Lib/site-packages/grpc/aio/_metadata.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 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
+ """Implementation of the metadata abstraction for gRPC Asyncio Python."""
15
+ from __future__ import annotations
16
+
17
+ from collections import OrderedDict
18
+ from collections.abc import Collection
19
+ from collections.abc import ItemsView
20
+ from collections.abc import Iterable
21
+ from collections.abc import Iterator
22
+ from collections.abc import KeysView
23
+ from collections.abc import Sequence
24
+ from collections.abc import ValuesView
25
+ from typing import Any, List, Optional, Tuple, Union
26
+
27
+ from typing_extensions import Self
28
+
29
+ MetadataKey = str
30
+ MetadataValue = Union[str, bytes]
31
+ MetadatumType = Tuple[MetadataKey, MetadataValue]
32
+ MetadataType = Union["Metadata", Sequence[MetadatumType]]
33
+
34
+
35
+ class Metadata(Collection): # noqa: PLW1641
36
+ """Metadata abstraction for the asynchronous calls and interceptors.
37
+
38
+ The metadata is a mapping from str -> List[str]
39
+
40
+ Traits
41
+ * Multiple entries are allowed for the same key
42
+ * The order of the values by key is preserved
43
+ * Getting by an element by key, retrieves the first mapped value
44
+ * Supports an immutable view of the data
45
+ * Allows partial mutation on the data without recreating the new object from scratch.
46
+ """
47
+
48
+ def __init__(self, *args: MetadatumType) -> None:
49
+ self._metadata = OrderedDict()
50
+ for md_key, md_value in args:
51
+ self.add(md_key, md_value)
52
+
53
+ @classmethod
54
+ def from_tuple(cls, raw_metadata: tuple):
55
+ # Note: We unintentionally support non-tuple arguments here. We plan
56
+ # to emit a DeprecationWarning when a non-tuple type is used.
57
+ if raw_metadata:
58
+ return cls(*raw_metadata)
59
+ return cls()
60
+
61
+ @classmethod
62
+ def _create(
63
+ cls,
64
+ raw_metadata: Union[None, Self, Iterable[MetadatumType]],
65
+ ) -> Self:
66
+ # TODO(asheshvidyut): Make this method public and encourage people to use it instead
67
+ # of `from_tuple` to create metadata from non-tuple types.
68
+ if raw_metadata is None:
69
+ return Metadata()
70
+ if isinstance(raw_metadata, cls):
71
+ return raw_metadata
72
+ if raw_metadata:
73
+ return cls(*raw_metadata)
74
+ return cls()
75
+
76
+ def add(self, key: MetadataKey, value: MetadataValue) -> None:
77
+ self._metadata.setdefault(key, [])
78
+ self._metadata[key].append(value)
79
+
80
+ def __len__(self) -> int:
81
+ """Return the total number of elements that there are in the metadata,
82
+ including multiple values for the same key.
83
+ """
84
+ return sum(map(len, self._metadata.values()))
85
+
86
+ def __getitem__(self, key: MetadataKey) -> MetadataValue:
87
+ """When calling <metadata>[<key>], the first element of all those
88
+ mapped for <key> is returned.
89
+ """
90
+ try:
91
+ return self._metadata[key][0]
92
+ except (ValueError, IndexError) as e:
93
+ error_msg = f"{key!r}"
94
+ raise KeyError(error_msg) from e
95
+
96
+ def __setitem__(self, key: MetadataKey, value: MetadataValue) -> None:
97
+ """Calling metadata[<key>] = <value>
98
+ Maps <value> to the first instance of <key>.
99
+ """
100
+ if key not in self:
101
+ self._metadata[key] = [value]
102
+ else:
103
+ current_values = self.get_all(key)
104
+ self._metadata[key] = [value, *current_values[1:]]
105
+
106
+ def __delitem__(self, key: MetadataKey) -> None:
107
+ """``del metadata[<key>]`` deletes the first mapping for <key>."""
108
+ current_values = self.get_all(key)
109
+ if not current_values:
110
+ raise KeyError(repr(key))
111
+ self._metadata[key] = current_values[1:]
112
+
113
+ def delete_all(self, key: MetadataKey) -> None:
114
+ """Delete all mappings for <key>."""
115
+ del self._metadata[key]
116
+
117
+ def __iter__(self) -> Iterator[Tuple[MetadataKey, MetadataValue]]:
118
+ for key, values in self._metadata.items():
119
+ for value in values:
120
+ yield (key, value)
121
+
122
+ def keys(self) -> KeysView:
123
+ return KeysView(self._metadata)
124
+
125
+ def values(self) -> ValuesView:
126
+ return ValuesView(self._metadata)
127
+
128
+ def items(self) -> ItemsView:
129
+ return ItemsView(self._metadata)
130
+
131
+ def get(
132
+ self, key: MetadataKey, default: Optional[MetadataValue] = None
133
+ ) -> Optional[MetadataValue]:
134
+ try:
135
+ return self[key]
136
+ except KeyError:
137
+ return default
138
+
139
+ def get_all(self, key: MetadataKey) -> List[MetadataValue]:
140
+ """For compatibility with other Metadata abstraction objects (like in Java),
141
+ this would return all items under the desired <key>.
142
+ """
143
+ return self._metadata.get(key, [])
144
+
145
+ def set_all(self, key: MetadataKey, values: List[MetadataValue]) -> None:
146
+ self._metadata[key] = values
147
+
148
+ def __contains__(self, key: MetadataKey) -> bool:
149
+ return key in self._metadata
150
+
151
+ def __eq__(self, other: object) -> bool:
152
+ if isinstance(other, self.__class__):
153
+ return self._metadata == other._metadata
154
+ if isinstance(other, tuple):
155
+ return tuple(self) == other
156
+ return NotImplemented # pytype: disable=bad-return-type
157
+
158
+ def __add__(self, other: Any) -> "Metadata":
159
+ if isinstance(other, self.__class__):
160
+ return Metadata(*(tuple(self) + tuple(other)))
161
+ if isinstance(other, tuple):
162
+ return Metadata(*(tuple(self) + other))
163
+ return NotImplemented # pytype: disable=bad-return-type
164
+
165
+ def __repr__(self) -> str:
166
+ view = tuple(self)
167
+ return "{0}({1!r})".format(self.__class__.__name__, view)