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
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable, Mapping
|
|
4
|
+
from dataclasses import dataclass, replace
|
|
5
|
+
|
|
6
|
+
from irimi._labeled_calls import CallLabel
|
|
7
|
+
from irimi._rebuilding import RebuildError, rebuild
|
|
8
|
+
from irimi._recorded_calls import RecordedOutput, key_call
|
|
9
|
+
from irimi._replay_decisions import (
|
|
10
|
+
CandidateCall,
|
|
11
|
+
Decides,
|
|
12
|
+
Decision,
|
|
13
|
+
choose_undescribed_decision,
|
|
14
|
+
)
|
|
15
|
+
from irimi._wire import JsonValue, field_names
|
|
16
|
+
from irimi._wire.call_roles import CallRole, classify_call, is_write_role
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class ServedValue:
|
|
21
|
+
value: object
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class FunctionAnswer:
|
|
26
|
+
decision: Decision
|
|
27
|
+
served: ServedValue | None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def answer_function_call(
|
|
31
|
+
decider: Decides, label: CallLabel, start_fields: Mapping[str, JsonValue]
|
|
32
|
+
) -> FunctionAnswer:
|
|
33
|
+
role = classify_call(label.kind, start_fields)
|
|
34
|
+
decision = decider.decide(CandidateCall(role, label.name, key_call(role, start_fields)))
|
|
35
|
+
return _serve(decision, label)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def answer_undescribed_call(
|
|
39
|
+
decider: Decides, label: CallLabel, report_failure: Callable[[str], None]
|
|
40
|
+
) -> FunctionAnswer:
|
|
41
|
+
role = _choose_undescribed_role(label)
|
|
42
|
+
try:
|
|
43
|
+
decision = decider.decide_undescribed_call(role)
|
|
44
|
+
except Exception:
|
|
45
|
+
report_failure("decide an undescribed call in a replay")
|
|
46
|
+
decision = choose_undescribed_decision(role)
|
|
47
|
+
return FunctionAnswer(decision, answer_without_the_recording(label))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _choose_undescribed_role(label: CallLabel) -> CallRole:
|
|
51
|
+
if label.is_write:
|
|
52
|
+
return "write_function"
|
|
53
|
+
return "read_function" if label.is_read else "plain"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def answer_without_the_recording(label: CallLabel) -> ServedValue | None:
|
|
57
|
+
return ServedValue(_choose_fake(label)) if label.is_write else None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _serve(decision: Decision, label: CallLabel) -> FunctionAnswer:
|
|
61
|
+
if decision.answer == "live":
|
|
62
|
+
return FunctionAnswer(decision, None)
|
|
63
|
+
if decision.answer == "faked":
|
|
64
|
+
return FunctionAnswer(decision, ServedValue(_choose_fake(label)))
|
|
65
|
+
try:
|
|
66
|
+
return FunctionAnswer(decision, ServedValue(rebuild(_read_recorded_value(decision))))
|
|
67
|
+
except RebuildError:
|
|
68
|
+
return _serve(_mark_unservable(decision), label)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _read_recorded_value(decision: Decision) -> JsonValue:
|
|
72
|
+
recorded = decision.matched.result if decision.matched is not None else None
|
|
73
|
+
if not isinstance(recorded, RecordedOutput):
|
|
74
|
+
raise TypeError("a call answered from the recording has no recorded output")
|
|
75
|
+
return recorded.value
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _mark_unservable(decision: Decision) -> Decision:
|
|
79
|
+
return replace(
|
|
80
|
+
decision,
|
|
81
|
+
answer="faked" if is_write_role(decision.role) else "live",
|
|
82
|
+
flags=(*decision.flags, field_names.RECORDED_VALUE_UNSERVABLE),
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _choose_fake(label: CallLabel) -> object:
|
|
87
|
+
return None if label.fake is ... else label.fake
|
irimi/_git.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
REFERENCE_PREFIX = "ref: "
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def find_commit(directory: Path) -> str | None:
|
|
9
|
+
for candidate in (directory, *directory.parents):
|
|
10
|
+
git_directory = candidate / ".git"
|
|
11
|
+
if git_directory.is_dir():
|
|
12
|
+
return _read_head_commit(git_directory)
|
|
13
|
+
return None
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _read_head_commit(git_directory: Path) -> str | None:
|
|
17
|
+
try:
|
|
18
|
+
head = (git_directory / "HEAD").read_text().strip()
|
|
19
|
+
if not head.startswith(REFERENCE_PREFIX):
|
|
20
|
+
return head or None
|
|
21
|
+
return _read_reference(git_directory, head[len(REFERENCE_PREFIX) :])
|
|
22
|
+
except OSError:
|
|
23
|
+
return None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _read_reference(git_directory: Path, reference: str) -> str | None:
|
|
27
|
+
reference_file = git_directory / reference
|
|
28
|
+
if reference_file.is_file():
|
|
29
|
+
return reference_file.read_text().strip() or None
|
|
30
|
+
packed_references = git_directory / "packed-refs"
|
|
31
|
+
if not packed_references.is_file():
|
|
32
|
+
return None
|
|
33
|
+
for line in packed_references.read_text().splitlines():
|
|
34
|
+
commit, _, name = line.partition(" ")
|
|
35
|
+
if name == reference:
|
|
36
|
+
return commit
|
|
37
|
+
return None
|
irimi/_httpx_patch.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import functools
|
|
4
|
+
import inspect
|
|
5
|
+
import weakref
|
|
6
|
+
from collections.abc import AsyncIterator, Awaitable, Callable, Iterator
|
|
7
|
+
from types import ModuleType
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from irimi._interception import Interception, OpenCall
|
|
11
|
+
from irimi._outbound_calls import Headers, OutboundCall, OutboundResponse
|
|
12
|
+
from irimi._recorded_calls import RecordedResponse
|
|
13
|
+
from irimi._response_recording import (
|
|
14
|
+
ResponseRecording,
|
|
15
|
+
end_without_response,
|
|
16
|
+
serve_built_response,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
TRANSPORT_METHODS = (
|
|
20
|
+
"HTTPTransport.handle_request",
|
|
21
|
+
"AsyncHTTPTransport.handle_async_request",
|
|
22
|
+
)
|
|
23
|
+
RECORDING_TARGETS = (
|
|
24
|
+
*TRANSPORT_METHODS,
|
|
25
|
+
"SyncByteStream",
|
|
26
|
+
"AsyncByteStream",
|
|
27
|
+
"ByteStream",
|
|
28
|
+
"RequestNotRead",
|
|
29
|
+
)
|
|
30
|
+
SERVING_TARGETS = ("Response",)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def patch_httpx(library: ModuleType, interception: Interception) -> bool:
|
|
34
|
+
targets = (
|
|
35
|
+
(*RECORDING_TARGETS, *SERVING_TARGETS) if interception.is_shadow else RECORDING_TARGETS
|
|
36
|
+
)
|
|
37
|
+
if not all(_find_attribute(library, path) is not None for path in targets):
|
|
38
|
+
return False
|
|
39
|
+
if not all(_takes_one_request(_find_attribute(library, path)) for path in TRANSPORT_METHODS):
|
|
40
|
+
return False
|
|
41
|
+
handle_request = _wrap_sync_transport(library, interception)
|
|
42
|
+
handle_async_request = _wrap_async_transport(library, interception)
|
|
43
|
+
library.HTTPTransport.handle_request = handle_request
|
|
44
|
+
library.AsyncHTTPTransport.handle_async_request = handle_async_request
|
|
45
|
+
return True
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _wrap_sync_transport(
|
|
49
|
+
library: ModuleType, interception: Interception
|
|
50
|
+
) -> Callable[[object, Any], Any]:
|
|
51
|
+
send_request = library.HTTPTransport.handle_request
|
|
52
|
+
stream_class = type(
|
|
53
|
+
"RecordingSyncByteStream",
|
|
54
|
+
(library.SyncByteStream,),
|
|
55
|
+
{"__init__": _hold_stream, "__iter__": _iterate_sync_stream, "close": _close_sync_stream},
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
@functools.wraps(send_request)
|
|
59
|
+
def handle_request(transport: object, request: Any) -> Any:
|
|
60
|
+
open_call = _begin_call(interception, request, library)
|
|
61
|
+
if open_call is not None and open_call.served_response is not None:
|
|
62
|
+
served = open_call.served_response
|
|
63
|
+
return _serve_response(interception, open_call, served, request, library)
|
|
64
|
+
try:
|
|
65
|
+
response = send_request(transport, request)
|
|
66
|
+
except BaseException as error:
|
|
67
|
+
end_without_response(interception, open_call, error)
|
|
68
|
+
raise
|
|
69
|
+
_record_response(interception, open_call, response, stream_class)
|
|
70
|
+
return response
|
|
71
|
+
|
|
72
|
+
return handle_request
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _wrap_async_transport(
|
|
76
|
+
library: ModuleType, interception: Interception
|
|
77
|
+
) -> Callable[[object, Any], Awaitable[Any]]:
|
|
78
|
+
send_request = library.AsyncHTTPTransport.handle_async_request
|
|
79
|
+
stream_class = type(
|
|
80
|
+
"RecordingAsyncByteStream",
|
|
81
|
+
(library.AsyncByteStream,),
|
|
82
|
+
{
|
|
83
|
+
"__init__": _hold_stream,
|
|
84
|
+
"__aiter__": _iterate_async_stream,
|
|
85
|
+
"aclose": _close_async_stream,
|
|
86
|
+
},
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
@functools.wraps(send_request)
|
|
90
|
+
async def handle_async_request(transport: object, request: Any) -> Any:
|
|
91
|
+
open_call = _begin_call(interception, request, library)
|
|
92
|
+
if open_call is not None and open_call.served_response is not None:
|
|
93
|
+
served = open_call.served_response
|
|
94
|
+
return _serve_response(interception, open_call, served, request, library)
|
|
95
|
+
try:
|
|
96
|
+
response = await send_request(transport, request)
|
|
97
|
+
except BaseException as error:
|
|
98
|
+
end_without_response(interception, open_call, error)
|
|
99
|
+
raise
|
|
100
|
+
_record_response(interception, open_call, response, stream_class)
|
|
101
|
+
return response
|
|
102
|
+
|
|
103
|
+
return handle_async_request
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _begin_call(interception: Interception, request: Any, library: ModuleType) -> OpenCall | None:
|
|
107
|
+
try:
|
|
108
|
+
call = _translate_request(request, library)
|
|
109
|
+
except Exception:
|
|
110
|
+
return interception.begin_unreadable()
|
|
111
|
+
return interception.begin(call)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _serve_response(
|
|
115
|
+
interception: Interception,
|
|
116
|
+
open_call: OpenCall,
|
|
117
|
+
served: RecordedResponse,
|
|
118
|
+
request: Any,
|
|
119
|
+
library: ModuleType,
|
|
120
|
+
) -> Any:
|
|
121
|
+
def build_response() -> Any:
|
|
122
|
+
return library.Response(
|
|
123
|
+
served.status,
|
|
124
|
+
headers=list(served.headers),
|
|
125
|
+
stream=library.ByteStream(served.body),
|
|
126
|
+
request=request,
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
return serve_built_response(interception, open_call, build_response)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _record_response(
|
|
133
|
+
interception: Interception, open_call: OpenCall | None, response: Any, stream_class: type
|
|
134
|
+
) -> None:
|
|
135
|
+
if open_call is None:
|
|
136
|
+
return
|
|
137
|
+
try:
|
|
138
|
+
recording = ResponseRecording(interception, open_call, _translate_response(response))
|
|
139
|
+
response.stream = stream_class(response.stream, recording)
|
|
140
|
+
if interception.is_shadow:
|
|
141
|
+
weakref.finalize(response, recording.end, was_read_to_end=False, error=None)
|
|
142
|
+
except Exception:
|
|
143
|
+
interception.release_live_call(open_call)
|
|
144
|
+
interception.report_failure("record an outbound response")
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _translate_request(request: Any, library: ModuleType) -> OutboundCall:
|
|
148
|
+
in_memory_body = _find_in_memory_body(request, library)
|
|
149
|
+
return OutboundCall(
|
|
150
|
+
method=str(request.method),
|
|
151
|
+
url=str(request.url),
|
|
152
|
+
headers=_decode_headers(request.headers.raw),
|
|
153
|
+
body=in_memory_body or None,
|
|
154
|
+
has_streamed_body=in_memory_body is None,
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _find_in_memory_body(request: Any, library: ModuleType) -> bytes | None:
|
|
159
|
+
try:
|
|
160
|
+
return bytes(request.content)
|
|
161
|
+
except library.RequestNotRead:
|
|
162
|
+
return _read_unloaded_byte_stream(request.stream, library)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _read_unloaded_byte_stream(stream: Any, library: ModuleType) -> bytes | None:
|
|
166
|
+
if not isinstance(stream, library.ByteStream):
|
|
167
|
+
return None
|
|
168
|
+
return b"".join(stream)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _translate_response(response: Any) -> OutboundResponse:
|
|
172
|
+
return OutboundResponse(
|
|
173
|
+
status=int(response.status_code), headers=_decode_headers(response.headers.raw)
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _decode_headers(raw_headers: Any) -> Headers:
|
|
178
|
+
return tuple((name.decode("latin-1"), value.decode("latin-1")) for name, value in raw_headers)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _hold_stream(stream: Any, inner_stream: Any, recording: ResponseRecording) -> None:
|
|
182
|
+
stream.inner_stream = inner_stream
|
|
183
|
+
stream.recording = recording
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _iterate_sync_stream(stream: Any) -> Iterator[bytes]:
|
|
187
|
+
try:
|
|
188
|
+
for chunk in stream.inner_stream:
|
|
189
|
+
stream.recording.add(chunk)
|
|
190
|
+
yield chunk
|
|
191
|
+
except GeneratorExit:
|
|
192
|
+
raise
|
|
193
|
+
except BaseException as error:
|
|
194
|
+
stream.recording.end(was_read_to_end=False, error=error)
|
|
195
|
+
raise
|
|
196
|
+
stream.recording.end(was_read_to_end=True, error=None)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _close_sync_stream(stream: Any) -> None:
|
|
200
|
+
try:
|
|
201
|
+
stream.recording.end(was_read_to_end=False, error=None)
|
|
202
|
+
finally:
|
|
203
|
+
stream.inner_stream.close()
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
async def _iterate_async_stream(stream: Any) -> AsyncIterator[bytes]:
|
|
207
|
+
try:
|
|
208
|
+
async for chunk in stream.inner_stream:
|
|
209
|
+
stream.recording.add(chunk)
|
|
210
|
+
yield chunk
|
|
211
|
+
except GeneratorExit:
|
|
212
|
+
raise
|
|
213
|
+
except BaseException as error:
|
|
214
|
+
stream.recording.end(was_read_to_end=False, error=error)
|
|
215
|
+
raise
|
|
216
|
+
stream.recording.end(was_read_to_end=True, error=None)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
async def _close_async_stream(stream: Any) -> None:
|
|
220
|
+
try:
|
|
221
|
+
stream.recording.end(was_read_to_end=False, error=None)
|
|
222
|
+
finally:
|
|
223
|
+
await stream.inner_stream.aclose()
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _takes_one_request(send_request: object) -> bool:
|
|
227
|
+
if not callable(send_request):
|
|
228
|
+
return False
|
|
229
|
+
return list(inspect.signature(send_request).parameters)[1:] == ["request"]
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _find_attribute(root: object, path: str) -> object:
|
|
233
|
+
found = root
|
|
234
|
+
for name in path.split("."):
|
|
235
|
+
found = getattr(found, name, None)
|
|
236
|
+
return found
|
irimi/_interception.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import itertools
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Protocol
|
|
7
|
+
|
|
8
|
+
from irimi._bodies import copy_body
|
|
9
|
+
from irimi._outbound_calls import (
|
|
10
|
+
CallIdentity,
|
|
11
|
+
CallOutcome,
|
|
12
|
+
OutboundCall,
|
|
13
|
+
OutboundResponse,
|
|
14
|
+
describe_outcome,
|
|
15
|
+
describe_request,
|
|
16
|
+
find_address,
|
|
17
|
+
identify_call,
|
|
18
|
+
)
|
|
19
|
+
from irimi._recorded_calls import GENERIC_FAKE_RESPONSE, RecordedResponse, key_call
|
|
20
|
+
from irimi._recording import ActiveCall, Payload, Recorder
|
|
21
|
+
from irimi._replay_decisions import FAKED_UNDESCRIBED_CALL, CandidateCall, Decides, Decision
|
|
22
|
+
from irimi._wire import Flag
|
|
23
|
+
from irimi._wire.call_roles import classify_call
|
|
24
|
+
|
|
25
|
+
UNDESCRIBED_CALL_NAME = "undescribed call"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class TracksLiveCalls(Protocol):
|
|
29
|
+
def open(self, host: str, port: int) -> None: ...
|
|
30
|
+
def close(self, host: str, port: int) -> None: ...
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class LiveHold:
|
|
34
|
+
def __init__(self, live_calls: TracksLiveCalls, address: tuple[str, int]) -> None:
|
|
35
|
+
self._live_calls = live_calls
|
|
36
|
+
self._address = address
|
|
37
|
+
self._releases_asked_for = itertools.count()
|
|
38
|
+
live_calls.open(*address)
|
|
39
|
+
|
|
40
|
+
def release(self) -> None:
|
|
41
|
+
if next(self._releases_asked_for) == 0:
|
|
42
|
+
self._live_calls.close(*self._address)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True)
|
|
46
|
+
class OpenCall:
|
|
47
|
+
call: ActiveCall | None
|
|
48
|
+
is_attached: bool
|
|
49
|
+
decision: Decision | None = None
|
|
50
|
+
served_response: RecordedResponse | None = None
|
|
51
|
+
live_hold: LiveHold | None = None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class Interception:
|
|
55
|
+
def __init__(
|
|
56
|
+
self,
|
|
57
|
+
recorder: Recorder,
|
|
58
|
+
report_failure: Callable[[str], None],
|
|
59
|
+
decider: Decides | None = None,
|
|
60
|
+
live_calls: TracksLiveCalls | None = None,
|
|
61
|
+
) -> None:
|
|
62
|
+
self.recorder = recorder
|
|
63
|
+
self.report_failure = report_failure
|
|
64
|
+
self._decider = decider
|
|
65
|
+
self._live_calls = live_calls
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def is_shadow(self) -> bool:
|
|
69
|
+
return self._decider is not None
|
|
70
|
+
|
|
71
|
+
def is_inside_workflow(self) -> bool:
|
|
72
|
+
current_call = self.recorder.find_current_call()
|
|
73
|
+
return current_call is not None and current_call.run.is_workflow
|
|
74
|
+
|
|
75
|
+
def begin(self, call: OutboundCall, added_flags: tuple[Flag, ...] = ()) -> OpenCall | None:
|
|
76
|
+
try:
|
|
77
|
+
return self._begin(call, added_flags)
|
|
78
|
+
except Exception:
|
|
79
|
+
if self.is_shadow:
|
|
80
|
+
return self.fake_undescribed_call()
|
|
81
|
+
self.report_failure("record the start of an outbound call")
|
|
82
|
+
return None
|
|
83
|
+
|
|
84
|
+
def begin_unreadable(self) -> OpenCall | None:
|
|
85
|
+
if self.is_shadow:
|
|
86
|
+
return self.fake_undescribed_call()
|
|
87
|
+
self.report_failure("read an outbound request")
|
|
88
|
+
return None
|
|
89
|
+
|
|
90
|
+
def fake_undescribed_call(self) -> OpenCall:
|
|
91
|
+
self.report_failure("describe an outbound call in a replay, so it was faked")
|
|
92
|
+
decision = self._decide_undescribed_call()
|
|
93
|
+
try:
|
|
94
|
+
call = self.recorder.begin_detached_call("http", UNDESCRIBED_CALL_NAME, Payload({}, 0))
|
|
95
|
+
except Exception:
|
|
96
|
+
self.report_failure("record an undescribed outbound call")
|
|
97
|
+
call = None
|
|
98
|
+
return OpenCall(call, False, decision, GENERIC_FAKE_RESPONSE)
|
|
99
|
+
|
|
100
|
+
def _decide_undescribed_call(self) -> Decision:
|
|
101
|
+
if self._decider is None:
|
|
102
|
+
return FAKED_UNDESCRIBED_CALL
|
|
103
|
+
try:
|
|
104
|
+
return self._decider.decide_undescribed_call(FAKED_UNDESCRIBED_CALL.role)
|
|
105
|
+
except Exception:
|
|
106
|
+
self.report_failure("decide an undescribed outbound call in a replay")
|
|
107
|
+
return FAKED_UNDESCRIBED_CALL
|
|
108
|
+
|
|
109
|
+
def end_served(self, open_call: OpenCall) -> None:
|
|
110
|
+
served = open_call.served_response
|
|
111
|
+
if served is None:
|
|
112
|
+
return
|
|
113
|
+
outcome = CallOutcome(
|
|
114
|
+
response=OutboundResponse(served.status, served.headers),
|
|
115
|
+
body=copy_body(served.body),
|
|
116
|
+
was_read_to_end=True,
|
|
117
|
+
error=None,
|
|
118
|
+
)
|
|
119
|
+
self.end(open_call, outcome)
|
|
120
|
+
|
|
121
|
+
def release_live_call(self, open_call: OpenCall | None) -> None:
|
|
122
|
+
if open_call is not None and open_call.live_hold is not None:
|
|
123
|
+
open_call.live_hold.release()
|
|
124
|
+
|
|
125
|
+
def end(self, open_call: OpenCall | None, outcome: CallOutcome) -> None:
|
|
126
|
+
self.release_live_call(open_call)
|
|
127
|
+
if open_call is None or open_call.call is None:
|
|
128
|
+
return
|
|
129
|
+
try:
|
|
130
|
+
payload = describe_outcome(outcome, open_call.is_attached, open_call.decision)
|
|
131
|
+
self.recorder.end_detached_call(open_call.call, payload)
|
|
132
|
+
except Exception:
|
|
133
|
+
self.report_failure("record the end of an outbound call")
|
|
134
|
+
|
|
135
|
+
def _begin(self, call: OutboundCall, added_flags: tuple[Flag, ...]) -> OpenCall:
|
|
136
|
+
is_attached = self.is_inside_workflow()
|
|
137
|
+
payload = describe_request(call, is_attached, added_flags)
|
|
138
|
+
identity = identify_call(call)
|
|
139
|
+
decision = self._decide(identity, payload)
|
|
140
|
+
served_response = _choose_served_response(decision) if decision is not None else None
|
|
141
|
+
live_address = self._find_live_address(call, decision)
|
|
142
|
+
active_call = self.recorder.begin_detached_call(identity.kind, identity.name, payload)
|
|
143
|
+
live_hold = self._hold_live_address(live_address)
|
|
144
|
+
return OpenCall(active_call, is_attached, decision, served_response, live_hold)
|
|
145
|
+
|
|
146
|
+
def _find_live_address(
|
|
147
|
+
self, call: OutboundCall, decision: Decision | None
|
|
148
|
+
) -> tuple[str, int] | None:
|
|
149
|
+
if self._live_calls is None or decision is None or decision.answer != "live":
|
|
150
|
+
return None
|
|
151
|
+
return find_address(call.url)
|
|
152
|
+
|
|
153
|
+
def _hold_live_address(self, address: tuple[str, int] | None) -> LiveHold | None:
|
|
154
|
+
if self._live_calls is None or address is None:
|
|
155
|
+
return None
|
|
156
|
+
return LiveHold(self._live_calls, address)
|
|
157
|
+
|
|
158
|
+
def _decide(self, identity: CallIdentity, payload: Payload) -> Decision | None:
|
|
159
|
+
if self._decider is None:
|
|
160
|
+
return None
|
|
161
|
+
role = classify_call(identity.kind, payload.fields)
|
|
162
|
+
candidate = CandidateCall(role, identity.name, key_call(role, payload.fields))
|
|
163
|
+
return self._decider.decide(candidate)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _choose_served_response(decision: Decision) -> RecordedResponse | None:
|
|
167
|
+
if decision.answer == "live":
|
|
168
|
+
return None
|
|
169
|
+
if decision.answer == "faked":
|
|
170
|
+
return GENERIC_FAKE_RESPONSE
|
|
171
|
+
recorded = decision.matched.result if decision.matched is not None else None
|
|
172
|
+
if not isinstance(recorded, RecordedResponse):
|
|
173
|
+
raise TypeError("a call answered from the recording has no recorded response")
|
|
174
|
+
return recorded
|
irimi/_labeled_calls.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Collection, Mapping, Sequence
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Literal
|
|
6
|
+
|
|
7
|
+
from irimi._errors import describe_error
|
|
8
|
+
from irimi._recording import Payload
|
|
9
|
+
from irimi._replay_decisions import Decision
|
|
10
|
+
from irimi._replay_fields import describe_decision
|
|
11
|
+
from irimi._serialisation import serialise, serialise_arguments
|
|
12
|
+
from irimi._wire import Flag, JsonValue, field_names, write_flags
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class CallLabel:
|
|
17
|
+
kind: Literal["workflow", "function"]
|
|
18
|
+
name: str
|
|
19
|
+
import_path: str
|
|
20
|
+
key: str | None = None
|
|
21
|
+
is_write: bool = False
|
|
22
|
+
is_read: bool = False
|
|
23
|
+
fake: object = ...
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class RunSettings:
|
|
28
|
+
environment: str | None
|
|
29
|
+
version: str | None
|
|
30
|
+
commit: str | None
|
|
31
|
+
replay_source_run: str | None = None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def describe_start(
|
|
35
|
+
label: CallLabel,
|
|
36
|
+
arguments: Sequence[object],
|
|
37
|
+
keyword_arguments: Mapping[str, object],
|
|
38
|
+
settings: RunSettings,
|
|
39
|
+
is_root: bool,
|
|
40
|
+
allowed_unpatched: Collection[str],
|
|
41
|
+
) -> Payload:
|
|
42
|
+
call_input = serialise_arguments(arguments, keyword_arguments)
|
|
43
|
+
fields: dict[str, JsonValue] = {field_names.INPUT: call_input.value}
|
|
44
|
+
if label.is_write:
|
|
45
|
+
fields[field_names.WRITE] = True
|
|
46
|
+
if label.is_read:
|
|
47
|
+
fields[field_names.READ] = True
|
|
48
|
+
if is_root:
|
|
49
|
+
fields.update(_describe_root(label, settings, call_input.is_complete, allowed_unpatched))
|
|
50
|
+
return Payload(fields, call_input.approximate_size)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def describe_output(output: object, decision: Decision | None) -> Payload:
|
|
54
|
+
serialised = serialise(output)
|
|
55
|
+
fields: dict[str, JsonValue] = {field_names.STATUS: "ok", field_names.OUTPUT: serialised.value}
|
|
56
|
+
flags: tuple[Flag, ...] = () if serialised.is_complete else (field_names.UNSERIALISABLE_OUTPUT,)
|
|
57
|
+
return Payload(_add_answer(fields, flags, decision), serialised.approximate_size)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def describe_raised(error: BaseException, decision: Decision | None) -> Payload:
|
|
61
|
+
described = describe_error(error)
|
|
62
|
+
return Payload(_add_answer(dict(described.fields), (), decision), described.approximate_size)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _add_answer(
|
|
66
|
+
fields: dict[str, JsonValue], flags: tuple[Flag, ...], decision: Decision | None
|
|
67
|
+
) -> dict[str, JsonValue]:
|
|
68
|
+
if decision is not None:
|
|
69
|
+
fields = {**fields, **describe_decision(decision)}
|
|
70
|
+
flags = (*flags, *decision.flags)
|
|
71
|
+
if flags:
|
|
72
|
+
fields[field_names.FLAGS] = write_flags(*flags)
|
|
73
|
+
return fields
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _describe_root(
|
|
77
|
+
label: CallLabel,
|
|
78
|
+
settings: RunSettings,
|
|
79
|
+
is_input_complete: bool,
|
|
80
|
+
allowed_unpatched: Collection[str],
|
|
81
|
+
) -> dict[str, JsonValue]:
|
|
82
|
+
if label.kind == "function":
|
|
83
|
+
return {field_names.FLAGS: write_flags(field_names.UNATTACHED)}
|
|
84
|
+
deployment: dict[str, JsonValue] = {
|
|
85
|
+
name: value
|
|
86
|
+
for name, value in (
|
|
87
|
+
("version", settings.version or settings.commit),
|
|
88
|
+
("commit", settings.commit),
|
|
89
|
+
)
|
|
90
|
+
if value is not None
|
|
91
|
+
}
|
|
92
|
+
fields: dict[str, JsonValue] = {
|
|
93
|
+
field_names.MODE: "normal" if settings.replay_source_run is None else "shadow",
|
|
94
|
+
field_names.STARTED_BY: {
|
|
95
|
+
"kind": "decorated_function",
|
|
96
|
+
field_names.IMPORT_PATH: label.import_path,
|
|
97
|
+
},
|
|
98
|
+
field_names.DEPLOYMENT: deployment,
|
|
99
|
+
}
|
|
100
|
+
if label.key is not None:
|
|
101
|
+
fields[field_names.KEY] = label.key
|
|
102
|
+
if settings.replay_source_run is not None:
|
|
103
|
+
fields[field_names.REPLAY] = _describe_replay(settings.replay_source_run, allowed_unpatched)
|
|
104
|
+
if settings.environment is not None:
|
|
105
|
+
fields[field_names.ENVIRONMENT] = settings.environment
|
|
106
|
+
if not is_input_complete:
|
|
107
|
+
fields[field_names.FLAGS] = write_flags(field_names.NOT_REPLAYABLE)
|
|
108
|
+
return fields
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _describe_replay(source_run: str, allowed_unpatched: Collection[str]) -> dict[str, JsonValue]:
|
|
112
|
+
replay: dict[str, JsonValue] = {field_names.SOURCE_RUN: source_run}
|
|
113
|
+
if allowed_unpatched:
|
|
114
|
+
names: list[JsonValue] = [*sorted(allowed_unpatched)]
|
|
115
|
+
replay[field_names.ALLOWED_UNPATCHED] = names
|
|
116
|
+
return replay
|