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/__init__.py
ADDED
irimi/_aiohttp_patch.py
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import functools
|
|
5
|
+
import inspect
|
|
6
|
+
import weakref
|
|
7
|
+
from collections.abc import Awaitable, Callable
|
|
8
|
+
from types import ModuleType
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from irimi._aiohttp_serving import (
|
|
12
|
+
ParserSettings,
|
|
13
|
+
ServedRequest,
|
|
14
|
+
ServingParts,
|
|
15
|
+
find_serving_parts,
|
|
16
|
+
read_parser_settings,
|
|
17
|
+
serve_response,
|
|
18
|
+
)
|
|
19
|
+
from irimi._interception import Interception, OpenCall
|
|
20
|
+
from irimi._outbound_calls import Headers, OutboundCall, OutboundResponse
|
|
21
|
+
from irimi._response_recording import ResponseRecording, end_without_response
|
|
22
|
+
|
|
23
|
+
SWITCHING_PROTOCOLS = 101
|
|
24
|
+
INHERITED_ITERATORS = frozenset({"iter_chunked", "iter_any", "iter_chunks"})
|
|
25
|
+
FORWARDED_METHODS = (
|
|
26
|
+
"exception",
|
|
27
|
+
"set_exception",
|
|
28
|
+
"on_eof",
|
|
29
|
+
"feed_eof",
|
|
30
|
+
"feed_data",
|
|
31
|
+
"is_eof",
|
|
32
|
+
"at_eof",
|
|
33
|
+
"wait_eof",
|
|
34
|
+
"begin_http_chunk_receiving",
|
|
35
|
+
"end_http_chunk_receiving",
|
|
36
|
+
"get_read_buffer_limits",
|
|
37
|
+
"set_read_chunk_size",
|
|
38
|
+
)
|
|
39
|
+
FORWARDED_PROPERTIES = ("total_bytes", "total_compressed_bytes", "total_raw_bytes")
|
|
40
|
+
READS_OF_BYTES = ("read", "readany", "readexactly", "readline", "readuntil")
|
|
41
|
+
OWN_SLOTS = ("inner_reader", "recording")
|
|
42
|
+
|
|
43
|
+
Middleware = Callable[[Any, Callable[[Any], Awaitable[Any]]], Awaitable[Any]]
|
|
44
|
+
ChoosesMiddleware = Callable[[Any, dict[str, Any]], Middleware]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class _BodyRecording:
|
|
48
|
+
def __init__(self, inner_reader: Any, recording: ResponseRecording) -> None:
|
|
49
|
+
self._inner_reader = inner_reader
|
|
50
|
+
self._recording = recording
|
|
51
|
+
self._position = 0
|
|
52
|
+
self._copied_length = 0
|
|
53
|
+
self._failed_read: BaseException | None = None
|
|
54
|
+
|
|
55
|
+
def add_read(self, content: bytes) -> None:
|
|
56
|
+
self._failed_read = None
|
|
57
|
+
length_already_copied = self._copied_length - self._position
|
|
58
|
+
self._recording.add(content[length_already_copied:])
|
|
59
|
+
self._position += len(content)
|
|
60
|
+
self._copied_length = max(self._copied_length, self._position)
|
|
61
|
+
if self._inner_reader.at_eof():
|
|
62
|
+
self._end(error=None)
|
|
63
|
+
|
|
64
|
+
def add_failed_read(self, error: BaseException) -> None:
|
|
65
|
+
if isinstance(error, asyncio.IncompleteReadError):
|
|
66
|
+
self.add_read(error.partial)
|
|
67
|
+
return
|
|
68
|
+
self._failed_read = error
|
|
69
|
+
if self._inner_reader.exception() is not None:
|
|
70
|
+
self._end(error)
|
|
71
|
+
|
|
72
|
+
def step_back(self, length: int) -> None:
|
|
73
|
+
self._position -= length
|
|
74
|
+
|
|
75
|
+
def end_at_close(self) -> None:
|
|
76
|
+
self._end(self._failed_read)
|
|
77
|
+
|
|
78
|
+
def _end(self, error: BaseException | None) -> None:
|
|
79
|
+
reader = self._inner_reader
|
|
80
|
+
was_read_to_end = reader.at_eof() and self._copied_length == reader.total_bytes
|
|
81
|
+
self._recording.end(was_read_to_end=was_read_to_end, error=error)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def patch_aiohttp(library: ModuleType, interception: Interception) -> bool:
|
|
85
|
+
send_request = library.ClientSession._request
|
|
86
|
+
close_response = library.ClientResponse.close
|
|
87
|
+
release_response = library.ClientResponse.release
|
|
88
|
+
if "middlewares" not in inspect.signature(send_request).parameters:
|
|
89
|
+
return False
|
|
90
|
+
if not hasattr(library.BytesPayload, "as_bytes"):
|
|
91
|
+
return False
|
|
92
|
+
if not hasattr(library.StreamReader, "total_compressed_bytes"):
|
|
93
|
+
return False
|
|
94
|
+
reader_class = _build_recording_reader(library)
|
|
95
|
+
if reader_class is None:
|
|
96
|
+
return False
|
|
97
|
+
choose_middleware = _build_middleware_chooser(library, interception, reader_class)
|
|
98
|
+
if choose_middleware is None:
|
|
99
|
+
return False
|
|
100
|
+
library.ClientSession._request = _wrap_request(send_request, interception, choose_middleware)
|
|
101
|
+
library.ClientResponse.close = _wrap_close(close_response, interception, reader_class)
|
|
102
|
+
library.ClientResponse.release = _wrap_close(release_response, interception, reader_class)
|
|
103
|
+
return True
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _build_middleware_chooser(
|
|
107
|
+
library: ModuleType, interception: Interception, reader_class: type
|
|
108
|
+
) -> ChoosesMiddleware | None:
|
|
109
|
+
record_call = _build_recording_middleware(library, interception, reader_class)
|
|
110
|
+
if not interception.is_shadow:
|
|
111
|
+
|
|
112
|
+
def choose_recording(session: Any, options: dict[str, Any]) -> Middleware:
|
|
113
|
+
return record_call
|
|
114
|
+
|
|
115
|
+
return choose_recording
|
|
116
|
+
serving_parts = find_serving_parts(library)
|
|
117
|
+
if serving_parts is None:
|
|
118
|
+
return None
|
|
119
|
+
build_serving = _build_serving_middleware(library, interception, reader_class, serving_parts)
|
|
120
|
+
|
|
121
|
+
def choose_serving(session: Any, options: dict[str, Any]) -> Middleware:
|
|
122
|
+
return build_serving(read_parser_settings(serving_parts, session, options))
|
|
123
|
+
|
|
124
|
+
return choose_serving
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _wrap_request(
|
|
128
|
+
send_request: Callable[..., Awaitable[Any]],
|
|
129
|
+
interception: Interception,
|
|
130
|
+
choose_middleware: ChoosesMiddleware,
|
|
131
|
+
) -> Callable[..., Awaitable[Any]]:
|
|
132
|
+
@functools.wraps(send_request)
|
|
133
|
+
async def _request(session: Any, *arguments: Any, **options: Any) -> Any:
|
|
134
|
+
recorded_options = _add_middleware(session, options, choose_middleware, interception)
|
|
135
|
+
return await send_request(session, *arguments, **recorded_options)
|
|
136
|
+
|
|
137
|
+
return _request
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _add_middleware(
|
|
141
|
+
session: Any,
|
|
142
|
+
options: dict[str, Any],
|
|
143
|
+
choose_middleware: ChoosesMiddleware,
|
|
144
|
+
interception: Interception,
|
|
145
|
+
) -> dict[str, Any]:
|
|
146
|
+
try:
|
|
147
|
+
given_middlewares = options.get("middlewares")
|
|
148
|
+
middlewares = session._middlewares if given_middlewares is None else given_middlewares
|
|
149
|
+
record_call = choose_middleware(session, options)
|
|
150
|
+
return {**options, "middlewares": (*middlewares, record_call)}
|
|
151
|
+
except Exception:
|
|
152
|
+
if interception.is_shadow:
|
|
153
|
+
raise
|
|
154
|
+
interception.report_failure("record a call made through aiohttp")
|
|
155
|
+
return options
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _build_recording_middleware(
|
|
159
|
+
library: ModuleType, interception: Interception, reader_class: type
|
|
160
|
+
) -> Middleware:
|
|
161
|
+
async def record_call(request: Any, send_request: Callable[[Any], Awaitable[Any]]) -> Any:
|
|
162
|
+
open_call = await _begin_call(interception, request, library)
|
|
163
|
+
return await _send_and_record(interception, open_call, request, send_request, reader_class)
|
|
164
|
+
|
|
165
|
+
return record_call
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _build_serving_middleware(
|
|
169
|
+
library: ModuleType,
|
|
170
|
+
interception: Interception,
|
|
171
|
+
reader_class: type,
|
|
172
|
+
serving_parts: ServingParts,
|
|
173
|
+
) -> Callable[[ParserSettings], Middleware]:
|
|
174
|
+
def build_middleware(settings: ParserSettings) -> Middleware:
|
|
175
|
+
async def serve_or_record_call(
|
|
176
|
+
request: Any, send_request: Callable[[Any], Awaitable[Any]]
|
|
177
|
+
) -> Any:
|
|
178
|
+
open_call = await _begin_call(interception, request, library)
|
|
179
|
+
if open_call is not None and open_call.served_response is not None:
|
|
180
|
+
return serve_response(
|
|
181
|
+
serving_parts,
|
|
182
|
+
interception,
|
|
183
|
+
open_call,
|
|
184
|
+
open_call.served_response,
|
|
185
|
+
ServedRequest(request, settings),
|
|
186
|
+
)
|
|
187
|
+
return await _send_and_record(
|
|
188
|
+
interception, open_call, request, send_request, reader_class
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
return serve_or_record_call
|
|
192
|
+
|
|
193
|
+
return build_middleware
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
async def _send_and_record(
|
|
197
|
+
interception: Interception,
|
|
198
|
+
open_call: OpenCall | None,
|
|
199
|
+
request: Any,
|
|
200
|
+
send_request: Callable[[Any], Awaitable[Any]],
|
|
201
|
+
reader_class: type,
|
|
202
|
+
) -> Any:
|
|
203
|
+
try:
|
|
204
|
+
response = await send_request(request)
|
|
205
|
+
except BaseException as error:
|
|
206
|
+
end_without_response(interception, open_call, error)
|
|
207
|
+
raise
|
|
208
|
+
_record_response(interception, open_call, response, reader_class)
|
|
209
|
+
return response
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
async def _begin_call(
|
|
213
|
+
interception: Interception, request: Any, library: ModuleType
|
|
214
|
+
) -> OpenCall | None:
|
|
215
|
+
try:
|
|
216
|
+
call = await _translate_request(request, library)
|
|
217
|
+
except Exception:
|
|
218
|
+
return interception.begin_unreadable()
|
|
219
|
+
return interception.begin(call)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
async def _translate_request(request: Any, library: ModuleType) -> OutboundCall:
|
|
223
|
+
payload = request.body
|
|
224
|
+
is_held_in_memory = isinstance(payload, library.BytesPayload) and not request.compress
|
|
225
|
+
in_memory_body = bytes(await payload.as_bytes()) if is_held_in_memory else b""
|
|
226
|
+
return OutboundCall(
|
|
227
|
+
method=str(request.method),
|
|
228
|
+
url=str(request.url),
|
|
229
|
+
headers=tuple((str(name), str(value)) for name, value in request.headers.items()),
|
|
230
|
+
body=in_memory_body or None,
|
|
231
|
+
has_streamed_body=bool(payload) and not is_held_in_memory,
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _record_response(
|
|
236
|
+
interception: Interception, open_call: OpenCall | None, response: Any, reader_class: type
|
|
237
|
+
) -> None:
|
|
238
|
+
if open_call is None:
|
|
239
|
+
return
|
|
240
|
+
try:
|
|
241
|
+
content = response.content
|
|
242
|
+
has_body_to_read = int(response.status) != SWITCHING_PROTOCOLS and not content.at_eof()
|
|
243
|
+
translated = OutboundResponse(
|
|
244
|
+
status=int(response.status),
|
|
245
|
+
headers=_decode_headers(response.raw_headers),
|
|
246
|
+
is_body_decoded=has_body_to_read and content.total_compressed_bytes is not None,
|
|
247
|
+
)
|
|
248
|
+
recording = ResponseRecording(interception, open_call, translated)
|
|
249
|
+
if has_body_to_read:
|
|
250
|
+
response.content = reader_class(content, _BodyRecording(content, recording))
|
|
251
|
+
if interception.is_shadow:
|
|
252
|
+
weakref.finalize(response, recording.end, was_read_to_end=False, error=None)
|
|
253
|
+
else:
|
|
254
|
+
recording.end(was_read_to_end=True, error=None)
|
|
255
|
+
except Exception:
|
|
256
|
+
interception.release_live_call(open_call)
|
|
257
|
+
interception.report_failure("record an outbound response")
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _wrap_close(
|
|
261
|
+
close_response: Callable[..., Any], interception: Interception, reader_class: type
|
|
262
|
+
) -> Callable[..., Any]:
|
|
263
|
+
@functools.wraps(close_response)
|
|
264
|
+
def close(response: Any, *arguments: Any, **options: Any) -> Any:
|
|
265
|
+
_end_at_close(response, interception, reader_class)
|
|
266
|
+
return close_response(response, *arguments, **options)
|
|
267
|
+
|
|
268
|
+
return close
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _end_at_close(response: Any, interception: Interception, reader_class: type[Any]) -> None:
|
|
272
|
+
try:
|
|
273
|
+
content = response.content
|
|
274
|
+
if isinstance(content, reader_class):
|
|
275
|
+
content.recording.end_at_close()
|
|
276
|
+
except Exception:
|
|
277
|
+
interception.report_failure("record the end of an outbound response")
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _decode_headers(raw_headers: Any) -> Headers:
|
|
281
|
+
return tuple((name.decode("latin-1"), value.decode("latin-1")) for name, value in raw_headers)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _build_recording_reader(library: ModuleType) -> type | None:
|
|
285
|
+
forwarded_methods = [name for name in FORWARDED_METHODS if hasattr(library.StreamReader, name)]
|
|
286
|
+
members: dict[str, Any] = {
|
|
287
|
+
"__slots__": OWN_SLOTS,
|
|
288
|
+
"__init__": _hold_reader,
|
|
289
|
+
"__repr__": _describe_reader,
|
|
290
|
+
"__getattr__": _get_from_inner_reader,
|
|
291
|
+
"__setattr__": _set_on_inner_reader,
|
|
292
|
+
"unread_data": _unread_data,
|
|
293
|
+
"readchunk": _read_http_chunk,
|
|
294
|
+
"read_nowait": _read_without_waiting,
|
|
295
|
+
**{name: _forward_method(name) for name in forwarded_methods},
|
|
296
|
+
**{name: _forward_property(name) for name in FORWARDED_PROPERTIES},
|
|
297
|
+
**{name: _copy_read(name) for name in READS_OF_BYTES},
|
|
298
|
+
}
|
|
299
|
+
public_names = {name for name in vars(library.StreamReader) if not name.startswith("_")}
|
|
300
|
+
if not public_names <= members.keys() | INHERITED_ITERATORS:
|
|
301
|
+
return None
|
|
302
|
+
return type("RecordingStreamReader", (library.StreamReader,), members)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _hold_reader(reader: Any, inner_reader: Any, recording: _BodyRecording) -> None:
|
|
306
|
+
object.__setattr__(reader, "inner_reader", inner_reader)
|
|
307
|
+
object.__setattr__(reader, "recording", recording)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _describe_reader(reader: Any) -> str:
|
|
311
|
+
return repr(reader.inner_reader)
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _get_from_inner_reader(reader: Any, name: str) -> Any:
|
|
315
|
+
return getattr(object.__getattribute__(reader, "inner_reader"), name)
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _set_on_inner_reader(reader: Any, name: str, value: Any) -> None:
|
|
319
|
+
if name in OWN_SLOTS:
|
|
320
|
+
object.__setattr__(reader, name, value)
|
|
321
|
+
return
|
|
322
|
+
setattr(reader.inner_reader, name, value)
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _forward_method(name: str) -> Callable[..., Any]:
|
|
326
|
+
def forward(reader: Any, *arguments: Any, **options: Any) -> Any:
|
|
327
|
+
return getattr(reader.inner_reader, name)(*arguments, **options)
|
|
328
|
+
|
|
329
|
+
return forward
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _forward_property(name: str) -> property:
|
|
333
|
+
return property(lambda reader: getattr(reader.inner_reader, name))
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _unread_data(reader: Any, data: bytes) -> None:
|
|
337
|
+
reader.inner_reader.unread_data(data)
|
|
338
|
+
reader.recording.step_back(len(data))
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def _copy_read(name: str) -> Callable[..., Awaitable[bytes]]:
|
|
342
|
+
async def read(reader: Any, *arguments: Any, **options: Any) -> bytes:
|
|
343
|
+
try:
|
|
344
|
+
content: bytes = await getattr(reader.inner_reader, name)(*arguments, **options)
|
|
345
|
+
except BaseException as error:
|
|
346
|
+
reader.recording.add_failed_read(error)
|
|
347
|
+
raise
|
|
348
|
+
reader.recording.add_read(content)
|
|
349
|
+
return content
|
|
350
|
+
|
|
351
|
+
return read
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
async def _read_http_chunk(reader: Any) -> tuple[bytes, bool]:
|
|
355
|
+
try:
|
|
356
|
+
http_chunk: tuple[bytes, bool] = await reader.inner_reader.readchunk()
|
|
357
|
+
except BaseException as error:
|
|
358
|
+
reader.recording.add_failed_read(error)
|
|
359
|
+
raise
|
|
360
|
+
reader.recording.add_read(http_chunk[0])
|
|
361
|
+
return http_chunk
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _read_without_waiting(reader: Any, *arguments: Any, **options: Any) -> bytes:
|
|
365
|
+
try:
|
|
366
|
+
content: bytes = reader.inner_reader.read_nowait(*arguments, **options)
|
|
367
|
+
except BaseException as error:
|
|
368
|
+
reader.recording.add_failed_read(error)
|
|
369
|
+
raise
|
|
370
|
+
reader.recording.add_read(content)
|
|
371
|
+
return content
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import inspect
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from types import ModuleType
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from irimi._interception import Interception, OpenCall
|
|
10
|
+
from irimi._recorded_calls import RecordedResponse
|
|
11
|
+
from irimi._response_recording import serve_built_response
|
|
12
|
+
from irimi._status_reasons import find_reason
|
|
13
|
+
|
|
14
|
+
LARGEST_PARSER_BUFFER_LIMIT = 2**31 - 1
|
|
15
|
+
RESPONSE_PARAMETERS = (
|
|
16
|
+
"method",
|
|
17
|
+
"url",
|
|
18
|
+
"writer",
|
|
19
|
+
"continue100",
|
|
20
|
+
"timer",
|
|
21
|
+
"request_info",
|
|
22
|
+
"traces",
|
|
23
|
+
"loop",
|
|
24
|
+
"session",
|
|
25
|
+
"stream_writer",
|
|
26
|
+
)
|
|
27
|
+
RESPONSE_ATTRIBUTES_SET_FROM_A_MESSAGE = ("_headers", "_raw_headers")
|
|
28
|
+
PARSER_LIMITS = ("max_line_size", "max_field_size", "max_headers")
|
|
29
|
+
TRIAL_RESPONSE = RecordedResponse(200, (("content-length", "2"),), b"{}")
|
|
30
|
+
LINE_BREAKS = ("\r", "\n")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class ServingParts:
|
|
35
|
+
response_parser: Any
|
|
36
|
+
stream_writer: Any
|
|
37
|
+
protocol: Any
|
|
38
|
+
methods_without_a_body: frozenset[str]
|
|
39
|
+
limit_names: tuple[str, ...]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class ParserSettings:
|
|
44
|
+
is_decompressing: bool
|
|
45
|
+
limits: tuple[tuple[str, int], ...]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class ServedRequest:
|
|
50
|
+
request: Any
|
|
51
|
+
settings: ParserSettings
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def find_serving_parts(library: ModuleType) -> ServingParts | None:
|
|
55
|
+
try:
|
|
56
|
+
parts = ServingParts(
|
|
57
|
+
response_parser=library.http.HttpResponseParser,
|
|
58
|
+
stream_writer=library.http.StreamWriter,
|
|
59
|
+
protocol=library.base_protocol.BaseProtocol,
|
|
60
|
+
methods_without_a_body=frozenset(library.helpers.EMPTY_BODY_METHODS),
|
|
61
|
+
limit_names=_find_limit_names(library.ClientSession),
|
|
62
|
+
)
|
|
63
|
+
except (AttributeError, TypeError, ValueError):
|
|
64
|
+
return None
|
|
65
|
+
if not _builds_responses_as_expected(library.ClientResponse):
|
|
66
|
+
return None
|
|
67
|
+
if not isinstance(getattr(library.ClientSession, "auto_decompress", None), property):
|
|
68
|
+
return None
|
|
69
|
+
if not _parses_as_expected(parts, library.ClientSession):
|
|
70
|
+
return None
|
|
71
|
+
return parts
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def read_parser_settings(
|
|
75
|
+
parts: ServingParts, session: Any, options: dict[str, Any]
|
|
76
|
+
) -> ParserSettings:
|
|
77
|
+
return ParserSettings(
|
|
78
|
+
is_decompressing=bool(_given_or(options.get("auto_decompress"), session.auto_decompress)),
|
|
79
|
+
limits=tuple(
|
|
80
|
+
(name, int(_given_or(options.get(name), getattr(session, f"_{name}"))))
|
|
81
|
+
for name in parts.limit_names
|
|
82
|
+
),
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _given_or(given: Any, session_default: Any) -> Any:
|
|
87
|
+
return session_default if given is None else given
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _find_limit_names(session_class: Any) -> tuple[str, ...]:
|
|
91
|
+
request_options = inspect.signature(session_class._request).parameters
|
|
92
|
+
session_attributes: frozenset[str] = getattr(session_class, "ATTRS", frozenset())
|
|
93
|
+
return tuple(
|
|
94
|
+
name
|
|
95
|
+
for name in PARSER_LIMITS
|
|
96
|
+
if name in request_options and f"_{name}" in session_attributes
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _builds_responses_as_expected(response_class: Any) -> bool:
|
|
101
|
+
if tuple(inspect.signature(response_class).parameters) != RESPONSE_PARAMETERS:
|
|
102
|
+
return False
|
|
103
|
+
return all(name in vars(response_class) for name in RESPONSE_ATTRIBUTES_SET_FROM_A_MESSAGE)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _parses_as_expected(parts: ServingParts, session_class: Any) -> bool:
|
|
107
|
+
loop = asyncio.new_event_loop()
|
|
108
|
+
try:
|
|
109
|
+
session_defaults = inspect.signature(session_class).parameters
|
|
110
|
+
settings = ParserSettings(
|
|
111
|
+
is_decompressing=True,
|
|
112
|
+
limits=tuple((name, session_defaults[name].default) for name in parts.limit_names),
|
|
113
|
+
)
|
|
114
|
+
message, content = _parse_response(
|
|
115
|
+
parts, parts.protocol(loop), loop, TRIAL_RESPONSE, has_body=True, settings=settings
|
|
116
|
+
)
|
|
117
|
+
return bool(
|
|
118
|
+
message.code == TRIAL_RESPONSE.status
|
|
119
|
+
and message.raw_headers
|
|
120
|
+
and message.headers.get("content-length") == "2"
|
|
121
|
+
and content.read_nowait() == TRIAL_RESPONSE.body
|
|
122
|
+
)
|
|
123
|
+
except Exception:
|
|
124
|
+
return False
|
|
125
|
+
finally:
|
|
126
|
+
loop.close()
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def serve_response(
|
|
130
|
+
parts: ServingParts,
|
|
131
|
+
interception: Interception,
|
|
132
|
+
open_call: OpenCall,
|
|
133
|
+
served: RecordedResponse,
|
|
134
|
+
served_request: ServedRequest,
|
|
135
|
+
) -> Any:
|
|
136
|
+
return serve_built_response(
|
|
137
|
+
interception, open_call, lambda: _build_response(parts, served, served_request)
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _build_response(
|
|
142
|
+
parts: ServingParts, served: RecordedResponse, served_request: ServedRequest
|
|
143
|
+
) -> Any:
|
|
144
|
+
request = served_request.request
|
|
145
|
+
protocol = parts.protocol(request.loop)
|
|
146
|
+
message, content = _parse_response(
|
|
147
|
+
parts,
|
|
148
|
+
protocol,
|
|
149
|
+
request.loop,
|
|
150
|
+
served,
|
|
151
|
+
has_body=request.method not in parts.methods_without_a_body,
|
|
152
|
+
settings=served_request.settings,
|
|
153
|
+
)
|
|
154
|
+
response = request.response_class(
|
|
155
|
+
request.method,
|
|
156
|
+
request.original_url,
|
|
157
|
+
writer=None,
|
|
158
|
+
continue100=None,
|
|
159
|
+
timer=None,
|
|
160
|
+
request_info=request.request_info,
|
|
161
|
+
traces=[],
|
|
162
|
+
loop=request.loop,
|
|
163
|
+
session=request.session,
|
|
164
|
+
stream_writer=parts.stream_writer(protocol, request.loop),
|
|
165
|
+
)
|
|
166
|
+
response.version = message.version
|
|
167
|
+
response.status = message.code
|
|
168
|
+
response.reason = message.reason
|
|
169
|
+
response._headers = message.headers
|
|
170
|
+
response._raw_headers = message.raw_headers
|
|
171
|
+
response.content = content
|
|
172
|
+
return response
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _parse_response(
|
|
176
|
+
parts: ServingParts,
|
|
177
|
+
protocol: Any,
|
|
178
|
+
loop: Any,
|
|
179
|
+
served: RecordedResponse,
|
|
180
|
+
has_body: bool,
|
|
181
|
+
settings: ParserSettings,
|
|
182
|
+
) -> tuple[Any, Any]:
|
|
183
|
+
parser = parts.response_parser(
|
|
184
|
+
protocol,
|
|
185
|
+
loop,
|
|
186
|
+
LARGEST_PARSER_BUFFER_LIMIT,
|
|
187
|
+
response_with_body=has_body,
|
|
188
|
+
auto_decompress=settings.is_decompressing,
|
|
189
|
+
**dict(settings.limits),
|
|
190
|
+
)
|
|
191
|
+
messages, _, _ = parser.feed_data(_write_response(served, has_body))
|
|
192
|
+
[(message, content)] = messages
|
|
193
|
+
return message, content
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _write_response(served: RecordedResponse, has_body: bool) -> bytes:
|
|
197
|
+
status_line = f"HTTP/1.1 {served.status} {find_reason(served.status) or ''}\r\n"
|
|
198
|
+
header_lines = b"".join(
|
|
199
|
+
_write_header_line(name, value)
|
|
200
|
+
for name, value in served.headers
|
|
201
|
+
if not _has_line_break(name) and not _has_line_break(value)
|
|
202
|
+
)
|
|
203
|
+
head = status_line.encode("ascii") + header_lines + b"\r\n"
|
|
204
|
+
return head + served.body if has_body else head
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _has_line_break(text: str) -> bool:
|
|
208
|
+
return any(line_break in text for line_break in LINE_BREAKS)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _write_header_line(name: str, value: str) -> bytes:
|
|
212
|
+
line = f"{name}: {value}\r\n"
|
|
213
|
+
try:
|
|
214
|
+
return line.encode("latin-1")
|
|
215
|
+
except UnicodeEncodeError:
|
|
216
|
+
return line.encode("utf-8", "surrogateescape")
|
irimi/_atomic_total.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import io
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class AtomicTotal:
|
|
7
|
+
def __init__(self) -> None:
|
|
8
|
+
self._cursor = io.BytesIO()
|
|
9
|
+
|
|
10
|
+
def add(self, amount: int) -> int:
|
|
11
|
+
return self._cursor.seek(amount, io.SEEK_CUR)
|
|
12
|
+
|
|
13
|
+
def read(self) -> int:
|
|
14
|
+
return self._cursor.tell()
|
irimi/_bodies.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import codecs
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
from irimi._wire import JsonValue, field_names
|
|
8
|
+
|
|
9
|
+
BODY_LIMIT = 4 * 1024 * 1024
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class CopiedBody:
|
|
14
|
+
content: bytes
|
|
15
|
+
is_truncated: bool
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class BodyCopy:
|
|
19
|
+
def __init__(self) -> None:
|
|
20
|
+
self._content = bytearray()
|
|
21
|
+
self._is_truncated = False
|
|
22
|
+
|
|
23
|
+
def add(self, chunk: bytes) -> None:
|
|
24
|
+
room = BODY_LIMIT - len(self._content)
|
|
25
|
+
if len(chunk) > room:
|
|
26
|
+
self._is_truncated = True
|
|
27
|
+
self._content += chunk[:room]
|
|
28
|
+
|
|
29
|
+
def take(self) -> CopiedBody:
|
|
30
|
+
return CopiedBody(content=bytes(self._content), is_truncated=self._is_truncated)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def copy_body(content: bytes) -> CopiedBody:
|
|
34
|
+
body_copy = BodyCopy()
|
|
35
|
+
body_copy.add(content)
|
|
36
|
+
return body_copy.take()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def describe_body(
|
|
40
|
+
body: CopiedBody, content_type: str | None, content_encoding: str | None, is_whole: bool
|
|
41
|
+
) -> dict[str, JsonValue]:
|
|
42
|
+
description = _encode(body.content, is_cut=body.is_truncated or not is_whole)
|
|
43
|
+
if content_type is not None:
|
|
44
|
+
description[field_names.CONTENT_TYPE] = content_type
|
|
45
|
+
if content_encoding is not None and content_encoding.lower() != "identity":
|
|
46
|
+
description[field_names.CONTENT_ENCODING] = content_encoding
|
|
47
|
+
return description
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _encode(content: bytes, is_cut: bool) -> dict[str, JsonValue]:
|
|
51
|
+
try:
|
|
52
|
+
return {
|
|
53
|
+
field_names.ENCODING: field_names.TEXT,
|
|
54
|
+
field_names.DATA: _decode_text(content, is_cut),
|
|
55
|
+
}
|
|
56
|
+
except UnicodeDecodeError:
|
|
57
|
+
return {
|
|
58
|
+
field_names.ENCODING: field_names.BASE64,
|
|
59
|
+
field_names.DATA: base64.b64encode(content).decode("ascii"),
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _decode_text(content: bytes, is_cut: bool) -> str:
|
|
64
|
+
return codecs.getincrementaldecoder("utf-8")().decode(content, final=not is_cut)
|