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,52 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Sequence
|
|
4
|
+
|
|
5
|
+
from irimi._url_credentials import remove_userinfo
|
|
6
|
+
from irimi._wire import JsonValue, escape_reserved_key, mark_redacted
|
|
7
|
+
|
|
8
|
+
CREDENTIAL_HEADER_NAMES = frozenset(
|
|
9
|
+
{
|
|
10
|
+
"authorization",
|
|
11
|
+
"proxy-authorization",
|
|
12
|
+
"cookie",
|
|
13
|
+
"set-cookie",
|
|
14
|
+
"x-api-key",
|
|
15
|
+
"api-key",
|
|
16
|
+
"apikey",
|
|
17
|
+
"x-goog-api-key",
|
|
18
|
+
"x-auth-token",
|
|
19
|
+
"x-auth-key",
|
|
20
|
+
"x-amz-security-token",
|
|
21
|
+
"ocp-apim-subscription-key",
|
|
22
|
+
"x-functions-key",
|
|
23
|
+
"private-token",
|
|
24
|
+
"x-vault-token",
|
|
25
|
+
"x-shopify-access-token",
|
|
26
|
+
"dd-api-key",
|
|
27
|
+
}
|
|
28
|
+
)
|
|
29
|
+
URL_HEADER_NAMES = frozenset({"location"})
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def replace_credential_values(headers: Sequence[tuple[str, str]]) -> dict[str, JsonValue]:
|
|
33
|
+
return escape_reserved_key(
|
|
34
|
+
{name: _record_values(name, values) for name, values in _group_by_name(headers).items()}
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _group_by_name(headers: Sequence[tuple[str, str]]) -> dict[str, list[str]]:
|
|
39
|
+
first_spellings: dict[str, str] = {}
|
|
40
|
+
values_by_name: dict[str, list[str]] = {}
|
|
41
|
+
for name, value in headers:
|
|
42
|
+
spelling = first_spellings.setdefault(name.lower(), name)
|
|
43
|
+
values_by_name.setdefault(spelling, []).append(value)
|
|
44
|
+
return values_by_name
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _record_values(name: str, values: list[str]) -> JsonValue:
|
|
48
|
+
if name.lower() in CREDENTIAL_HEADER_NAMES:
|
|
49
|
+
return mark_redacted("credential")
|
|
50
|
+
if name.lower() in URL_HEADER_NAMES:
|
|
51
|
+
return ", ".join(remove_userinfo(value) for value in values)
|
|
52
|
+
return ", ".join(values)
|
irimi/_decorators.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import functools
|
|
4
|
+
import inspect
|
|
5
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any, TypeVar, cast, overload
|
|
8
|
+
|
|
9
|
+
from irimi._function_answers import (
|
|
10
|
+
FunctionAnswer,
|
|
11
|
+
ServedValue,
|
|
12
|
+
answer_function_call,
|
|
13
|
+
answer_undescribed_call,
|
|
14
|
+
answer_without_the_recording,
|
|
15
|
+
)
|
|
16
|
+
from irimi._labeled_calls import CallLabel, describe_output, describe_raised, describe_start
|
|
17
|
+
from irimi._recording import ActiveCall, Payload
|
|
18
|
+
from irimi._replay_decisions import Decision
|
|
19
|
+
from irimi._sdk import SDK, Recording, Replay
|
|
20
|
+
from irimi._wire import JsonValue
|
|
21
|
+
|
|
22
|
+
DecoratedFunction = TypeVar("DecoratedFunction", bound=Callable[..., Any])
|
|
23
|
+
Outcome = TypeVar("Outcome")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@overload
|
|
27
|
+
def workflow(fn: DecoratedFunction, /) -> DecoratedFunction: ...
|
|
28
|
+
@overload
|
|
29
|
+
def workflow(
|
|
30
|
+
*, name: str | None = None, id: str | None = None
|
|
31
|
+
) -> Callable[[DecoratedFunction], DecoratedFunction]: ...
|
|
32
|
+
def workflow(fn: Any = None, *, name: str | None = None, id: str | None = None) -> Any:
|
|
33
|
+
"""Mark a function as a workflow: each call is recorded as one run.
|
|
34
|
+
|
|
35
|
+
The function keeps its signature and behaviour, sync or async. Its arguments, its return
|
|
36
|
+
value or exception, and every labeled function called inside it are recorded. A workflow
|
|
37
|
+
called inside another workflow is a step of the outer run. Without `irimi.init` it does
|
|
38
|
+
nothing.
|
|
39
|
+
|
|
40
|
+
`name` is what the workflow is shown as and defaults to the function's name. `id` identifies
|
|
41
|
+
the workflow across renames; without one the name identifies it. Two workflows must not
|
|
42
|
+
share an id, or a name when neither sets an id.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
def decorate(function: DecoratedFunction) -> DecoratedFunction:
|
|
46
|
+
label = CallLabel(
|
|
47
|
+
kind="workflow",
|
|
48
|
+
name=name or function.__name__,
|
|
49
|
+
import_path=_import_path(function),
|
|
50
|
+
key=id,
|
|
51
|
+
)
|
|
52
|
+
SDK.register_workflow(label.name if label.key is None else label.key, label.import_path)
|
|
53
|
+
return _record_calls(function, label)
|
|
54
|
+
|
|
55
|
+
return decorate if fn is None else decorate(fn)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@overload
|
|
59
|
+
def function(fn: DecoratedFunction, /) -> DecoratedFunction: ...
|
|
60
|
+
@overload
|
|
61
|
+
def function(
|
|
62
|
+
*, name: str | None = None, write: bool = False, read: bool = False, fake: Any = ...
|
|
63
|
+
) -> Callable[[DecoratedFunction], DecoratedFunction]: ...
|
|
64
|
+
def function(
|
|
65
|
+
fn: Any = None,
|
|
66
|
+
*,
|
|
67
|
+
name: str | None = None,
|
|
68
|
+
write: bool = False,
|
|
69
|
+
read: bool = False,
|
|
70
|
+
fake: Any = ...,
|
|
71
|
+
) -> Any:
|
|
72
|
+
"""Record each call to a function as a step of the run it is called in.
|
|
73
|
+
|
|
74
|
+
The function keeps its signature and behaviour, sync or async. `name` identifies the step
|
|
75
|
+
and defaults to the function's name.
|
|
76
|
+
|
|
77
|
+
`write=True` marks a side effect irimi cannot see, such as a database write: in a replay
|
|
78
|
+
the function is not executed. `fake` is the value it returns in a replay when the recording
|
|
79
|
+
has no such call, and is `None` when not given. In a process the replay's workflow starts,
|
|
80
|
+
such as a `multiprocessing` worker, the function is not executed either and always returns
|
|
81
|
+
`fake`. `read=True` marks a read whose recorded value is served in a replay. `write` with
|
|
82
|
+
`read`, or `fake` without `write`, raises `TypeError`.
|
|
83
|
+
"""
|
|
84
|
+
if write and read:
|
|
85
|
+
raise TypeError("irimi.function: write=True and read=True cannot be combined")
|
|
86
|
+
if fake is not ... and not write:
|
|
87
|
+
raise TypeError("irimi.function: fake= needs write=True")
|
|
88
|
+
|
|
89
|
+
def decorate(function: DecoratedFunction) -> DecoratedFunction:
|
|
90
|
+
label = CallLabel(
|
|
91
|
+
kind="function",
|
|
92
|
+
name=name or function.__name__,
|
|
93
|
+
import_path=_import_path(function),
|
|
94
|
+
is_write=write,
|
|
95
|
+
is_read=read,
|
|
96
|
+
fake=fake,
|
|
97
|
+
)
|
|
98
|
+
return _record_calls(function, label)
|
|
99
|
+
|
|
100
|
+
return decorate if fn is None else decorate(fn)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _record_calls(function: DecoratedFunction, label: CallLabel) -> DecoratedFunction:
|
|
104
|
+
if inspect.iscoroutinefunction(function):
|
|
105
|
+
|
|
106
|
+
@functools.wraps(function)
|
|
107
|
+
async def record_async_call(*arguments: Any, **keyword_arguments: Any) -> Any:
|
|
108
|
+
opened = _begin_call(label, arguments, keyword_arguments)
|
|
109
|
+
if opened.served is not None:
|
|
110
|
+
return _end_served_call(opened, opened.served)
|
|
111
|
+
try:
|
|
112
|
+
output = await function(*arguments, **keyword_arguments)
|
|
113
|
+
except BaseException as error:
|
|
114
|
+
_end_call(opened, describe_raised, error)
|
|
115
|
+
raise
|
|
116
|
+
_end_call(opened, describe_output, output)
|
|
117
|
+
return output
|
|
118
|
+
|
|
119
|
+
return cast("DecoratedFunction", record_async_call)
|
|
120
|
+
|
|
121
|
+
@functools.wraps(function)
|
|
122
|
+
def record_call(*arguments: Any, **keyword_arguments: Any) -> Any:
|
|
123
|
+
opened = _begin_call(label, arguments, keyword_arguments)
|
|
124
|
+
if opened.served is not None:
|
|
125
|
+
return _end_served_call(opened, opened.served)
|
|
126
|
+
try:
|
|
127
|
+
output = function(*arguments, **keyword_arguments)
|
|
128
|
+
except BaseException as error:
|
|
129
|
+
_end_call(opened, describe_raised, error)
|
|
130
|
+
raise
|
|
131
|
+
_end_call(opened, describe_output, output)
|
|
132
|
+
return output
|
|
133
|
+
|
|
134
|
+
return cast("DecoratedFunction", record_call)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@dataclass(frozen=True)
|
|
138
|
+
class StartedCall:
|
|
139
|
+
call: ActiveCall
|
|
140
|
+
fields: Mapping[str, JsonValue]
|
|
141
|
+
is_root: bool
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
@dataclass(frozen=True)
|
|
145
|
+
class OpenLabeledCall:
|
|
146
|
+
call: ActiveCall | None
|
|
147
|
+
decision: Decision | None = None
|
|
148
|
+
served: ServedValue | None = None
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _begin_call(
|
|
152
|
+
label: CallLabel, arguments: Sequence[object], keyword_arguments: Mapping[str, object]
|
|
153
|
+
) -> OpenLabeledCall:
|
|
154
|
+
recording = SDK.recording
|
|
155
|
+
if recording is None:
|
|
156
|
+
return _begin_unrecorded_call(label)
|
|
157
|
+
started = _record_start(recording, label, arguments, keyword_arguments)
|
|
158
|
+
if recording.replay is None:
|
|
159
|
+
return OpenLabeledCall(started.call if started is not None else None)
|
|
160
|
+
return _begin_replayed_call(recording.replay, label, started)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _begin_unrecorded_call(label: CallLabel) -> OpenLabeledCall:
|
|
164
|
+
if not SDK.is_replay_worker():
|
|
165
|
+
return OpenLabeledCall(None)
|
|
166
|
+
SDK.warn_once_of_replay_worker()
|
|
167
|
+
return OpenLabeledCall(None, served=answer_without_the_recording(label))
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _record_start(
|
|
171
|
+
recording: Recording,
|
|
172
|
+
label: CallLabel,
|
|
173
|
+
arguments: Sequence[object],
|
|
174
|
+
keyword_arguments: Mapping[str, object],
|
|
175
|
+
) -> StartedCall | None:
|
|
176
|
+
try:
|
|
177
|
+
is_root = recording.recorder.find_current_call() is None
|
|
178
|
+
allowed_unpatched = (
|
|
179
|
+
recording.replay.allowed_unpatched if recording.replay is not None else ()
|
|
180
|
+
)
|
|
181
|
+
payload = describe_start(
|
|
182
|
+
label, arguments, keyword_arguments, recording.settings, is_root, allowed_unpatched
|
|
183
|
+
)
|
|
184
|
+
call = recording.recorder.begin_call(label.kind, label.name, payload)
|
|
185
|
+
return StartedCall(call, payload.fields, is_root)
|
|
186
|
+
except Exception:
|
|
187
|
+
SDK.report_failure("record the start of a call")
|
|
188
|
+
return None
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _begin_replayed_call(
|
|
192
|
+
replay: Replay, label: CallLabel, started: StartedCall | None
|
|
193
|
+
) -> OpenLabeledCall:
|
|
194
|
+
if started is None:
|
|
195
|
+
return _open_answered(
|
|
196
|
+
None, answer_undescribed_call(replay.decider, label, SDK.report_failure)
|
|
197
|
+
)
|
|
198
|
+
if started.is_root and label.kind == "workflow":
|
|
199
|
+
replay.started_runs.append(started.call.run.trace_id)
|
|
200
|
+
replay.running_workflow = started.call
|
|
201
|
+
return OpenLabeledCall(started.call)
|
|
202
|
+
try:
|
|
203
|
+
answer = answer_function_call(replay.decider, label, started.fields)
|
|
204
|
+
except Exception:
|
|
205
|
+
SDK.report_failure("decide a call in a replay")
|
|
206
|
+
answer = answer_undescribed_call(replay.decider, label, SDK.report_failure)
|
|
207
|
+
return _open_answered(started.call, answer)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _open_answered(call: ActiveCall | None, answer: FunctionAnswer) -> OpenLabeledCall:
|
|
211
|
+
return OpenLabeledCall(call, answer.decision, answer.served)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _end_served_call(opened: OpenLabeledCall, served: ServedValue) -> object:
|
|
215
|
+
_end_call(opened, describe_output, served.value)
|
|
216
|
+
return served.value
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _end_call(
|
|
220
|
+
opened: OpenLabeledCall,
|
|
221
|
+
describe_end: Callable[[Outcome, Decision | None], Payload],
|
|
222
|
+
outcome: Outcome,
|
|
223
|
+
) -> None:
|
|
224
|
+
recording = SDK.recording
|
|
225
|
+
if opened.call is None or recording is None:
|
|
226
|
+
return
|
|
227
|
+
if recording.replay is not None and recording.replay.running_workflow is opened.call:
|
|
228
|
+
recording.replay.running_workflow = None
|
|
229
|
+
try:
|
|
230
|
+
recording.recorder.end_call(opened.call, describe_end(outcome, opened.decision))
|
|
231
|
+
except Exception:
|
|
232
|
+
SDK.report_failure("record the end of a call")
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _import_path(function: Callable[..., Any]) -> str:
|
|
236
|
+
return f"{function.__module__}:{function.__qualname__}"
|
irimi/_delivery.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import functools
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Literal
|
|
6
|
+
|
|
7
|
+
from irimi._wire import (
|
|
8
|
+
EVENTS_PATH,
|
|
9
|
+
Batch,
|
|
10
|
+
Event,
|
|
11
|
+
JsonValue,
|
|
12
|
+
RefusedEvent,
|
|
13
|
+
parse_refused_events,
|
|
14
|
+
write_batch,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
REQUEST_TIMEOUT_SECONDS = 5.0
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class Delivery:
|
|
22
|
+
status: Literal["delivered", "refused", "failed"]
|
|
23
|
+
refused_events: tuple[RefusedEvent, ...] = ()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class Destination:
|
|
28
|
+
server_url: str
|
|
29
|
+
api_key: str | None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class ServerClient:
|
|
33
|
+
def __init__(self, destination: Destination) -> None:
|
|
34
|
+
self._events_url = destination.server_url.rstrip("/") + EVENTS_PATH
|
|
35
|
+
self._headers = {"Content-Type": "application/json"}
|
|
36
|
+
if destination.api_key:
|
|
37
|
+
self._headers["Authorization"] = f"Bearer {destination.api_key}"
|
|
38
|
+
|
|
39
|
+
def send_batch(self, events: tuple[Event, ...]) -> Delivery:
|
|
40
|
+
import http.client
|
|
41
|
+
import json
|
|
42
|
+
import urllib.error
|
|
43
|
+
import urllib.request
|
|
44
|
+
|
|
45
|
+
batch = Batch(events=events, fields={"sdk": self._sdk_description})
|
|
46
|
+
request = urllib.request.Request(
|
|
47
|
+
self._events_url,
|
|
48
|
+
data=json.dumps(write_batch(batch)).encode(),
|
|
49
|
+
headers=self._headers,
|
|
50
|
+
method="POST",
|
|
51
|
+
)
|
|
52
|
+
try:
|
|
53
|
+
with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as answer:
|
|
54
|
+
return Delivery("delivered", parse_refused_events(json.loads(answer.read())))
|
|
55
|
+
except urllib.error.HTTPError as error:
|
|
56
|
+
return Delivery("refused" if 400 <= error.code < 500 else "failed")
|
|
57
|
+
except ValueError:
|
|
58
|
+
return Delivery("refused")
|
|
59
|
+
except (OSError, http.client.HTTPException):
|
|
60
|
+
return Delivery("failed")
|
|
61
|
+
|
|
62
|
+
@functools.cached_property
|
|
63
|
+
def _sdk_description(self) -> dict[str, JsonValue]:
|
|
64
|
+
from importlib import metadata
|
|
65
|
+
|
|
66
|
+
try:
|
|
67
|
+
version = metadata.version("irimi-sdk")
|
|
68
|
+
except metadata.PackageNotFoundError:
|
|
69
|
+
version = "unknown"
|
|
70
|
+
return {"name": "irimi-python", "version": version}
|
irimi/_divergence.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import replace
|
|
4
|
+
from threading import Lock
|
|
5
|
+
|
|
6
|
+
from irimi._recorded_calls import RecordedCall
|
|
7
|
+
from irimi._replay_decisions import CandidateCall, Decides, Decision
|
|
8
|
+
from irimi._wire import field_names
|
|
9
|
+
from irimi._wire.call_roles import CallRole, is_write_role
|
|
10
|
+
|
|
11
|
+
READ_ROLES = frozenset({"http_read", "read_function"})
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class DivergenceFlagging:
|
|
15
|
+
def __init__(self, decider: Decides, calls: tuple[RecordedCall, ...]) -> None:
|
|
16
|
+
self._decider = decider
|
|
17
|
+
self._unmade_write_positions = {
|
|
18
|
+
call.span_id: call.seq for call in calls if is_write_role(call.role)
|
|
19
|
+
}
|
|
20
|
+
self._has_diverged = False
|
|
21
|
+
self._lock = Lock()
|
|
22
|
+
|
|
23
|
+
def decide(self, call: CandidateCall) -> Decision:
|
|
24
|
+
with self._lock:
|
|
25
|
+
decision = self._decider.decide(call)
|
|
26
|
+
self._watch(decision)
|
|
27
|
+
if self._has_diverged and _is_served_read(decision):
|
|
28
|
+
return replace(decision, flags=(*decision.flags, field_names.AFTER_DIVERGENCE))
|
|
29
|
+
return decision
|
|
30
|
+
|
|
31
|
+
def decide_undescribed_call(self, role: CallRole) -> Decision:
|
|
32
|
+
with self._lock:
|
|
33
|
+
self._has_diverged = True
|
|
34
|
+
return self._decider.decide_undescribed_call(role)
|
|
35
|
+
|
|
36
|
+
def _watch(self, decision: Decision) -> None:
|
|
37
|
+
if decision.answer == "recorded" and decision.matched is not None:
|
|
38
|
+
self._forget_inner_writes(decision.matched)
|
|
39
|
+
if is_write_role(decision.role):
|
|
40
|
+
self._watch_write(decision)
|
|
41
|
+
elif _is_served_read(decision) and decision.matched is not None:
|
|
42
|
+
self._watch_served_read(decision.matched)
|
|
43
|
+
|
|
44
|
+
def _watch_write(self, decision: Decision) -> None:
|
|
45
|
+
if decision.matched is None or decision.is_changed:
|
|
46
|
+
self._has_diverged = True
|
|
47
|
+
if decision.matched is not None:
|
|
48
|
+
self._unmade_write_positions.pop(decision.matched.span_id, None)
|
|
49
|
+
|
|
50
|
+
def _forget_inner_writes(self, answered: RecordedCall) -> None:
|
|
51
|
+
for span_id in answered.descendant_span_ids:
|
|
52
|
+
self._unmade_write_positions.pop(span_id, None)
|
|
53
|
+
|
|
54
|
+
def _watch_served_read(self, read: RecordedCall) -> None:
|
|
55
|
+
if any(seq < read.seq for seq in self._unmade_write_positions.values()):
|
|
56
|
+
self._has_diverged = True
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _is_served_read(decision: Decision) -> bool:
|
|
60
|
+
return decision.role in READ_ROLES and decision.answer == "recorded"
|
irimi/_drops.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
|
|
5
|
+
from irimi._atomic_total import AtomicTotal
|
|
6
|
+
|
|
7
|
+
logger = logging.getLogger("irimi")
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class DropTally:
|
|
11
|
+
def __init__(self) -> None:
|
|
12
|
+
self._count = AtomicTotal()
|
|
13
|
+
self._count_already_taken = 0
|
|
14
|
+
|
|
15
|
+
def record(self, count: int, warning: str, has_exception: bool = False) -> None:
|
|
16
|
+
is_first_drop = self._count.add(count) == count
|
|
17
|
+
if is_first_drop:
|
|
18
|
+
logger.warning(warning, exc_info=has_exception)
|
|
19
|
+
|
|
20
|
+
def take_new_count(self) -> int:
|
|
21
|
+
count = self._count.read()
|
|
22
|
+
new_count = count - self._count_already_taken
|
|
23
|
+
self._count_already_taken = count
|
|
24
|
+
return new_count
|
irimi/_errors.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from irimi._recording import Payload
|
|
4
|
+
from irimi._serialisation import name_type, serialise
|
|
5
|
+
from irimi._wire import JsonValue, field_names
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def describe_error(error: BaseException) -> Payload:
|
|
9
|
+
message = serialise(str(error))
|
|
10
|
+
fields: dict[str, JsonValue] = {
|
|
11
|
+
field_names.STATUS: "error",
|
|
12
|
+
field_names.ERROR: {"type": name_type(type(error)), "message": message.value},
|
|
13
|
+
}
|
|
14
|
+
return Payload(fields, message.approximate_size)
|
irimi/_exporter.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import atexit
|
|
4
|
+
import os
|
|
5
|
+
import queue
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
from collections import deque
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
|
|
12
|
+
from irimi._atomic_total import AtomicTotal
|
|
13
|
+
from irimi._delivery import Delivery
|
|
14
|
+
from irimi._drops import DropTally
|
|
15
|
+
from irimi._wire import Event
|
|
16
|
+
|
|
17
|
+
QUEUE_LIMIT = 10_000
|
|
18
|
+
QUEUE_SIZE_LIMIT = 64 * 1024 * 1024
|
|
19
|
+
BATCH_SIZE = 100
|
|
20
|
+
BATCH_SIZE_LIMIT = 8 * 1024 * 1024
|
|
21
|
+
SEND_INTERVAL_SECONDS = 1.0
|
|
22
|
+
SEND_ATTEMPTS = 3
|
|
23
|
+
RETRY_DELAY_SECONDS = 0.2
|
|
24
|
+
EXIT_FLUSH_SECONDS = 5.0
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class _Offer:
|
|
29
|
+
event: Event
|
|
30
|
+
approximate_size: int
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class _FlushRequest:
|
|
35
|
+
is_reached: threading.Event = field(default_factory=threading.Event)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Exporter:
|
|
39
|
+
def __init__(
|
|
40
|
+
self, send_batch: Callable[[tuple[Event, ...]], Delivery], drops: DropTally
|
|
41
|
+
) -> None:
|
|
42
|
+
self._send_batch = send_batch
|
|
43
|
+
self._drops = drops
|
|
44
|
+
self._offers: queue.SimpleQueue[_Offer | _FlushRequest]
|
|
45
|
+
self._offers_made: AtomicTotal
|
|
46
|
+
self._sender_claims: AtomicTotal
|
|
47
|
+
self._waiting_count: AtomicTotal
|
|
48
|
+
self._waiting_size: AtomicTotal
|
|
49
|
+
self._flushes_waiting: AtomicTotal
|
|
50
|
+
self._sender_wakes: queue.SimpleQueue[None]
|
|
51
|
+
self._received: deque[_Offer | _FlushRequest]
|
|
52
|
+
self._reset()
|
|
53
|
+
atexit.register(self.flush, EXIT_FLUSH_SECONDS)
|
|
54
|
+
if hasattr(os, "register_at_fork"):
|
|
55
|
+
os.register_at_fork(after_in_child=self._reset)
|
|
56
|
+
|
|
57
|
+
def enqueue(self, event: Event, approximate_size: int) -> None:
|
|
58
|
+
waiting_count = self._waiting_count.add(1)
|
|
59
|
+
waiting_size = self._waiting_size.add(approximate_size)
|
|
60
|
+
if waiting_count > QUEUE_LIMIT or waiting_size > QUEUE_SIZE_LIMIT:
|
|
61
|
+
self._waiting_count.add(-1)
|
|
62
|
+
self._waiting_size.add(-approximate_size)
|
|
63
|
+
self._drops.record(1, "irimi events were dropped: too many are waiting to be sent")
|
|
64
|
+
return
|
|
65
|
+
self._offers.put(_Offer(event, approximate_size))
|
|
66
|
+
self._offers_made.add(1)
|
|
67
|
+
self._start_sender_if_none_runs()
|
|
68
|
+
if waiting_count >= BATCH_SIZE or waiting_size >= BATCH_SIZE_LIMIT:
|
|
69
|
+
self._wake_sender()
|
|
70
|
+
|
|
71
|
+
def flush(self, timeout: float | None = None) -> bool:
|
|
72
|
+
if self._offers_made.read() == 0:
|
|
73
|
+
return True
|
|
74
|
+
self._start_sender_if_none_runs()
|
|
75
|
+
request = _FlushRequest()
|
|
76
|
+
self._flushes_waiting.add(1)
|
|
77
|
+
try:
|
|
78
|
+
self._offers.put(request)
|
|
79
|
+
self._wake_sender()
|
|
80
|
+
return request.is_reached.wait(timeout)
|
|
81
|
+
finally:
|
|
82
|
+
self._flushes_waiting.add(-1)
|
|
83
|
+
|
|
84
|
+
def _reset(self) -> None:
|
|
85
|
+
self._offers = queue.SimpleQueue()
|
|
86
|
+
self._offers_made = AtomicTotal()
|
|
87
|
+
self._sender_claims = AtomicTotal()
|
|
88
|
+
self._waiting_count = AtomicTotal()
|
|
89
|
+
self._waiting_size = AtomicTotal()
|
|
90
|
+
self._flushes_waiting = AtomicTotal()
|
|
91
|
+
self._sender_wakes = queue.SimpleQueue()
|
|
92
|
+
self._received = deque()
|
|
93
|
+
|
|
94
|
+
def _start_sender_if_none_runs(self) -> None:
|
|
95
|
+
if self._sender_claims.read() == 0:
|
|
96
|
+
threading.Thread(
|
|
97
|
+
target=self._send_as_the_only_sender, name="irimi-export", daemon=True
|
|
98
|
+
).start()
|
|
99
|
+
|
|
100
|
+
def _send_as_the_only_sender(self) -> None:
|
|
101
|
+
if self._sender_claims.add(1) == 1:
|
|
102
|
+
self._send_forever()
|
|
103
|
+
|
|
104
|
+
def _wake_sender(self) -> None:
|
|
105
|
+
if self._sender_wakes.empty():
|
|
106
|
+
self._sender_wakes.put(None)
|
|
107
|
+
|
|
108
|
+
def _send_forever(self) -> None:
|
|
109
|
+
while True:
|
|
110
|
+
self._wait_until_send_is_due()
|
|
111
|
+
self._receive_offers()
|
|
112
|
+
events, flushes_reached = self._take_batch()
|
|
113
|
+
if events:
|
|
114
|
+
self._deliver(events)
|
|
115
|
+
for flush in flushes_reached:
|
|
116
|
+
flush.is_reached.set()
|
|
117
|
+
|
|
118
|
+
def _wait_until_send_is_due(self) -> None:
|
|
119
|
+
if not self._received:
|
|
120
|
+
self._received.append(self._offers.get())
|
|
121
|
+
deadline = time.monotonic() + SEND_INTERVAL_SECONDS
|
|
122
|
+
while not self._is_send_due():
|
|
123
|
+
try:
|
|
124
|
+
self._sender_wakes.get(timeout=max(0.0, deadline - time.monotonic()))
|
|
125
|
+
except queue.Empty:
|
|
126
|
+
return
|
|
127
|
+
|
|
128
|
+
def _is_send_due(self) -> bool:
|
|
129
|
+
return (
|
|
130
|
+
self._waiting_count.read() >= BATCH_SIZE
|
|
131
|
+
or self._waiting_size.read() >= BATCH_SIZE_LIMIT
|
|
132
|
+
or self._flushes_waiting.read() > 0
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
def _receive_offers(self) -> None:
|
|
136
|
+
while True:
|
|
137
|
+
try:
|
|
138
|
+
self._received.append(self._offers.get_nowait())
|
|
139
|
+
except queue.Empty:
|
|
140
|
+
return
|
|
141
|
+
|
|
142
|
+
def _take_batch(self) -> tuple[tuple[Event, ...], tuple[_FlushRequest, ...]]:
|
|
143
|
+
events: list[Event] = []
|
|
144
|
+
flushes_reached: list[_FlushRequest] = []
|
|
145
|
+
batch_size = 0
|
|
146
|
+
while self._received:
|
|
147
|
+
offer = self._received[0]
|
|
148
|
+
if isinstance(offer, _FlushRequest):
|
|
149
|
+
flushes_reached.append(offer)
|
|
150
|
+
elif _has_room(len(events), batch_size, offer.approximate_size):
|
|
151
|
+
events.append(offer.event)
|
|
152
|
+
batch_size += offer.approximate_size
|
|
153
|
+
else:
|
|
154
|
+
break
|
|
155
|
+
self._received.popleft()
|
|
156
|
+
self._waiting_count.add(-len(events))
|
|
157
|
+
self._waiting_size.add(-batch_size)
|
|
158
|
+
return tuple(events), tuple(flushes_reached)
|
|
159
|
+
|
|
160
|
+
def _deliver(self, batch: tuple[Event, ...]) -> None:
|
|
161
|
+
try:
|
|
162
|
+
delivery = self._send_with_retries(batch)
|
|
163
|
+
except Exception:
|
|
164
|
+
self._drops.record(
|
|
165
|
+
len(batch), "irimi could not send a batch of events; they were dropped", True
|
|
166
|
+
)
|
|
167
|
+
return
|
|
168
|
+
if delivery.status != "delivered":
|
|
169
|
+
self._drops.record(
|
|
170
|
+
len(batch),
|
|
171
|
+
f"irimi events were dropped: sending a batch to the server {delivery.status}",
|
|
172
|
+
)
|
|
173
|
+
elif delivery.refused_events:
|
|
174
|
+
self._drops.record(
|
|
175
|
+
len(delivery.refused_events),
|
|
176
|
+
f"irimi events were dropped: the server refused {len(delivery.refused_events)}, "
|
|
177
|
+
f"the first because {delivery.refused_events[0].reason}",
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
def _send_with_retries(self, batch: tuple[Event, ...]) -> Delivery:
|
|
181
|
+
delivery = self._send_batch(batch)
|
|
182
|
+
for attempt in range(1, SEND_ATTEMPTS):
|
|
183
|
+
if delivery.status != "failed":
|
|
184
|
+
break
|
|
185
|
+
time.sleep(RETRY_DELAY_SECONDS * attempt)
|
|
186
|
+
delivery = self._send_batch(batch)
|
|
187
|
+
return delivery
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _has_room(batch_count: int, batch_size: int, next_size: int) -> bool:
|
|
191
|
+
if batch_count == 0:
|
|
192
|
+
return True
|
|
193
|
+
return batch_count < BATCH_SIZE and batch_size + next_size <= BATCH_SIZE_LIMIT
|