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.
Files changed (48) hide show
  1. irimi/__init__.py +4 -0
  2. irimi/_aiohttp_patch.py +371 -0
  3. irimi/_aiohttp_serving.py +216 -0
  4. irimi/_atomic_total.py +14 -0
  5. irimi/_bodies.py +64 -0
  6. irimi/_credential_headers.py +52 -0
  7. irimi/_decorators.py +236 -0
  8. irimi/_delivery.py +70 -0
  9. irimi/_divergence.py +60 -0
  10. irimi/_drops.py +24 -0
  11. irimi/_errors.py +14 -0
  12. irimi/_exporter.py +193 -0
  13. irimi/_function_answers.py +87 -0
  14. irimi/_git.py +37 -0
  15. irimi/_httpx_patch.py +236 -0
  16. irimi/_interception.py +174 -0
  17. irimi/_labeled_calls.py +116 -0
  18. irimi/_llm_providers.py +57 -0
  19. irimi/_object_fields.py +32 -0
  20. irimi/_outbound_calls.py +190 -0
  21. irimi/_patching.py +58 -0
  22. irimi/_rebuilding.py +97 -0
  23. irimi/_recorded_calls.py +231 -0
  24. irimi/_recording.py +122 -0
  25. irimi/_recording_loader.py +63 -0
  26. irimi/_replay_child.py +156 -0
  27. irimi/_replay_decisions.py +120 -0
  28. irimi/_replay_fields.py +16 -0
  29. irimi/_replay_proxy.py +328 -0
  30. irimi/_replay_refusals.py +5 -0
  31. irimi/_response_recording.py +74 -0
  32. irimi/_sdk.py +318 -0
  33. irimi/_serialisation.py +114 -0
  34. irimi/_status_reasons.py +10 -0
  35. irimi/_unpatched_clients.py +105 -0
  36. irimi/_url_credentials.py +11 -0
  37. irimi/_urllib3_patch.py +465 -0
  38. irimi/_urllib3_serving.py +81 -0
  39. irimi/_wire/__init__.py +56 -0
  40. irimi/_wire/call_roles.py +32 -0
  41. irimi/_wire/events.py +209 -0
  42. irimi/_wire/field_names.py +80 -0
  43. irimi/_wire/json_value.py +3 -0
  44. irimi/_wire/markers.py +49 -0
  45. irimi/py.typed +0 -0
  46. irimi_sdk-0.2.0.dev0.dist-info/METADATA +81 -0
  47. irimi_sdk-0.2.0.dev0.dist-info/RECORD +48 -0
  48. irimi_sdk-0.2.0.dev0.dist-info/WHEEL +4 -0
