irimi-sdk 0.2.0.dev0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- irimi/__init__.py +4 -0
- irimi/_aiohttp_patch.py +371 -0
- irimi/_aiohttp_serving.py +216 -0
- irimi/_atomic_total.py +14 -0
- irimi/_bodies.py +64 -0
- irimi/_credential_headers.py +52 -0
- irimi/_decorators.py +236 -0
- irimi/_delivery.py +70 -0
- irimi/_divergence.py +60 -0
- irimi/_drops.py +24 -0
- irimi/_errors.py +14 -0
- irimi/_exporter.py +193 -0
- irimi/_function_answers.py +87 -0
- irimi/_git.py +37 -0
- irimi/_httpx_patch.py +236 -0
- irimi/_interception.py +174 -0
- irimi/_labeled_calls.py +116 -0
- irimi/_llm_providers.py +57 -0
- irimi/_object_fields.py +32 -0
- irimi/_outbound_calls.py +190 -0
- irimi/_patching.py +58 -0
- irimi/_rebuilding.py +97 -0
- irimi/_recorded_calls.py +231 -0
- irimi/_recording.py +122 -0
- irimi/_recording_loader.py +63 -0
- irimi/_replay_child.py +156 -0
- irimi/_replay_decisions.py +120 -0
- irimi/_replay_fields.py +16 -0
- irimi/_replay_proxy.py +328 -0
- irimi/_replay_refusals.py +5 -0
- irimi/_response_recording.py +74 -0
- irimi/_sdk.py +318 -0
- irimi/_serialisation.py +114 -0
- irimi/_status_reasons.py +10 -0
- irimi/_unpatched_clients.py +105 -0
- irimi/_url_credentials.py +11 -0
- irimi/_urllib3_patch.py +465 -0
- irimi/_urllib3_serving.py +81 -0
- irimi/_wire/__init__.py +56 -0
- irimi/_wire/call_roles.py +32 -0
- irimi/_wire/events.py +209 -0
- irimi/_wire/field_names.py +80 -0
- irimi/_wire/json_value.py +3 -0
- irimi/_wire/markers.py +49 -0
- irimi/py.typed +0 -0
- irimi_sdk-0.2.0.dev0.dist-info/METADATA +81 -0
- irimi_sdk-0.2.0.dev0.dist-info/RECORD +48 -0
- irimi_sdk-0.2.0.dev0.dist-info/WHEEL +4 -0
irimi/_urllib3_patch.py
ADDED
|
@@ -0,0 +1,465 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import functools
|
|
4
|
+
import inspect
|
|
5
|
+
import threading
|
|
6
|
+
import weakref
|
|
7
|
+
from collections.abc import Callable, Iterator
|
|
8
|
+
from types import GeneratorType, ModuleType
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from irimi._bodies import BODY_LIMIT
|
|
12
|
+
from irimi._interception import Interception, OpenCall
|
|
13
|
+
from irimi._outbound_calls import (
|
|
14
|
+
DEFAULT_PORTS,
|
|
15
|
+
CallOutcome,
|
|
16
|
+
Headers,
|
|
17
|
+
OutboundCall,
|
|
18
|
+
OutboundResponse,
|
|
19
|
+
)
|
|
20
|
+
from irimi._response_recording import ResponseRecording, end_without_response
|
|
21
|
+
from irimi._urllib3_serving import (
|
|
22
|
+
ResponseOptions,
|
|
23
|
+
prepare_deferred_proxy,
|
|
24
|
+
serve_response,
|
|
25
|
+
wrap_prepare_proxy,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
FOLLOWED_RESPONSE_ATTRIBUTE = "_irimi_followed_response"
|
|
29
|
+
LEADING_REQUEST_PARAMETERS = ("self", "conn", "method", "url")
|
|
30
|
+
RECORDED_REQUEST_PARAMETERS = ("body", "headers")
|
|
31
|
+
SERVING_PARAMETERS = ("retries", "response_conn", "preload_content", "decode_content")
|
|
32
|
+
PROXY_POOL_CLASSES = ("HTTPConnectionPool", "HTTPSConnectionPool")
|
|
33
|
+
POOL_METHODS_SERVING_USES = ("_raise_timeout", "_put_conn")
|
|
34
|
+
RESPONSE_METHODS = ("_raw_read", "_handle_chunk", "read_chunked", "close")
|
|
35
|
+
LONGEST_BODY_TAKEN = BODY_LIMIT + 1
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def patch_urllib3(library: ModuleType, interception: Interception) -> bool:
|
|
39
|
+
pool_class: Any = getattr(library, "HTTPConnectionPool", None)
|
|
40
|
+
connection_class: Any = getattr(pool_class, "ConnectionCls", None)
|
|
41
|
+
response_class: Any = getattr(library, "HTTPResponse", None)
|
|
42
|
+
is_shadow = interception.is_shadow
|
|
43
|
+
if not _sends_one_request(getattr(pool_class, "_make_request", None), is_shadow):
|
|
44
|
+
return False
|
|
45
|
+
if is_shadow and not _serves_as_expected(library, pool_class):
|
|
46
|
+
return False
|
|
47
|
+
if not callable(getattr(connection_class, "getresponse", None)):
|
|
48
|
+
return False
|
|
49
|
+
if not _reads_a_body_as_expected(response_class):
|
|
50
|
+
return False
|
|
51
|
+
following = _ResponseFollowing(interception)
|
|
52
|
+
make_request = _wrap_make_request(library, interception, following)
|
|
53
|
+
response_methods = {
|
|
54
|
+
"_raw_read": _wrap_raw_read(response_class._raw_read, following),
|
|
55
|
+
"_handle_chunk": _wrap_handle_chunk(response_class._handle_chunk, following),
|
|
56
|
+
"read_chunked": _wrap_read_chunked(response_class.read_chunked, following),
|
|
57
|
+
"close": _wrap_close(response_class.close, following),
|
|
58
|
+
}
|
|
59
|
+
pool_class._make_request = make_request
|
|
60
|
+
for proxy_pool_class in _find_proxy_pool_classes(library):
|
|
61
|
+
proxy_pool_class._prepare_proxy = wrap_prepare_proxy(
|
|
62
|
+
proxy_pool_class._prepare_proxy, interception
|
|
63
|
+
)
|
|
64
|
+
connection_class.getresponse = _wrap_get_response(connection_class.getresponse, following)
|
|
65
|
+
for name, method in response_methods.items():
|
|
66
|
+
setattr(response_class, name, method)
|
|
67
|
+
return True
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _sends_one_request(make_request: object, is_shadow: bool) -> bool:
|
|
71
|
+
if not callable(make_request):
|
|
72
|
+
return False
|
|
73
|
+
parameters = tuple(inspect.signature(make_request).parameters)
|
|
74
|
+
needed = {*RECORDED_REQUEST_PARAMETERS, *(SERVING_PARAMETERS if is_shadow else ())}
|
|
75
|
+
return parameters[:4] == LEADING_REQUEST_PARAMETERS and set(parameters) >= needed
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _serves_as_expected(library: ModuleType, pool_class: object) -> bool:
|
|
79
|
+
if "_prepare_proxy" not in vars(pool_class):
|
|
80
|
+
return False
|
|
81
|
+
if not all(callable(getattr(pool_class, name, None)) for name in POOL_METHODS_SERVING_USES):
|
|
82
|
+
return False
|
|
83
|
+
return isinstance(_find_ssl_error(library), type)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _find_proxy_pool_classes(library: ModuleType) -> list[Any]:
|
|
87
|
+
found = (getattr(library, name, None) for name in PROXY_POOL_CLASSES)
|
|
88
|
+
return [
|
|
89
|
+
pool_class
|
|
90
|
+
for pool_class in found
|
|
91
|
+
if pool_class is not None and "_prepare_proxy" in vars(pool_class)
|
|
92
|
+
]
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _find_ssl_error(library: ModuleType) -> object:
|
|
96
|
+
return getattr(getattr(library, "connectionpool", None), "BaseSSLError", None)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _reads_a_body_as_expected(response_class: object) -> bool:
|
|
100
|
+
if not all(callable(getattr(response_class, name, None)) for name in RESPONSE_METHODS):
|
|
101
|
+
return False
|
|
102
|
+
return inspect.isgeneratorfunction(getattr(response_class, "read_chunked", None))
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class _Attempt:
|
|
106
|
+
def __init__(self, open_call: OpenCall, connection: Any) -> None:
|
|
107
|
+
self.open_call = open_call
|
|
108
|
+
self.connection = connection
|
|
109
|
+
self.socket: Any = None
|
|
110
|
+
self.recording: ResponseRecording | None = None
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class _FollowedResponse:
|
|
114
|
+
def __init__(self, recording: ResponseRecording) -> None:
|
|
115
|
+
self.recording = recording
|
|
116
|
+
self.has_unrecorded_content = False
|
|
117
|
+
self.chunked_reader: GeneratorType[bytes, None, None] | None = None
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class _ResponseFollowing:
|
|
121
|
+
def __init__(self, interception: Interception) -> None:
|
|
122
|
+
self._interception = interception
|
|
123
|
+
self._waiting = threading.local()
|
|
124
|
+
|
|
125
|
+
def swap_waiting_attempt(self, attempt: _Attempt | None) -> _Attempt | None:
|
|
126
|
+
previous_attempt: _Attempt | None = getattr(self._waiting, "attempt", None)
|
|
127
|
+
self._waiting.attempt = attempt
|
|
128
|
+
return previous_attempt
|
|
129
|
+
|
|
130
|
+
def find(self, response: Any) -> _FollowedResponse | None:
|
|
131
|
+
followed: _FollowedResponse | None = vars(response).get(FOLLOWED_RESPONSE_ATTRIBUTE)
|
|
132
|
+
if followed is not None:
|
|
133
|
+
return followed
|
|
134
|
+
attempt: _Attempt | None = getattr(self._waiting, "attempt", None)
|
|
135
|
+
if attempt is None or not _reads_from_socket(response, attempt.socket):
|
|
136
|
+
return None
|
|
137
|
+
return self._claim(attempt, response)
|
|
138
|
+
|
|
139
|
+
def remember_socket_awaiting_response(self, connection: Any) -> None:
|
|
140
|
+
attempt: _Attempt | None = getattr(self._waiting, "attempt", None)
|
|
141
|
+
if attempt is not None and attempt.connection is connection:
|
|
142
|
+
attempt.socket = getattr(connection, "sock", None)
|
|
143
|
+
|
|
144
|
+
def follow_returned_response(
|
|
145
|
+
self, attempt: _Attempt, response: Any, response_class: type
|
|
146
|
+
) -> None:
|
|
147
|
+
can_be_followed = isinstance(response, response_class)
|
|
148
|
+
if not can_be_followed:
|
|
149
|
+
self._end_without_a_body(attempt, response)
|
|
150
|
+
return
|
|
151
|
+
followed = vars(response).get(FOLLOWED_RESPONSE_ATTRIBUTE) or self._claim_after_reads(
|
|
152
|
+
attempt, response
|
|
153
|
+
)
|
|
154
|
+
if followed is None:
|
|
155
|
+
return
|
|
156
|
+
try:
|
|
157
|
+
if response.isclosed() or response.length_remaining == 0:
|
|
158
|
+
_end_finished_response(followed)
|
|
159
|
+
except Exception:
|
|
160
|
+
self._interception.report_failure("record an outbound response")
|
|
161
|
+
|
|
162
|
+
def end_failed_attempt(self, attempt: _Attempt, error: BaseException) -> None:
|
|
163
|
+
if attempt.recording is not None:
|
|
164
|
+
attempt.recording.end(was_read_to_end=False, error=error)
|
|
165
|
+
return
|
|
166
|
+
end_without_response(self._interception, attempt.open_call, error)
|
|
167
|
+
|
|
168
|
+
def record_read(self, followed: _FollowedResponse, response: Any, content: bytes) -> None:
|
|
169
|
+
try:
|
|
170
|
+
if content:
|
|
171
|
+
followed.recording.add(content)
|
|
172
|
+
if response.isclosed():
|
|
173
|
+
_end_finished_response(followed)
|
|
174
|
+
except Exception:
|
|
175
|
+
self._interception.report_failure("record an outbound response")
|
|
176
|
+
|
|
177
|
+
def end_stopped_read(
|
|
178
|
+
self, followed: _FollowedResponse, response: Any, error: BaseException | None
|
|
179
|
+
) -> None:
|
|
180
|
+
try:
|
|
181
|
+
if response.isclosed():
|
|
182
|
+
followed.recording.end(was_read_to_end=False, error=error)
|
|
183
|
+
except Exception:
|
|
184
|
+
self._interception.report_failure("record an outbound response")
|
|
185
|
+
|
|
186
|
+
def end_closed_response(self, response: Any) -> None:
|
|
187
|
+
try:
|
|
188
|
+
followed: _FollowedResponse | None = vars(response).get(FOLLOWED_RESPONSE_ATTRIBUTE)
|
|
189
|
+
if followed is None or _is_reading_chunks(followed):
|
|
190
|
+
return
|
|
191
|
+
followed.recording.end(was_read_to_end=False, error=None)
|
|
192
|
+
except Exception:
|
|
193
|
+
self._interception.report_failure("record an outbound response")
|
|
194
|
+
|
|
195
|
+
def _claim(self, attempt: _Attempt, response: Any) -> _FollowedResponse | None:
|
|
196
|
+
if attempt.recording is not None:
|
|
197
|
+
return None
|
|
198
|
+
try:
|
|
199
|
+
recording = ResponseRecording(
|
|
200
|
+
self._interception, attempt.open_call, _translate_response(response)
|
|
201
|
+
)
|
|
202
|
+
followed = _FollowedResponse(recording)
|
|
203
|
+
weakref.finalize(response, recording.end, was_read_to_end=False, error=None)
|
|
204
|
+
vars(response)[FOLLOWED_RESPONSE_ATTRIBUTE] = followed
|
|
205
|
+
attempt.recording = recording
|
|
206
|
+
except Exception:
|
|
207
|
+
self._interception.release_live_call(attempt.open_call)
|
|
208
|
+
self._interception.report_failure("record an outbound response")
|
|
209
|
+
return None
|
|
210
|
+
return followed
|
|
211
|
+
|
|
212
|
+
def _claim_after_reads(self, attempt: _Attempt, response: Any) -> _FollowedResponse | None:
|
|
213
|
+
followed = self._claim(attempt, response)
|
|
214
|
+
if followed is None:
|
|
215
|
+
return None
|
|
216
|
+
try:
|
|
217
|
+
followed.has_unrecorded_content = response.tell() > 0
|
|
218
|
+
except Exception:
|
|
219
|
+
followed.has_unrecorded_content = True
|
|
220
|
+
self._interception.report_failure("record an outbound response")
|
|
221
|
+
return followed
|
|
222
|
+
|
|
223
|
+
def _end_without_a_body(self, attempt: _Attempt, response: Any) -> None:
|
|
224
|
+
try:
|
|
225
|
+
outcome = CallOutcome(
|
|
226
|
+
response=_translate_response(response),
|
|
227
|
+
body=None,
|
|
228
|
+
was_read_to_end=False,
|
|
229
|
+
error=None,
|
|
230
|
+
)
|
|
231
|
+
except Exception:
|
|
232
|
+
self._interception.release_live_call(attempt.open_call)
|
|
233
|
+
self._interception.report_failure("record an outbound response")
|
|
234
|
+
return
|
|
235
|
+
self._interception.end(attempt.open_call, outcome)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _is_reading_chunks(followed: _FollowedResponse) -> bool:
|
|
239
|
+
return followed.chunked_reader is not None and followed.chunked_reader.gi_running
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _end_finished_response(followed: _FollowedResponse) -> None:
|
|
243
|
+
followed.recording.end(was_read_to_end=not followed.has_unrecorded_content, error=None)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _reads_from_socket(response: Any, socket: Any) -> bool:
|
|
247
|
+
try:
|
|
248
|
+
return bool(response.fileno() == socket.fileno())
|
|
249
|
+
except Exception:
|
|
250
|
+
return False
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _wrap_make_request(
|
|
254
|
+
library: ModuleType, interception: Interception, following: _ResponseFollowing
|
|
255
|
+
) -> Callable[..., Any]:
|
|
256
|
+
send_request = library.HTTPConnectionPool._make_request
|
|
257
|
+
response_class = library.HTTPResponse
|
|
258
|
+
skipped_header_value = library.util.SKIP_HEADER
|
|
259
|
+
ssl_error: Any = _find_ssl_error(library)
|
|
260
|
+
parameters = _Parameters(list(inspect.signature(send_request).parameters.values())[4:])
|
|
261
|
+
|
|
262
|
+
@functools.wraps(send_request)
|
|
263
|
+
def _make_request(
|
|
264
|
+
pool: Any, conn: Any, method: Any, url: Any, *arguments: Any, **options: Any
|
|
265
|
+
) -> Any:
|
|
266
|
+
open_call = _begin_call(
|
|
267
|
+
interception,
|
|
268
|
+
pool,
|
|
269
|
+
method,
|
|
270
|
+
url,
|
|
271
|
+
parameters.find_argument("body", arguments, options),
|
|
272
|
+
parameters.find_argument("headers", arguments, options),
|
|
273
|
+
skipped_header_value,
|
|
274
|
+
)
|
|
275
|
+
if open_call is None:
|
|
276
|
+
return send_request(pool, conn, method, url, *arguments, **options)
|
|
277
|
+
if open_call.served_response is not None:
|
|
278
|
+
response_options = ResponseOptions(
|
|
279
|
+
pool=pool,
|
|
280
|
+
method=method,
|
|
281
|
+
url=url,
|
|
282
|
+
retries=parameters.find_argument("retries", arguments, options),
|
|
283
|
+
response_connection=parameters.find_argument("response_conn", arguments, options),
|
|
284
|
+
preload_content=parameters.find_argument("preload_content", arguments, options),
|
|
285
|
+
decode_content=parameters.find_argument("decode_content", arguments, options),
|
|
286
|
+
)
|
|
287
|
+
return serve_response(
|
|
288
|
+
library, interception, open_call, open_call.served_response, response_options
|
|
289
|
+
)
|
|
290
|
+
attempt = _Attempt(open_call, conn)
|
|
291
|
+
outer_attempt = following.swap_waiting_attempt(attempt)
|
|
292
|
+
try:
|
|
293
|
+
if interception.is_shadow:
|
|
294
|
+
prepare_deferred_proxy(pool, conn, ssl_error)
|
|
295
|
+
response = send_request(pool, conn, method, url, *arguments, **options)
|
|
296
|
+
except BaseException as error:
|
|
297
|
+
following.end_failed_attempt(attempt, error)
|
|
298
|
+
raise
|
|
299
|
+
finally:
|
|
300
|
+
following.swap_waiting_attempt(outer_attempt)
|
|
301
|
+
following.follow_returned_response(attempt, response, response_class)
|
|
302
|
+
return response
|
|
303
|
+
|
|
304
|
+
return _make_request
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _wrap_get_response(
|
|
308
|
+
get_response: Callable[..., Any], following: _ResponseFollowing
|
|
309
|
+
) -> Callable[..., Any]:
|
|
310
|
+
@functools.wraps(get_response)
|
|
311
|
+
def getresponse(connection: Any, *arguments: Any, **options: Any) -> Any:
|
|
312
|
+
following.remember_socket_awaiting_response(connection)
|
|
313
|
+
return get_response(connection, *arguments, **options)
|
|
314
|
+
|
|
315
|
+
return getresponse
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _wrap_raw_read(read: Callable[..., Any], following: _ResponseFollowing) -> Callable[..., Any]:
|
|
319
|
+
@functools.wraps(read)
|
|
320
|
+
def _raw_read(response: Any, *arguments: Any, **options: Any) -> Any:
|
|
321
|
+
followed = following.find(response)
|
|
322
|
+
if followed is None:
|
|
323
|
+
return read(response, *arguments, **options)
|
|
324
|
+
try:
|
|
325
|
+
content = read(response, *arguments, **options)
|
|
326
|
+
except BaseException as error:
|
|
327
|
+
following.end_stopped_read(followed, response, error)
|
|
328
|
+
raise
|
|
329
|
+
following.record_read(followed, response, content)
|
|
330
|
+
return content
|
|
331
|
+
|
|
332
|
+
return _raw_read
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _wrap_handle_chunk(
|
|
336
|
+
read_chunk: Callable[..., Any], following: _ResponseFollowing
|
|
337
|
+
) -> Callable[..., Any]:
|
|
338
|
+
@functools.wraps(read_chunk)
|
|
339
|
+
def _handle_chunk(response: Any, *arguments: Any, **options: Any) -> Any:
|
|
340
|
+
followed = following.find(response)
|
|
341
|
+
chunk = read_chunk(response, *arguments, **options)
|
|
342
|
+
if followed is not None and chunk:
|
|
343
|
+
followed.recording.add(chunk)
|
|
344
|
+
return chunk
|
|
345
|
+
|
|
346
|
+
return _handle_chunk
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _wrap_read_chunked(
|
|
350
|
+
read_chunks: Callable[..., GeneratorType[bytes, None, None]], following: _ResponseFollowing
|
|
351
|
+
) -> Callable[..., Iterator[bytes]]:
|
|
352
|
+
@functools.wraps(read_chunks)
|
|
353
|
+
def read_chunked(response: Any, *arguments: Any, **options: Any) -> Iterator[bytes]:
|
|
354
|
+
followed = following.find(response)
|
|
355
|
+
reader = read_chunks(response, *arguments, **options)
|
|
356
|
+
if followed is None:
|
|
357
|
+
yield from reader
|
|
358
|
+
return
|
|
359
|
+
followed.chunked_reader = reader
|
|
360
|
+
try:
|
|
361
|
+
yield from reader
|
|
362
|
+
except GeneratorExit:
|
|
363
|
+
following.end_stopped_read(followed, response, None)
|
|
364
|
+
raise
|
|
365
|
+
except BaseException as error:
|
|
366
|
+
following.end_stopped_read(followed, response, error)
|
|
367
|
+
raise
|
|
368
|
+
following.record_read(followed, response, b"")
|
|
369
|
+
|
|
370
|
+
return read_chunked
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _wrap_close(
|
|
374
|
+
close_response: Callable[..., Any], following: _ResponseFollowing
|
|
375
|
+
) -> Callable[..., Any]:
|
|
376
|
+
@functools.wraps(close_response)
|
|
377
|
+
def close(response: Any, *arguments: Any, **options: Any) -> None:
|
|
378
|
+
try:
|
|
379
|
+
following.end_closed_response(response)
|
|
380
|
+
finally:
|
|
381
|
+
close_response(response, *arguments, **options)
|
|
382
|
+
|
|
383
|
+
return close
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _begin_call(
|
|
387
|
+
interception: Interception,
|
|
388
|
+
pool: Any,
|
|
389
|
+
method: Any,
|
|
390
|
+
target: Any,
|
|
391
|
+
body: Any,
|
|
392
|
+
headers: Any,
|
|
393
|
+
skipped_header_value: object,
|
|
394
|
+
) -> OpenCall | None:
|
|
395
|
+
try:
|
|
396
|
+
in_memory_body = _find_in_memory_body(body) if interception.is_inside_workflow() else b""
|
|
397
|
+
call = OutboundCall(
|
|
398
|
+
method=str(method),
|
|
399
|
+
url=_build_url(str(pool.scheme), str(pool.host), pool.port, str(target)),
|
|
400
|
+
headers=_translate_request_headers(headers, skipped_header_value),
|
|
401
|
+
body=in_memory_body or None,
|
|
402
|
+
has_streamed_body=in_memory_body is None,
|
|
403
|
+
)
|
|
404
|
+
except Exception:
|
|
405
|
+
return interception.begin_unreadable()
|
|
406
|
+
return interception.begin(call)
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _build_url(scheme: str, host: str, port: int | None, target: str) -> str:
|
|
410
|
+
if not target.startswith("/"):
|
|
411
|
+
return target
|
|
412
|
+
bracketed_host = f"[{host}]" if ":" in host else host
|
|
413
|
+
shown_port = "" if port is None or port == DEFAULT_PORTS.get(scheme) else f":{port}"
|
|
414
|
+
return f"{scheme}://{bracketed_host}{shown_port}{target}"
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
class _Parameters:
|
|
418
|
+
def __init__(self, parameters: list[inspect.Parameter]) -> None:
|
|
419
|
+
self._positions = {parameter.name: index for index, parameter in enumerate(parameters)}
|
|
420
|
+
self._defaults = {parameter.name: parameter.default for parameter in parameters}
|
|
421
|
+
|
|
422
|
+
def find_argument(self, name: str, arguments: tuple[Any, ...], options: dict[str, Any]) -> Any:
|
|
423
|
+
if name in options:
|
|
424
|
+
return options[name]
|
|
425
|
+
position = self._positions[name]
|
|
426
|
+
return arguments[position] if position < len(arguments) else self._defaults[name]
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def _find_in_memory_body(body: Any) -> bytes | None:
|
|
430
|
+
if body is None:
|
|
431
|
+
return b""
|
|
432
|
+
if isinstance(body, bytes):
|
|
433
|
+
return body
|
|
434
|
+
if isinstance(body, str):
|
|
435
|
+
return body[:LONGEST_BODY_TAKEN].encode()
|
|
436
|
+
if hasattr(body, "read"):
|
|
437
|
+
return None
|
|
438
|
+
try:
|
|
439
|
+
return bytes(memoryview(body).cast("B")[:LONGEST_BODY_TAKEN])
|
|
440
|
+
except TypeError:
|
|
441
|
+
return None
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def _translate_request_headers(headers: Any, skipped_header_value: object) -> Headers:
|
|
445
|
+
if headers is None:
|
|
446
|
+
return ()
|
|
447
|
+
return tuple(
|
|
448
|
+
(_decode_header_part(name), _decode_header_part(value))
|
|
449
|
+
for name, value in headers.items()
|
|
450
|
+
if value != skipped_header_value
|
|
451
|
+
)
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def _translate_response(response: Any) -> OutboundResponse:
|
|
455
|
+
return OutboundResponse(
|
|
456
|
+
status=int(response.status),
|
|
457
|
+
headers=tuple(
|
|
458
|
+
(_decode_header_part(name), _decode_header_part(value))
|
|
459
|
+
for name, value in response.headers.items()
|
|
460
|
+
),
|
|
461
|
+
)
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def _decode_header_part(part: Any) -> str:
|
|
465
|
+
return part.decode("latin-1") if isinstance(part, bytes) else str(part)
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import functools
|
|
4
|
+
import io
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from types import ModuleType
|
|
8
|
+
from typing import Any, Protocol
|
|
9
|
+
|
|
10
|
+
from irimi._interception import Interception, OpenCall
|
|
11
|
+
from irimi._recorded_calls import RecordedResponse
|
|
12
|
+
from irimi._response_recording import serve_built_response
|
|
13
|
+
from irimi._status_reasons import find_reason
|
|
14
|
+
|
|
15
|
+
DEFERRED_PROXY_ATTRIBUTE = "_irimi_deferred_proxy_preparation"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ConnectionPool(Protocol):
|
|
19
|
+
def _put_conn(self, conn: object) -> None: ...
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class ResponseOptions:
|
|
24
|
+
pool: ConnectionPool
|
|
25
|
+
method: str
|
|
26
|
+
url: str
|
|
27
|
+
retries: object
|
|
28
|
+
response_connection: object | None
|
|
29
|
+
preload_content: bool
|
|
30
|
+
decode_content: bool
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def wrap_prepare_proxy(
|
|
34
|
+
prepare: Callable[..., Any], interception: Interception
|
|
35
|
+
) -> Callable[..., Any]:
|
|
36
|
+
@functools.wraps(prepare)
|
|
37
|
+
def _prepare_proxy(pool: Any, connection: Any) -> Any:
|
|
38
|
+
if not interception.is_shadow:
|
|
39
|
+
return prepare(pool, connection)
|
|
40
|
+
vars(connection)[DEFERRED_PROXY_ATTRIBUTE] = prepare
|
|
41
|
+
return None
|
|
42
|
+
|
|
43
|
+
return _prepare_proxy
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def prepare_deferred_proxy(pool: Any, connection: Any, ssl_error: type[BaseException]) -> None:
|
|
47
|
+
prepare: Callable[..., Any] | None = vars(connection).pop(DEFERRED_PROXY_ATTRIBUTE, None)
|
|
48
|
+
if prepare is None:
|
|
49
|
+
return
|
|
50
|
+
try:
|
|
51
|
+
prepare(pool, connection)
|
|
52
|
+
except (ssl_error, OSError) as error:
|
|
53
|
+
pool._raise_timeout(err=error, url=pool.proxy.url, timeout_value=connection.timeout)
|
|
54
|
+
raise
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def serve_response(
|
|
58
|
+
library: ModuleType,
|
|
59
|
+
interception: Interception,
|
|
60
|
+
open_call: OpenCall,
|
|
61
|
+
served: RecordedResponse,
|
|
62
|
+
options: ResponseOptions,
|
|
63
|
+
) -> Any:
|
|
64
|
+
def build_response() -> Any:
|
|
65
|
+
response = library.HTTPResponse(
|
|
66
|
+
body=io.BytesIO(served.body),
|
|
67
|
+
headers=served.headers,
|
|
68
|
+
status=served.status,
|
|
69
|
+
reason=find_reason(served.status),
|
|
70
|
+
preload_content=options.preload_content,
|
|
71
|
+
decode_content=options.decode_content,
|
|
72
|
+
pool=options.pool,
|
|
73
|
+
retries=options.retries,
|
|
74
|
+
request_method=options.method,
|
|
75
|
+
request_url=options.url,
|
|
76
|
+
)
|
|
77
|
+
if options.response_connection is not None:
|
|
78
|
+
options.pool._put_conn(options.response_connection)
|
|
79
|
+
return response
|
|
80
|
+
|
|
81
|
+
return serve_built_response(interception, open_call, build_response)
|
irimi/_wire/__init__.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
from irimi._wire.events import (
|
|
2
|
+
EVENTS_PATH,
|
|
3
|
+
RUN_EVENTS_PATH,
|
|
4
|
+
WIRE_VERSION,
|
|
5
|
+
Batch,
|
|
6
|
+
EndEvent,
|
|
7
|
+
Event,
|
|
8
|
+
ParsedBatch,
|
|
9
|
+
RefusedEvent,
|
|
10
|
+
StartEvent,
|
|
11
|
+
WireFormatError,
|
|
12
|
+
parse_batch,
|
|
13
|
+
parse_event,
|
|
14
|
+
parse_refused_events,
|
|
15
|
+
write_batch,
|
|
16
|
+
write_event,
|
|
17
|
+
write_refused_events,
|
|
18
|
+
)
|
|
19
|
+
from irimi._wire.field_names import Flag, write_flags
|
|
20
|
+
from irimi._wire.json_value import JsonValue
|
|
21
|
+
from irimi._wire.markers import (
|
|
22
|
+
escape_reserved_key,
|
|
23
|
+
escape_reserved_keys,
|
|
24
|
+
mark_object,
|
|
25
|
+
mark_redacted,
|
|
26
|
+
mark_unserialisable,
|
|
27
|
+
unescape_reserved_keys,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"EVENTS_PATH",
|
|
32
|
+
"RUN_EVENTS_PATH",
|
|
33
|
+
"WIRE_VERSION",
|
|
34
|
+
"Batch",
|
|
35
|
+
"EndEvent",
|
|
36
|
+
"Event",
|
|
37
|
+
"Flag",
|
|
38
|
+
"JsonValue",
|
|
39
|
+
"ParsedBatch",
|
|
40
|
+
"RefusedEvent",
|
|
41
|
+
"StartEvent",
|
|
42
|
+
"WireFormatError",
|
|
43
|
+
"escape_reserved_key",
|
|
44
|
+
"escape_reserved_keys",
|
|
45
|
+
"mark_object",
|
|
46
|
+
"mark_redacted",
|
|
47
|
+
"mark_unserialisable",
|
|
48
|
+
"parse_batch",
|
|
49
|
+
"parse_event",
|
|
50
|
+
"parse_refused_events",
|
|
51
|
+
"unescape_reserved_keys",
|
|
52
|
+
"write_batch",
|
|
53
|
+
"write_event",
|
|
54
|
+
"write_flags",
|
|
55
|
+
"write_refused_events",
|
|
56
|
+
]
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from typing import Literal
|
|
5
|
+
|
|
6
|
+
from irimi._wire import field_names
|
|
7
|
+
from irimi._wire.json_value import JsonValue
|
|
8
|
+
|
|
9
|
+
CallRole = Literal["plain", "write_function", "read_function", "llm", "http_read", "http_write"]
|
|
10
|
+
|
|
11
|
+
READ_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
|
|
12
|
+
FUNCTION_KINDS = frozenset({"function", "workflow"})
|
|
13
|
+
WRITE_ROLES: frozenset[CallRole] = frozenset({"http_write", "write_function"})
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def classify_call(kind: str, start_fields: Mapping[str, JsonValue]) -> CallRole:
|
|
17
|
+
if kind == "llm":
|
|
18
|
+
return "llm"
|
|
19
|
+
if kind == "http":
|
|
20
|
+
request = start_fields.get(field_names.REQUEST)
|
|
21
|
+
method = request.get(field_names.METHOD) if isinstance(request, dict) else None
|
|
22
|
+
return "http_read" if method in READ_METHODS else "http_write"
|
|
23
|
+
if kind in FUNCTION_KINDS:
|
|
24
|
+
if start_fields.get(field_names.WRITE) is True:
|
|
25
|
+
return "write_function"
|
|
26
|
+
if start_fields.get(field_names.READ) is True:
|
|
27
|
+
return "read_function"
|
|
28
|
+
return "plain"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def is_write_role(role: CallRole) -> bool:
|
|
32
|
+
return role in WRITE_ROLES
|