|
13 | 13 | # limitations under the License. |
14 | 14 |
|
15 | 15 | from collections import defaultdict |
| 16 | +import threading |
| 17 | + |
16 | 18 | from grpc_interceptor import ClientInterceptor |
17 | 19 | from google.api_core.exceptions import Aborted |
18 | 20 |
|
@@ -63,3 +65,67 @@ def reset(self): |
63 | 65 | self._method_to_abort = None |
64 | 66 | self._count = 0 |
65 | 67 | self._connection = None |
| 68 | + |
| 69 | + |
| 70 | +X_GOOG_REQUEST_ID = "x-goog-spanner-request-id" |
| 71 | + |
| 72 | + |
| 73 | +class XGoogRequestIDHeaderInterceptor(ClientInterceptor): |
| 74 | + def __init__(self): |
| 75 | + self._unary_req_segments = [] |
| 76 | + self._stream_req_segments = [] |
| 77 | + self.__lock = threading.Lock() |
| 78 | + |
| 79 | + def intercept(self, method, request_or_iterator, call_details): |
| 80 | + metadata = call_details.metadata |
| 81 | + x_goog_request_id = None |
| 82 | + for key, value in metadata: |
| 83 | + if key == X_GOOG_REQUEST_ID: |
| 84 | + x_goog_request_id = value |
| 85 | + break |
| 86 | + |
| 87 | + if not x_goog_request_id: |
| 88 | + raise Exception( |
| 89 | + f"Missing {X_GOOG_REQUEST_ID} header in {call_details.method}" |
| 90 | + ) |
| 91 | + |
| 92 | + response_or_iterator = method(request_or_iterator, call_details) |
| 93 | + streaming = getattr(response_or_iterator, "__iter__", None) is not None |
| 94 | + with self.__lock: |
| 95 | + if streaming: |
| 96 | + self._stream_req_segments.append( |
| 97 | + (call_details.method, parse_request_id(x_goog_request_id)) |
| 98 | + ) |
| 99 | + else: |
| 100 | + self._unary_req_segments.append( |
| 101 | + (call_details.method, parse_request_id(x_goog_request_id)) |
| 102 | + ) |
| 103 | + |
| 104 | + return response_or_iterator |
| 105 | + |
| 106 | + @property |
| 107 | + def unary_request_ids(self): |
| 108 | + return self._unary_req_segments |
| 109 | + |
| 110 | + @property |
| 111 | + def stream_request_ids(self): |
| 112 | + return self._stream_req_segments |
| 113 | + |
| 114 | + def reset(self): |
| 115 | + self._stream_req_segments.clear() |
| 116 | + self._unary_req_segments.clear() |
| 117 | + |
| 118 | + |
| 119 | +def parse_request_id(request_id_str): |
| 120 | + splits = request_id_str.split(".") |
| 121 | + version, rand_process_id, client_id, channel_id, nth_request, nth_attempt = list( |
| 122 | + map(lambda v: int(v), splits) |
| 123 | + ) |
| 124 | + return ( |
| 125 | + version, |
| 126 | + rand_process_id, |
| 127 | + client_id, |
| 128 | + channel_id, |
| 129 | + nth_request, |
| 130 | + nth_attempt, |
| 131 | + ) |
0 commit comments