@@ -0,0 +1,57 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+
5
+
6
+ @dataclass(frozen=True)
7
+ class ProviderOperation:
8
+ host: str
9
+ path_segments: tuple[str, ...]
10
+ name: str
11
+
12
+
13
+ PROVIDER_OPERATIONS = (
14
+ ProviderOperation("api.anthropic.com", ("v1", "messages"), "anthropic messages.create"),
15
+ ProviderOperation(
16
+ "api.openai.com", ("v1", "chat", "completions"), "openai chat.completions.create"
17
+ ),
18
+ ProviderOperation("api.openai.com", ("v1", "responses"), "openai responses.create"),
19
+ ProviderOperation(
20
+ "openrouter.ai", ("api", "v1", "chat", "completions"), "openrouter chat.completions.create"
21
+ ),
22
+ ProviderOperation(
23
+ "generativelanguage.googleapis.com",
24
+ ("{version}", "models", "{model}:generateContent"),
25
+ "gemini models.generate_content",
26
+ ),
27
+ ProviderOperation(
28
+ "generativelanguage.googleapis.com",
29
+ ("{version}", "models", "{model}:streamGenerateContent"),
30
+ "gemini models.generate_content",
31
+ ),
32
+ )
33
+
34
+
35
+ def recognise_llm_call(method: str, host: str, path: str) -> str | None:
36
+ lower_case_host = host.lower()
37
+ segments = tuple(path.split("/")[1:])
38
+ return next(
39
+ (
40
+ operation.name
41
+ for operation in PROVIDER_OPERATIONS
42
+ if operation.host == lower_case_host
43
+ and _has_matching_segments(operation.path_segments, segments)
44
+ ),
45
+ None,
46
+ )
47
+
48
+
49
+ def _has_matching_segments(patterns: tuple[str, ...], segments: tuple[str, ...]) -> bool:
50
+ return len(patterns) == len(segments) and all(map(_is_matching_segment, patterns, segments))
51
+
52
+
53
+ def _is_matching_segment(pattern: str, segment: str) -> bool:
54
+ if "}" not in pattern:
55
+ return segment == pattern
56
+ ending = pattern.rpartition("}")[2]
57
+ return len(segment) > len(ending) and segment.endswith(ending)
@@ -0,0 +1,32 @@
1
+ from __future__ import annotations
2
+
3
+ import dataclasses
4
+ from types import BuiltinFunctionType
5
+
6
+ HEAP_TYPE_FLAG = 1 << 9
7
+
8
+
9
+ def read_fields(value: object) -> dict[str, object] | None:
10
+ if dataclasses.is_dataclass(value) and not isinstance(value, type):
11
+ return {field.name: getattr(value, field.name) for field in dataclasses.fields(value)}
12
+ model_type = type(value)
13
+ model_fields = getattr(model_type, "model_fields", None)
14
+ if not callable(getattr(model_type, "model_dump", None)) or not isinstance(model_fields, dict):
15
+ return None
16
+ fields = {name: getattr(value, name) for name in model_fields}
17
+ extra_fields = getattr(value, "model_extra", None)
18
+ return {**fields, **extra_fields} if isinstance(extra_fields, dict) else fields
19
+
20
+
21
+ def keeps_state_outside_attributes(object_type: type) -> bool:
22
+ for base in object_type.__mro__:
23
+ if base is not object and _lays_out_its_own_instances(base):
24
+ return True
25
+ return False
26
+
27
+
28
+ def _lays_out_its_own_instances(base: type) -> bool:
29
+ if not base.__flags__ & HEAP_TYPE_FLAG:
30
+ return True
31
+ constructor = base.__new__
32
+ return isinstance(constructor, BuiltinFunctionType) and constructor.__self__ is base
@@ -0,0 +1,190 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Sequence
4
+ from dataclasses import dataclass
5
+ from typing import Literal
6
+ from urllib.parse import urlsplit
7
+
8
+ from irimi._bodies import CopiedBody, copy_body, describe_body
9
+ from irimi._credential_headers import replace_credential_values
10
+ from irimi._errors import describe_error
11
+ from irimi._llm_providers import recognise_llm_call
12
+ from irimi._recording import Payload
13
+ from irimi._replay_decisions import Decision
14
+ from irimi._replay_fields import describe_decision
15
+ from irimi._url_credentials import remove_userinfo
16
+ from irimi._wire import Flag, JsonValue, field_names, write_flags
17
+
18
+ Headers = tuple[tuple[str, str], ...]
19
+
20
+ EVENT_STREAM_TYPE = "text/event-stream"
21
+ EVENT_ENDINGS = (b"\n\n", b"\r\r", b"\r\n\r\n")
22
+ DEFAULT_PORTS = {"http": 80, "https": 443}
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class OutboundCall:
27
+ method: str
28
+ url: str
29
+ headers: Headers
30
+ body: bytes | None
31
+ has_streamed_body: bool
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class OutboundResponse:
36
+ status: int
37
+ headers: Headers
38
+ is_body_decoded: bool = False
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class CallOutcome:
43
+ response: OutboundResponse | None
44
+ body: CopiedBody | None
45
+ was_read_to_end: bool
46
+ error: BaseException | None
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class CallIdentity:
51
+ kind: Literal["http", "llm"]
52
+ name: str
53
+
54
+
55
+ def identify_call(call: OutboundCall) -> CallIdentity:
56
+ address = urlsplit(call.url)
57
+ host = address.hostname or ""
58
+ if call.method == "CONNECT" and not address.path:
59
+ return CallIdentity("http", f"CONNECT {host}")
60
+ path = address.path or "/"
61
+ llm_name = recognise_llm_call(call.method, host, path)
62
+ if llm_name is not None:
63
+ return CallIdentity("llm", llm_name)
64
+ return CallIdentity("http", f"{call.method} {host}{path}")
65
+
66
+
67
+ def find_address(url: str) -> tuple[str, int]:
68
+ address = urlsplit(url)
69
+ return address.hostname or "", address.port or DEFAULT_PORTS.get(address.scheme, 80)
70
+
71
+
72
+ def describe_request(
73
+ call: OutboundCall, is_attached: bool, added_flags: tuple[Flag, ...] = ()
74
+ ) -> Payload:
75
+ url = remove_userinfo(call.url)
76
+ request: dict[str, JsonValue] = {
77
+ field_names.METHOD: call.method,
78
+ field_names.URL: url,
79
+ field_names.HEADERS: replace_credential_values(call.headers),
80
+ }
81
+ size = len(url) + _measure_header_values(call.headers)
82
+ flags: list[Flag] = list(added_flags)
83
+ if not is_attached:
84
+ flags.append(field_names.UNATTACHED)
85
+ elif call.has_streamed_body:
86
+ flags.append(field_names.REQUEST_BODY_NOT_RECORDED)
87
+ elif call.body is not None:
88
+ body = copy_body(call.body)
89
+ request[field_names.BODY] = _describe_body(body, call.headers, is_whole=True)
90
+ size += len(body.content)
91
+ if body.is_truncated:
92
+ flags.append(field_names.REQUEST_BODY_TRUNCATED)
93
+ fields: dict[str, JsonValue] = {field_names.REQUEST: request}
94
+ return Payload(_add_flags(fields, flags), size)
95
+
96
+
97
+ def describe_outcome(outcome: CallOutcome, is_attached: bool, decision: Decision | None) -> Payload:
98
+ status = (
99
+ describe_error(outcome.error)
100
+ if outcome.error is not None
101
+ else Payload({field_names.STATUS: "ok"}, 0)
102
+ )
103
+ fields: dict[str, JsonValue] = {**status.fields, **_describe_answer(decision)}
104
+ flags: list[Flag] = []
105
+ size = status.approximate_size
106
+ if outcome.response is not None:
107
+ recorded_body = outcome.body if is_attached else None
108
+ is_whole = outcome.was_read_to_end or _was_closed_after_an_event(outcome, recorded_body)
109
+ response = _describe_response(outcome.response, recorded_body, is_whole)
110
+ fields[field_names.RESPONSE] = dict(response.fields)
111
+ flags = _name_response_body_flags(recorded_body, is_whole)
112
+ size += response.approximate_size
113
+ if decision is not None:
114
+ flags = [*flags, *decision.flags]
115
+ return Payload(_add_flags(fields, flags), size)
116
+
117
+
118
+ def _describe_answer(decision: Decision | None) -> dict[str, JsonValue]:
119
+ if decision is None:
120
+ return {field_names.ANSWERED: "live"}
121
+ return describe_decision(decision)
122
+
123
+
124
+ def _was_closed_after_an_event(outcome: CallOutcome, body: CopiedBody | None) -> bool:
125
+ if outcome.error is not None or outcome.response is None or body is None:
126
+ return False
127
+ content_type = _find_header(outcome.response.headers, "content-type") or ""
128
+ is_readable_event_stream = (
129
+ content_type.lower().startswith(EVENT_STREAM_TYPE)
130
+ and _find_body_encoding(outcome.response) is None
131
+ and not body.is_truncated
132
+ )
133
+ return is_readable_event_stream and body.content.endswith(EVENT_ENDINGS)
134
+
135
+
136
+ def _name_response_body_flags(body: CopiedBody | None, is_whole: bool) -> list[Flag]:
137
+ flags: list[Flag] = []
138
+ if body is not None and body.is_truncated:
139
+ flags.append(field_names.RESPONSE_BODY_TRUNCATED)
140
+ if not is_whole:
141
+ flags.append(field_names.RESPONSE_BODY_INCOMPLETE)
142
+ return flags
143
+
144
+
145
+ def _add_flags(fields: dict[str, JsonValue], flags: list[Flag]) -> dict[str, JsonValue]:
146
+ if not flags:
147
+ return fields
148
+ return {**fields, field_names.FLAGS: write_flags(*flags)}
149
+
150
+
151
+ def _describe_response(
152
+ response: OutboundResponse, body: CopiedBody | None, is_whole: bool
153
+ ) -> Payload:
154
+ described: dict[str, JsonValue] = {
155
+ field_names.STATUS: response.status,
156
+ field_names.HEADERS: replace_credential_values(response.headers),
157
+ }
158
+ size = _measure_header_values(response.headers)
159
+ if body is not None and body.content:
160
+ described[field_names.BODY] = describe_body(
161
+ body,
162
+ _find_header(response.headers, "content-type"),
163
+ _find_body_encoding(response),
164
+ is_whole,
165
+ )
166
+ size += len(body.content)
167
+ return Payload(described, size)
168
+
169
+
170
+ def _find_body_encoding(response: OutboundResponse) -> str | None:
171
+ if response.is_body_decoded:
172
+ return None
173
+ return _find_header(response.headers, "content-encoding")
174
+
175
+
176
+ def _describe_body(body: CopiedBody, headers: Headers, is_whole: bool) -> dict[str, JsonValue]:
177
+ return describe_body(
178
+ body,
179
+ _find_header(headers, "content-type"),
180
+ _find_header(headers, "content-encoding"),
181
+ is_whole,
182
+ )
183
+
184
+
185
+ def _find_header(headers: Sequence[tuple[str, str]], lower_case_name: str) -> str | None:
186
+ return next((value for name, value in headers if name.lower() == lower_case_name), None)
187
+
188
+
189
+ def _measure_header_values(headers: Sequence[tuple[str, str]]) -> int:
190
+ return sum(len(value) for _, value in headers)
irimi/_patching.py ADDED
@@ -0,0 +1,58 @@
1
+ from __future__ import annotations
2
+
3
+ import importlib.util
4
+ import logging
5
+ from collections.abc import Callable
6
+ from dataclasses import dataclass
7
+ from types import ModuleType
8
+ from typing import Literal
9
+
10
+ from irimi._aiohttp_patch import patch_aiohttp
11
+ from irimi._httpx_patch import patch_httpx
12
+ from irimi._interception import Interception
13
+ from irimi._urllib3_patch import patch_urllib3
14
+
15
+ logger = logging.getLogger("irimi")
16
+
17
+ Patch = Callable[[ModuleType, Interception], bool]
18
+
19
+ LIBRARY_PATCHES: dict[str, Patch | None] = {
20
+ "httpx": patch_httpx,
21
+ "httpx2": patch_httpx,
22
+ "urllib3": patch_urllib3,
23
+ "aiohttp": patch_aiohttp,
24
+ }
25
+ UNPATCHED_WARNING = "irimi could not patch %s, so calls made through it are not recorded"
26
+
27
+ PatchResult = Literal["patched", "unpatched", "not_installed"]
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class PatchReport:
32
+ patched: tuple[str, ...]
33
+ unpatched: tuple[str, ...]
34
+
35
+
36
+ def patch_installed_libraries(interception: Interception) -> PatchReport:
37
+ results = {name: _patch_library(name, interception) for name in LIBRARY_PATCHES}
38
+ return PatchReport(
39
+ patched=tuple(name for name, result in results.items() if result == "patched"),
40
+ unpatched=tuple(name for name, result in results.items() if result == "unpatched"),
41
+ )
42
+
43
+
44
+ def _patch_library(name: str, interception: Interception) -> PatchResult:
45
+ try:
46
+ if importlib.util.find_spec(name) is None:
47
+ return "not_installed"
48
+ patch = LIBRARY_PATCHES[name]
49
+ if patch is None:
50
+ return "unpatched"
51
+ is_patched = patch(importlib.import_module(name), interception)
52
+ except Exception:
53
+ logger.warning(UNPATCHED_WARNING, name, exc_info=True)
54
+ return "unpatched"
55
+ if not is_patched:
56
+ logger.warning(UNPATCHED_WARNING, name)
57
+ return "unpatched"
58
+ return "patched"
irimi/_rebuilding.py ADDED
@@ -0,0 +1,97 @@
1
+ from __future__ import annotations
2
+
3
+ import dataclasses
4
+ import importlib
5
+ from typing import cast
6
+
7
+ from irimi._wire import JsonValue
8
+ from irimi._wire.markers import LITERAL, RESERVED_KEY
9
+
10
+
11
+ class RebuildError(Exception):
12
+ pass
13
+
14
+
15
+ def rebuild(value: JsonValue) -> object:
16
+ if isinstance(value, list):
17
+ return [rebuild(item) for item in value]
18
+ if not isinstance(value, dict):
19
+ return value
20
+ if RESERVED_KEY not in value:
21
+ return _rebuild_items(value)
22
+ marker = value[RESERVED_KEY]
23
+ if marker == LITERAL and isinstance(value.get("value"), dict):
24
+ return _rebuild_items(cast("dict[str, JsonValue]", value["value"]))
25
+ if marker == "object":
26
+ return _rebuild_object(value)
27
+ if marker == "unserialisable":
28
+ raise RebuildError(f"a value of type {value.get('type')} was not recorded")
29
+ if marker == "redacted":
30
+ raise RebuildError(f"a redacted value ({value.get('reason')}) cannot be rebuilt")
31
+ raise RebuildError(f"unknown marker {marker!r}")
32
+
33
+
34
+ def _rebuild_items(items: dict[str, JsonValue]) -> dict[str, object]:
35
+ return {name: rebuild(item) for name, item in items.items()}
36
+
37
+
38
+ def _rebuild_object(marker: dict[str, JsonValue]) -> object:
39
+ type_name = marker.get("type")
40
+ fields = marker.get("fields")
41
+ if not isinstance(type_name, str) or not isinstance(fields, dict):
42
+ raise RebuildError(f"malformed object marker {marker!r}")
43
+ object_type = _import_type(type_name)
44
+ model_validate = getattr(object_type, "model_validate", None)
45
+ if not callable(model_validate) and not dataclasses.is_dataclass(object_type):
46
+ raise RebuildError(f"{type_name} is neither a dataclass nor a Pydantic model")
47
+ rebuilt_fields = _rebuild_items(fields)
48
+ try:
49
+ if callable(model_validate):
50
+ return model_validate(rebuilt_fields)
51
+ return _construct_dataclass(object_type, rebuilt_fields)
52
+ except Exception as error:
53
+ raise RebuildError(f"cannot rebuild {type_name}: {error}") from error
54
+
55
+
56
+ def _construct_dataclass(object_type: type, fields: dict[str, object]) -> object:
57
+ init_names = {field.name for field in dataclasses.fields(object_type) if field.init}
58
+ rebuilt = object_type(**{name: item for name, item in fields.items() if name in init_names})
59
+ for name, item in fields.items():
60
+ if name not in init_names:
61
+ object.__setattr__(rebuilt, name, item)
62
+ return rebuilt
63
+
64
+
65
+ def _import_type(type_name: str) -> type:
66
+ parts = type_name.split(".")
67
+ if not all(parts):
68
+ raise RebuildError(f"{type_name} is not a valid type name")
69
+ for split in range(len(parts) - 1, 0, -1):
70
+ module_name = ".".join(parts[:split])
71
+ try:
72
+ found: object = importlib.import_module(module_name)
73
+ except ModuleNotFoundError as error:
74
+ if _is_missing_module_or_parent(error, module_name):
75
+ continue
76
+ raise RebuildError(f"cannot import {module_name} for {type_name}: {error}") from error
77
+ except Exception as error:
78
+ raise RebuildError(f"cannot import {module_name} for {type_name}: {error}") from error
79
+ return _walk_to_type(found, parts[split:], type_name)
80
+ raise RebuildError(f"cannot import the module of {type_name}")
81
+
82
+
83
+ def _is_missing_module_or_parent(error: ModuleNotFoundError, module_name: str) -> bool:
84
+ return error.name is not None and (
85
+ module_name == error.name or module_name.startswith(f"{error.name}.")
86
+ )
87
+
88
+
89
+ def _walk_to_type(found: object, names: list[str], type_name: str) -> type:
90
+ for name in names:
91
+ try:
92
+ found = getattr(found, name)
93
+ except AttributeError:
94
+ raise RebuildError(f"{type_name} does not exist") from None
95
+ if not isinstance(found, type):
96
+ raise RebuildError(f"{type_name} is not a class")
97
+ return found
@@ -0,0 +1,231 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import json
5
+ from collections.abc import Iterator, Mapping, Sequence
6
+ from dataclasses import dataclass
7
+
8
+ from irimi._wire import EndEvent, Event, JsonValue, StartEvent, field_names
9
+ from irimi._wire.call_roles import CallRole, classify_call
10
+ from irimi._wire.markers import LITERAL, RESERVED_KEY, unescape_reserved_keys
11
+
12
+ REQUEST_ROLES = frozenset({"llm", "http_read", "http_write"})
13
+ UNSERVABLE_RESPONSE_FLAGS = frozenset(
14
+ {field_names.RESPONSE_BODY_TRUNCATED, field_names.RESPONSE_BODY_INCOMPLETE}
15
+ )
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class RecordedResponse:
20
+ status: int
21
+ headers: tuple[tuple[str, str], ...]
22
+ body: bytes
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class RecordedOutput:
27
+ value: JsonValue
28
+
29
+
30
+ GENERIC_FAKE_RESPONSE = RecordedResponse(
31
+ 200, (("content-type", "application/json"), ("content-length", "2")), b"{}"
32
+ )
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class RecordedCall:
37
+ span_id: str
38
+ name: str
39
+ seq: int
40
+ role: CallRole
41
+ match_key: JsonValue
42
+ result: RecordedResponse | RecordedOutput | None
43
+ descendant_span_ids: frozenset[str] = frozenset()
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class RecordedRun:
48
+ trace_id: str
49
+ root: StartEvent
50
+ calls: tuple[RecordedCall, ...]
51
+
52
+
53
+ class NotReplayableError(Exception):
54
+ pass
55
+
56
+
57
+ def key_call(role: CallRole, start_fields: Mapping[str, JsonValue]) -> JsonValue:
58
+ if role in REQUEST_ROLES:
59
+ return _key_request(_read_object(start_fields, field_names.REQUEST))
60
+ return _replace_unserialisable(start_fields.get(field_names.INPUT))
61
+
62
+
63
+ def read_recorded_run(events: Sequence[Event]) -> RecordedRun:
64
+ starts = {event.span_id: event for event in events if isinstance(event, StartEvent)}
65
+ ends = {event.span_id: event for event in events if isinstance(event, EndEvent)}
66
+ root = _find_root(starts)
67
+ roles = {span_id: classify_call(start.kind, start.fields) for span_id, start in starts.items()}
68
+ descendants = _find_descendants(starts)
69
+ calls = [
70
+ _read_call(start, roles[span_id], ends.get(span_id), descendants.get(span_id, set()))
71
+ for span_id, start in starts.items()
72
+ if start is not root and not _is_inside_write(start, starts, roles)
73
+ ]
74
+ calls.sort(key=lambda call: call.seq)
75
+ return RecordedRun(trace_id=root.trace_id, root=root, calls=tuple(calls))
76
+
77
+
78
+ def _find_root(starts: Mapping[str, StartEvent]) -> StartEvent:
79
+ roots = sorted(
80
+ (start for start in starts.values() if start.parent_span_id is None),
81
+ key=lambda start: start.seq,
82
+ )
83
+ if not roots:
84
+ raise NotReplayableError("the recording has no root call")
85
+ if field_names.NOT_REPLAYABLE in _read_list(roots[0].fields, field_names.FLAGS):
86
+ raise NotReplayableError("its input was not fully recorded")
87
+ return roots[0]
88
+
89
+
90
+ def _is_inside_write(
91
+ start: StartEvent, starts: Mapping[str, StartEvent], roles: Mapping[str, CallRole]
92
+ ) -> bool:
93
+ return any(
94
+ roles.get(ancestor) == "write_function" for ancestor in _find_ancestors(start, starts)
95
+ )
96
+
97
+
98
+ def _find_descendants(starts: Mapping[str, StartEvent]) -> dict[str, set[str]]:
99
+ descendants: dict[str, set[str]] = {}
100
+ for start in starts.values():
101
+ for ancestor in _find_ancestors(start, starts):
102
+ descendants.setdefault(ancestor, set()).add(start.span_id)
103
+ return descendants
104
+
105
+
106
+ def _find_ancestors(start: StartEvent, starts: Mapping[str, StartEvent]) -> Iterator[str]:
107
+ seen = {start.span_id}
108
+ parent_span_id = start.parent_span_id
109
+ while parent_span_id is not None and parent_span_id not in seen:
110
+ seen.add(parent_span_id)
111
+ yield parent_span_id
112
+ parent = starts.get(parent_span_id)
113
+ parent_span_id = parent.parent_span_id if parent is not None else None
114
+
115
+
116
+ def _read_call(
117
+ start: StartEvent, role: CallRole, end: EndEvent | None, descendant_span_ids: set[str]
118
+ ) -> RecordedCall:
119
+ return RecordedCall(
120
+ span_id=start.span_id,
121
+ name=start.name,
122
+ seq=start.seq,
123
+ role=role,
124
+ match_key=key_call(role, start.fields),
125
+ result=_read_result(role, end),
126
+ descendant_span_ids=frozenset(descendant_span_ids),
127
+ )
128
+
129
+
130
+ def _read_result(role: CallRole, end: EndEvent | None) -> RecordedResponse | RecordedOutput | None:
131
+ if end is None or end.fields.get(field_names.STATUS) != "ok":
132
+ return None
133
+ flags = set(_read_list(end.fields, field_names.FLAGS))
134
+ if role in REQUEST_ROLES:
135
+ if flags & UNSERVABLE_RESPONSE_FLAGS:
136
+ return None
137
+ return _read_response(_read_object(end.fields, field_names.RESPONSE))
138
+ if field_names.UNSERIALISABLE_OUTPUT in flags:
139
+ return None
140
+ return RecordedOutput(end.fields.get(field_names.OUTPUT))
141
+
142
+
143
+ def _read_response(response: Mapping[str, JsonValue]) -> RecordedResponse | None:
144
+ status = response.get(field_names.STATUS)
145
+ if isinstance(status, bool) or not isinstance(status, int):
146
+ return None
147
+ description = _read_object(response, field_names.BODY)
148
+ body = _decode_body(description)
149
+ if body is None:
150
+ return None
151
+ return RecordedResponse(
152
+ status=status,
153
+ headers=_make_servable(
154
+ _read_headers(response), len(body), field_names.CONTENT_ENCODING in description
155
+ ),
156
+ body=body,
157
+ )
158
+
159
+
160
+ def _decode_body(description: Mapping[str, JsonValue]) -> bytes | None:
161
+ data = description.get(field_names.DATA)
162
+ if not isinstance(data, str):
163
+ return b""
164
+ if description.get(field_names.ENCODING) == field_names.BASE64:
165
+ try:
166
+ return base64.b64decode(data)
167
+ except ValueError:
168
+ return None
169
+ return data.encode("utf-8")
170
+
171
+
172
+ def _read_headers(document: Mapping[str, JsonValue]) -> list[tuple[str, str]]:
173
+ headers = unescape_reserved_keys(document.get(field_names.HEADERS))
174
+ if not isinstance(headers, dict):
175
+ return []
176
+ return [(name, value) for name, value in headers.items() if isinstance(value, str)]
177
+
178
+
179
+ def _make_servable(
180
+ headers: list[tuple[str, str]], body_length: int, has_content_encoding: bool
181
+ ) -> tuple[tuple[str, str], ...]:
182
+ dropped = {"transfer-encoding", "content-length"}
183
+ if not has_content_encoding:
184
+ dropped.add("content-encoding")
185
+ kept = [(name, value) for name, value in headers if name.lower() not in dropped]
186
+ return (*kept, ("content-length", str(body_length)))
187
+
188
+
189
+ def _key_request(request: Mapping[str, JsonValue]) -> JsonValue:
190
+ return [
191
+ request.get(field_names.METHOD),
192
+ request.get(field_names.URL),
193
+ _key_body(_read_object(request, field_names.BODY)),
194
+ ]
195
+
196
+
197
+ def _key_body(description: Mapping[str, JsonValue]) -> JsonValue:
198
+ if not description:
199
+ return None
200
+ encoding = description.get(field_names.ENCODING)
201
+ data = description.get(field_names.DATA)
202
+ if encoding == field_names.TEXT and isinstance(data, str):
203
+ try:
204
+ parsed: JsonValue = json.loads(data)
205
+ except ValueError:
206
+ return [encoding, data]
207
+ return parsed
208
+ return [encoding, data]
209
+
210
+
211
+ def _replace_unserialisable(value: JsonValue) -> JsonValue:
212
+ if isinstance(value, list):
213
+ return [_replace_unserialisable(item) for item in value]
214
+ if not isinstance(value, dict):
215
+ return value
216
+ marker = value.get(RESERVED_KEY)
217
+ if marker == "unserialisable":
218
+ return None
219
+ if marker == LITERAL:
220
+ return value
221
+ return {name: _replace_unserialisable(item) for name, item in value.items()}
222
+
223
+
224
+ def _read_object(fields: Mapping[str, JsonValue], name: str) -> Mapping[str, JsonValue]:
225
+ value = fields.get(name)
226
+ return value if isinstance(value, dict) else {}
227
+
228
+
229
+ def _read_list(fields: Mapping[str, JsonValue], name: str) -> list[JsonValue]:
230
+ value = fields.get(name)
231
+ return value if isinstance(value, list) else []