irimi-sdk 0.2.0__tar.gz
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_sdk-0.2.0/PKG-INFO +82 -0
- irimi_sdk-0.2.0/README.md +67 -0
- irimi_sdk-0.2.0/pyproject.toml +26 -0
- irimi_sdk-0.2.0/pyproject.toml.orig +26 -0
- irimi_sdk-0.2.0/src/irimi/__init__.py +4 -0
- irimi_sdk-0.2.0/src/irimi/_aiohttp_patch.py +371 -0
- irimi_sdk-0.2.0/src/irimi/_aiohttp_serving.py +216 -0
- irimi_sdk-0.2.0/src/irimi/_atomic_total.py +14 -0
- irimi_sdk-0.2.0/src/irimi/_bodies.py +64 -0
- irimi_sdk-0.2.0/src/irimi/_credential_headers.py +52 -0
- irimi_sdk-0.2.0/src/irimi/_decorators.py +236 -0
- irimi_sdk-0.2.0/src/irimi/_delivery.py +118 -0
- irimi_sdk-0.2.0/src/irimi/_divergence.py +60 -0
- irimi_sdk-0.2.0/src/irimi/_drops.py +24 -0
- irimi_sdk-0.2.0/src/irimi/_errors.py +14 -0
- irimi_sdk-0.2.0/src/irimi/_exporter.py +193 -0
- irimi_sdk-0.2.0/src/irimi/_function_answers.py +87 -0
- irimi_sdk-0.2.0/src/irimi/_git.py +37 -0
- irimi_sdk-0.2.0/src/irimi/_httpx_patch.py +236 -0
- irimi_sdk-0.2.0/src/irimi/_interception.py +174 -0
- irimi_sdk-0.2.0/src/irimi/_labeled_calls.py +116 -0
- irimi_sdk-0.2.0/src/irimi/_llm_providers.py +57 -0
- irimi_sdk-0.2.0/src/irimi/_object_fields.py +32 -0
- irimi_sdk-0.2.0/src/irimi/_outbound_calls.py +190 -0
- irimi_sdk-0.2.0/src/irimi/_patching.py +58 -0
- irimi_sdk-0.2.0/src/irimi/_rebuilding.py +97 -0
- irimi_sdk-0.2.0/src/irimi/_recorded_calls.py +231 -0
- irimi_sdk-0.2.0/src/irimi/_recording.py +122 -0
- irimi_sdk-0.2.0/src/irimi/_recording_loader.py +63 -0
- irimi_sdk-0.2.0/src/irimi/_replay_child.py +156 -0
- irimi_sdk-0.2.0/src/irimi/_replay_decisions.py +120 -0
- irimi_sdk-0.2.0/src/irimi/_replay_fields.py +16 -0
- irimi_sdk-0.2.0/src/irimi/_replay_proxy.py +328 -0
- irimi_sdk-0.2.0/src/irimi/_replay_refusals.py +5 -0
- irimi_sdk-0.2.0/src/irimi/_response_recording.py +74 -0
- irimi_sdk-0.2.0/src/irimi/_sdk.py +325 -0
- irimi_sdk-0.2.0/src/irimi/_serialisation.py +114 -0
- irimi_sdk-0.2.0/src/irimi/_status_reasons.py +10 -0
- irimi_sdk-0.2.0/src/irimi/_unpatched_clients.py +105 -0
- irimi_sdk-0.2.0/src/irimi/_url_credentials.py +11 -0
- irimi_sdk-0.2.0/src/irimi/_urllib3_patch.py +465 -0
- irimi_sdk-0.2.0/src/irimi/_urllib3_serving.py +81 -0
- irimi_sdk-0.2.0/src/irimi/_wire/__init__.py +60 -0
- irimi_sdk-0.2.0/src/irimi/_wire/call_roles.py +32 -0
- irimi_sdk-0.2.0/src/irimi/_wire/events.py +209 -0
- irimi_sdk-0.2.0/src/irimi/_wire/field_names.py +80 -0
- irimi_sdk-0.2.0/src/irimi/_wire/json_value.py +3 -0
- irimi_sdk-0.2.0/src/irimi/_wire/local_files.py +5 -0
- irimi_sdk-0.2.0/src/irimi/_wire/markers.py +49 -0
- irimi_sdk-0.2.0/src/irimi/py.typed +0 -0
irimi_sdk-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: irimi-sdk
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: The irimi SDK alone, for production apps: record workflow runs and send them to an irimi server.
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
9
|
+
Classifier: Typing :: Typed
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Project-URL: Homepage, https://github.com/irimi-io/Irimi
|
|
12
|
+
Project-URL: Issues, https://github.com/irimi-io/Irimi/issues
|
|
13
|
+
Project-URL: Source, https://github.com/irimi-io/Irimi
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# irimi-sdk
|
|
17
|
+
|
|
18
|
+
The irimi SDK alone. irimi does shadow runs for AI agents: record a workflow run in production,
|
|
19
|
+
replay it with one change (a model, a prompt, code) with every write faked, and see how the two
|
|
20
|
+
runs differ.
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
pip install irimi-sdk
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
This is the part that runs inside an app and records it: `import irimi`, no dependencies, Python
|
|
27
|
+
3.10 or newer. `pip install irimi` installs it together with the `irimi` command and the irimi
|
|
28
|
+
server, and needs Python 3.12 or newer.
|
|
29
|
+
|
|
30
|
+
## Replay a run
|
|
31
|
+
|
|
32
|
+
A replay runs a recorded run's workflow as the code is now and records the result as a new run.
|
|
33
|
+
Calls that match the recording are answered from it. Writes sent through the HTTP clients irimi
|
|
34
|
+
intercepts (httpx, httpx2, requests, urllib3 and aiohttp) and calls to functions marked
|
|
35
|
+
`@irimi.function(write=True)` are never performed; a read with no match is sent for real. So is an
|
|
36
|
+
LLM call whose request changed: its new answer is the point of a replay, and it costs money and
|
|
37
|
+
tokens like any other call. Once the replay makes a write that is new or has different arguments, or
|
|
38
|
+
skips a recorded write, every read answered from the recording after that is flagged
|
|
39
|
+
`after_divergence`: its answer shows the world as the recorded run left it, not as the replay's
|
|
40
|
+
writes would have. The workflow must live in a module that can be imported. Run the replay from the
|
|
41
|
+
app's directory. With `IRIMI_SERVER_URL` set it uses that server; without it, it reads the runs the
|
|
42
|
+
app recorded to `.irimi` in that directory:
|
|
43
|
+
|
|
44
|
+
```sh
|
|
45
|
+
irimi replay <run id>
|
|
46
|
+
irimi runs <new run id>
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
`irimi replay <run id> --diff` ends by printing how the replay differs from the recorded run,
|
|
50
|
+
call by call, as `irimi diff <run id> <new run id>` does.
|
|
51
|
+
|
|
52
|
+
The `irimi` command comes with `pip install irimi`; `pip install irimi-sdk` does not install it.
|
|
53
|
+
|
|
54
|
+
A replay stops when it finds a client irimi cannot intercept, such as a database driver
|
|
55
|
+
(psycopg, SQLAlchemy, redis and others) or an HTTP client irimi could not patch, and only when the
|
|
56
|
+
app loads it: one that is installed but never imported does not stop a replay. It checks once
|
|
57
|
+
the workflow's module has been imported, and again whenever the workflow imports such a client
|
|
58
|
+
later; writes a module makes while it is being imported happen before that first check. Probing
|
|
59
|
+
for an optional driver inside the workflow, as `importlib.util.find_spec("redis")` does, also
|
|
60
|
+
stops the replay. Label every write through a driver `@irimi.function(write=True)`, then allow it
|
|
61
|
+
by name with `irimi replay <run id> --dangerously-allow-unpatched psycopg` or
|
|
62
|
+
`irimi.init(dangerously_allow_unpatched=["psycopg"])`. Upgrade an HTTP client irimi could not
|
|
63
|
+
patch, or allow it the same way if the workflow makes no calls through it.
|
|
64
|
+
|
|
65
|
+
A replay also points every client that honours proxy settings (`HTTP_PROXY`, `HTTPS_PROXY` and
|
|
66
|
+
`ALL_PROXY`), such as `urllib.request` or `curl`, at a proxy of irimi's own. A plain HTTP call it
|
|
67
|
+
catches is answered like any other call in the replay: from the recording, faked, or sent for real
|
|
68
|
+
when it is a read. An HTTPS connection it catches is refused, since irimi cannot see what would be
|
|
69
|
+
sent through it, and is recorded as `CONNECT <host>`. Both are flagged `caught_by_proxy`. During a
|
|
70
|
+
replay your own `NO_PROXY` is ignored and your `HTTP_PROXY`, `HTTPS_PROXY` and `ALL_PROXY` are
|
|
71
|
+
replaced, so where calls out of your network need a company proxy, the replay's live calls fail.
|
|
72
|
+
|
|
73
|
+
Some writes still really happen: those through a client irimi does not know by name, HTTP sent by a
|
|
74
|
+
client that ignores proxy settings, such as `http.client` used directly, a call the proxy catches on
|
|
75
|
+
its way to a host while irimi has a live call of its own open to that same host, and writes a
|
|
76
|
+
process the workflow starts, such as a `multiprocessing` worker, makes other than through a labeled
|
|
77
|
+
function. In such a process functions marked `@irimi.function(write=True)` are still faked and
|
|
78
|
+
nothing is recorded, but irimi intercepts no HTTP client there: HTTP reaches the replay's proxy only
|
|
79
|
+
from a client that honours proxy settings, and a database driver there is not guarded. Code that
|
|
80
|
+
catches the refusal keeps the replay running, without the driver it tried to import.
|
|
81
|
+
|
|
82
|
+
Early development. Source and issues: https://github.com/irimi-io/Irimi
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# irimi-sdk
|
|
2
|
+
|
|
3
|
+
The irimi SDK alone. irimi does shadow runs for AI agents: record a workflow run in production,
|
|
4
|
+
replay it with one change (a model, a prompt, code) with every write faked, and see how the two
|
|
5
|
+
runs differ.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
pip install irimi-sdk
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
This is the part that runs inside an app and records it: `import irimi`, no dependencies, Python
|
|
12
|
+
3.10 or newer. `pip install irimi` installs it together with the `irimi` command and the irimi
|
|
13
|
+
server, and needs Python 3.12 or newer.
|
|
14
|
+
|
|
15
|
+
## Replay a run
|
|
16
|
+
|
|
17
|
+
A replay runs a recorded run's workflow as the code is now and records the result as a new run.
|
|
18
|
+
Calls that match the recording are answered from it. Writes sent through the HTTP clients irimi
|
|
19
|
+
intercepts (httpx, httpx2, requests, urllib3 and aiohttp) and calls to functions marked
|
|
20
|
+
`@irimi.function(write=True)` are never performed; a read with no match is sent for real. So is an
|
|
21
|
+
LLM call whose request changed: its new answer is the point of a replay, and it costs money and
|
|
22
|
+
tokens like any other call. Once the replay makes a write that is new or has different arguments, or
|
|
23
|
+
skips a recorded write, every read answered from the recording after that is flagged
|
|
24
|
+
`after_divergence`: its answer shows the world as the recorded run left it, not as the replay's
|
|
25
|
+
writes would have. The workflow must live in a module that can be imported. Run the replay from the
|
|
26
|
+
app's directory. With `IRIMI_SERVER_URL` set it uses that server; without it, it reads the runs the
|
|
27
|
+
app recorded to `.irimi` in that directory:
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
irimi replay <run id>
|
|
31
|
+
irimi runs <new run id>
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
`irimi replay <run id> --diff` ends by printing how the replay differs from the recorded run,
|
|
35
|
+
call by call, as `irimi diff <run id> <new run id>` does.
|
|
36
|
+
|
|
37
|
+
The `irimi` command comes with `pip install irimi`; `pip install irimi-sdk` does not install it.
|
|
38
|
+
|
|
39
|
+
A replay stops when it finds a client irimi cannot intercept, such as a database driver
|
|
40
|
+
(psycopg, SQLAlchemy, redis and others) or an HTTP client irimi could not patch, and only when the
|
|
41
|
+
app loads it: one that is installed but never imported does not stop a replay. It checks once
|
|
42
|
+
the workflow's module has been imported, and again whenever the workflow imports such a client
|
|
43
|
+
later; writes a module makes while it is being imported happen before that first check. Probing
|
|
44
|
+
for an optional driver inside the workflow, as `importlib.util.find_spec("redis")` does, also
|
|
45
|
+
stops the replay. Label every write through a driver `@irimi.function(write=True)`, then allow it
|
|
46
|
+
by name with `irimi replay <run id> --dangerously-allow-unpatched psycopg` or
|
|
47
|
+
`irimi.init(dangerously_allow_unpatched=["psycopg"])`. Upgrade an HTTP client irimi could not
|
|
48
|
+
patch, or allow it the same way if the workflow makes no calls through it.
|
|
49
|
+
|
|
50
|
+
A replay also points every client that honours proxy settings (`HTTP_PROXY`, `HTTPS_PROXY` and
|
|
51
|
+
`ALL_PROXY`), such as `urllib.request` or `curl`, at a proxy of irimi's own. A plain HTTP call it
|
|
52
|
+
catches is answered like any other call in the replay: from the recording, faked, or sent for real
|
|
53
|
+
when it is a read. An HTTPS connection it catches is refused, since irimi cannot see what would be
|
|
54
|
+
sent through it, and is recorded as `CONNECT <host>`. Both are flagged `caught_by_proxy`. During a
|
|
55
|
+
replay your own `NO_PROXY` is ignored and your `HTTP_PROXY`, `HTTPS_PROXY` and `ALL_PROXY` are
|
|
56
|
+
replaced, so where calls out of your network need a company proxy, the replay's live calls fail.
|
|
57
|
+
|
|
58
|
+
Some writes still really happen: those through a client irimi does not know by name, HTTP sent by a
|
|
59
|
+
client that ignores proxy settings, such as `http.client` used directly, a call the proxy catches on
|
|
60
|
+
its way to a host while irimi has a live call of its own open to that same host, and writes a
|
|
61
|
+
process the workflow starts, such as a `multiprocessing` worker, makes other than through a labeled
|
|
62
|
+
function. In such a process functions marked `@irimi.function(write=True)` are still faked and
|
|
63
|
+
nothing is recorded, but irimi intercepts no HTTP client there: HTTP reaches the replay's proxy only
|
|
64
|
+
from a client that honours proxy settings, and a database driver there is not guarded. Code that
|
|
65
|
+
catches the refusal keeps the replay running, without the driver it tried to import.
|
|
66
|
+
|
|
67
|
+
Early development. Source and issues: https://github.com/irimi-io/Irimi
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "irimi-sdk"
|
|
3
|
+
version = "0.2.0"
|
|
4
|
+
description = "The irimi SDK alone, for production apps: record workflow runs and send them to an irimi server."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "Apache-2.0"
|
|
7
|
+
requires-python = ">=3.10"
|
|
8
|
+
dependencies = []
|
|
9
|
+
classifiers = [
|
|
10
|
+
"Development Status :: 2 - Pre-Alpha",
|
|
11
|
+
"Programming Language :: Python :: 3",
|
|
12
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
13
|
+
"Typing :: Typed",
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
[project.urls]
|
|
17
|
+
Homepage = "https://github.com/irimi-io/Irimi"
|
|
18
|
+
Issues = "https://github.com/irimi-io/Irimi/issues"
|
|
19
|
+
Source = "https://github.com/irimi-io/Irimi"
|
|
20
|
+
|
|
21
|
+
[build-system]
|
|
22
|
+
requires = ["uv_build>=0.12,<0.13"]
|
|
23
|
+
build-backend = "uv_build"
|
|
24
|
+
|
|
25
|
+
[tool.uv.build-backend]
|
|
26
|
+
module-name = "irimi"
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "irimi-sdk"
|
|
3
|
+
version = "0.2.0"
|
|
4
|
+
description = "The irimi SDK alone, for production apps: record workflow runs and send them to an irimi server."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "Apache-2.0"
|
|
7
|
+
requires-python = ">=3.10"
|
|
8
|
+
dependencies = []
|
|
9
|
+
classifiers = [
|
|
10
|
+
"Development Status :: 2 - Pre-Alpha",
|
|
11
|
+
"Programming Language :: Python :: 3",
|
|
12
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
13
|
+
"Typing :: Typed",
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
[project.urls]
|
|
17
|
+
Homepage = "https://github.com/irimi-io/Irimi"
|
|
18
|
+
Issues = "https://github.com/irimi-io/Irimi/issues"
|
|
19
|
+
Source = "https://github.com/irimi-io/Irimi"
|
|
20
|
+
|
|
21
|
+
[build-system]
|
|
22
|
+
requires = ["uv_build>=0.12,<0.13"]
|
|
23
|
+
build-backend = "uv_build"
|
|
24
|
+
|
|
25
|
+
[tool.uv.build-backend]
|
|
26
|
+
module-name = "irimi"
|
|
@@ -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
|