irimi-sdk 0.2.0.dev0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- irimi/__init__.py +4 -0
- irimi/_aiohttp_patch.py +371 -0
- irimi/_aiohttp_serving.py +216 -0
- irimi/_atomic_total.py +14 -0
- irimi/_bodies.py +64 -0
- irimi/_credential_headers.py +52 -0
- irimi/_decorators.py +236 -0
- irimi/_delivery.py +70 -0
- irimi/_divergence.py +60 -0
- irimi/_drops.py +24 -0
- irimi/_errors.py +14 -0
- irimi/_exporter.py +193 -0
- irimi/_function_answers.py +87 -0
- irimi/_git.py +37 -0
- irimi/_httpx_patch.py +236 -0
- irimi/_interception.py +174 -0
- irimi/_labeled_calls.py +116 -0
- irimi/_llm_providers.py +57 -0
- irimi/_object_fields.py +32 -0
- irimi/_outbound_calls.py +190 -0
- irimi/_patching.py +58 -0
- irimi/_rebuilding.py +97 -0
- irimi/_recorded_calls.py +231 -0
- irimi/_recording.py +122 -0
- irimi/_recording_loader.py +63 -0
- irimi/_replay_child.py +156 -0
- irimi/_replay_decisions.py +120 -0
- irimi/_replay_fields.py +16 -0
- irimi/_replay_proxy.py +328 -0
- irimi/_replay_refusals.py +5 -0
- irimi/_response_recording.py +74 -0
- irimi/_sdk.py +318 -0
- irimi/_serialisation.py +114 -0
- irimi/_status_reasons.py +10 -0
- irimi/_unpatched_clients.py +105 -0
- irimi/_url_credentials.py +11 -0
- irimi/_urllib3_patch.py +465 -0
- irimi/_urllib3_serving.py +81 -0
- irimi/_wire/__init__.py +56 -0
- irimi/_wire/call_roles.py +32 -0
- irimi/_wire/events.py +209 -0
- irimi/_wire/field_names.py +80 -0
- irimi/_wire/json_value.py +3 -0
- irimi/_wire/markers.py +49 -0
- irimi/py.typed +0 -0
- irimi_sdk-0.2.0.dev0.dist-info/METADATA +81 -0
- irimi_sdk-0.2.0.dev0.dist-info/RECORD +48 -0
- irimi_sdk-0.2.0.dev0.dist-info/WHEEL +4 -0
irimi/_sdk.py
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
import threading
|
|
6
|
+
import time
|
|
7
|
+
from collections.abc import Iterable, Mapping, Sequence
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Literal
|
|
11
|
+
|
|
12
|
+
from irimi._delivery import Destination, ServerClient
|
|
13
|
+
from irimi._divergence import DivergenceFlagging
|
|
14
|
+
from irimi._drops import DropTally
|
|
15
|
+
from irimi._exporter import Exporter
|
|
16
|
+
from irimi._git import find_commit
|
|
17
|
+
from irimi._interception import Interception, TracksLiveCalls
|
|
18
|
+
from irimi._labeled_calls import RunSettings
|
|
19
|
+
from irimi._patching import patch_installed_libraries
|
|
20
|
+
from irimi._recorded_calls import NotReplayableError, RecordedRun, read_recorded_run
|
|
21
|
+
from irimi._recording import ActiveCall, Recorder
|
|
22
|
+
from irimi._recording_loader import load_recorded_events
|
|
23
|
+
from irimi._replay_decisions import Decides, ReplayDecider
|
|
24
|
+
from irimi._replay_refusals import ReplayRefusal
|
|
25
|
+
|
|
26
|
+
logger = logging.getLogger("irimi")
|
|
27
|
+
|
|
28
|
+
SERVER_URL_VARIABLE = "IRIMI_SERVER_URL"
|
|
29
|
+
REPLAY_RUN_VARIABLE = "IRIMI_REPLAY_RUN_ID"
|
|
30
|
+
REPLAY_RESULT_VARIABLE = "IRIMI_REPLAY_RESULT_PATH"
|
|
31
|
+
IGNORED_CLIENT_NAME_WARNING = (
|
|
32
|
+
"irimi.init ignored a dangerously_allow_unpatched value that is not a client name"
|
|
33
|
+
)
|
|
34
|
+
REPLAY_FAILURE_CONSEQUENCE = (
|
|
35
|
+
"the replay carries on, faking any call irimi could not decide, "
|
|
36
|
+
"and its recording may be incomplete"
|
|
37
|
+
)
|
|
38
|
+
REPLAY_WORKER_WARNING = (
|
|
39
|
+
"irimi is inside a worker process of a replay: labeled writes here are faked, "
|
|
40
|
+
"and nothing here is recorded"
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class InitResult:
|
|
46
|
+
"""What `irimi.init` set up.
|
|
47
|
+
|
|
48
|
+
`mode` is "normal" when runs are recorded and "shadow" inside a replay. `patched` names the
|
|
49
|
+
client libraries irimi intercepts, and `unpatched` names the ones it saw and does not.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
mode: Literal["normal", "shadow"]
|
|
53
|
+
patched: tuple[str, ...]
|
|
54
|
+
unpatched: tuple[str, ...]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass(frozen=True)
|
|
58
|
+
class InitArguments:
|
|
59
|
+
server_url: str | None
|
|
60
|
+
api_key: str | None
|
|
61
|
+
version: str | None
|
|
62
|
+
environment: str | None
|
|
63
|
+
dangerously_allow_unpatched: tuple[str, ...]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class Replay:
|
|
67
|
+
def __init__(self, source_run: str, decider: Decides, interception: Interception) -> None:
|
|
68
|
+
self.source_run = source_run
|
|
69
|
+
self.decider = decider
|
|
70
|
+
self.interception = interception
|
|
71
|
+
self.running_workflow: ActiveCall | None = None
|
|
72
|
+
self.started_runs: list[str] = []
|
|
73
|
+
self.allowed_unpatched: set[str] = set()
|
|
74
|
+
self.unpatched_libraries: tuple[str, ...] = ()
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@dataclass(frozen=True)
|
|
78
|
+
class Recording:
|
|
79
|
+
recorder: Recorder
|
|
80
|
+
settings: RunSettings
|
|
81
|
+
replay: Replay | None = None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
NORMAL_RUN = InitResult(mode="normal", patched=(), unpatched=())
|
|
85
|
+
REPLAY_WORKER = InitResult(mode="shadow", patched=(), unpatched=())
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class Sdk:
|
|
89
|
+
def __init__(self, environment_variables: Mapping[str, str]) -> None:
|
|
90
|
+
self.recording: Recording | None = None
|
|
91
|
+
self._is_inside_replay = bool(environment_variables.get(REPLAY_RUN_VARIABLE))
|
|
92
|
+
self._has_warned_of_replay_worker = False
|
|
93
|
+
self._lock = threading.Lock()
|
|
94
|
+
self._exporter: Exporter | None = None
|
|
95
|
+
self._first_arguments: InitArguments | None = None
|
|
96
|
+
self._first_result = NORMAL_RUN
|
|
97
|
+
self._workflow_import_paths: dict[str, str] = {}
|
|
98
|
+
self._registered_workflows: set[str] = set()
|
|
99
|
+
self._drops = DropTally()
|
|
100
|
+
|
|
101
|
+
def init(
|
|
102
|
+
self,
|
|
103
|
+
arguments: InitArguments,
|
|
104
|
+
environment_variables: Mapping[str, str],
|
|
105
|
+
working_directory: Path,
|
|
106
|
+
) -> InitResult:
|
|
107
|
+
with self._lock:
|
|
108
|
+
replay = self.recording.replay if self.recording is not None else None
|
|
109
|
+
if replay is not None:
|
|
110
|
+
replay.allowed_unpatched.update(arguments.dangerously_allow_unpatched)
|
|
111
|
+
return self._first_result
|
|
112
|
+
if not self._is_inside_replay:
|
|
113
|
+
return self._init_once(arguments, environment_variables, working_directory)
|
|
114
|
+
self.warn_once_of_replay_worker()
|
|
115
|
+
return REPLAY_WORKER
|
|
116
|
+
|
|
117
|
+
def is_replay_worker(self) -> bool:
|
|
118
|
+
return self._is_inside_replay and not self._is_replaying
|
|
119
|
+
|
|
120
|
+
def warn_once_of_replay_worker(self) -> None:
|
|
121
|
+
with self._lock:
|
|
122
|
+
is_first_warning = not self._has_warned_of_replay_worker
|
|
123
|
+
self._has_warned_of_replay_worker = True
|
|
124
|
+
if is_first_warning:
|
|
125
|
+
logger.warning(REPLAY_WORKER_WARNING)
|
|
126
|
+
|
|
127
|
+
def start_replay(
|
|
128
|
+
self,
|
|
129
|
+
environment_variables: Mapping[str, str],
|
|
130
|
+
working_directory: Path,
|
|
131
|
+
live_calls: TracksLiveCalls | None = None,
|
|
132
|
+
) -> tuple[RecordedRun, Replay]:
|
|
133
|
+
with self._lock:
|
|
134
|
+
if self._is_replaying or self._first_arguments is not None:
|
|
135
|
+
raise ReplayRefusal("irimi was initialised before the replay started")
|
|
136
|
+
destination = Destination(
|
|
137
|
+
server_url=_require(environment_variables, SERVER_URL_VARIABLE),
|
|
138
|
+
api_key=environment_variables.get("IRIMI_API_KEY"),
|
|
139
|
+
)
|
|
140
|
+
source_run = _require(environment_variables, REPLAY_RUN_VARIABLE)
|
|
141
|
+
recorded_run = _read_replayable_run(destination, source_run)
|
|
142
|
+
settings = RunSettings(
|
|
143
|
+
environment=environment_variables.get("IRIMI_ENVIRONMENT"),
|
|
144
|
+
version=environment_variables.get("IRIMI_VERSION"),
|
|
145
|
+
commit=find_commit(working_directory),
|
|
146
|
+
replay_source_run=source_run,
|
|
147
|
+
)
|
|
148
|
+
decider = DivergenceFlagging(ReplayDecider(recorded_run.calls), recorded_run.calls)
|
|
149
|
+
recorder = self._start_exporting(destination)
|
|
150
|
+
interception = Interception(recorder, self.report_failure, decider, live_calls)
|
|
151
|
+
replay = Replay(source_run, decider, interception)
|
|
152
|
+
report = patch_installed_libraries(interception)
|
|
153
|
+
self.recording = Recording(recorder, settings, replay)
|
|
154
|
+
replay.unpatched_libraries = report.unpatched
|
|
155
|
+
self._first_result = InitResult(
|
|
156
|
+
mode="shadow", patched=report.patched, unpatched=report.unpatched
|
|
157
|
+
)
|
|
158
|
+
return recorded_run, replay
|
|
159
|
+
|
|
160
|
+
def flush(self, timeout: float | None) -> bool:
|
|
161
|
+
is_drained = self._exporter is None or self._exporter.flush(timeout)
|
|
162
|
+
return is_drained and self._drops.take_new_count() == 0
|
|
163
|
+
|
|
164
|
+
def register_workflow(self, workflow_id: str, import_path: str) -> None:
|
|
165
|
+
with self._lock:
|
|
166
|
+
self._registered_workflows.add(import_path)
|
|
167
|
+
registered_path = self._workflow_import_paths.setdefault(workflow_id, import_path)
|
|
168
|
+
if registered_path != import_path:
|
|
169
|
+
logger.warning(
|
|
170
|
+
"two irimi workflows share the id %r: %s and %s; set a different id= on each",
|
|
171
|
+
workflow_id,
|
|
172
|
+
registered_path,
|
|
173
|
+
import_path,
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
def is_registered_workflow(self, import_path: str) -> bool:
|
|
177
|
+
with self._lock:
|
|
178
|
+
return import_path in self._registered_workflows
|
|
179
|
+
|
|
180
|
+
def report_failure(self, action: str) -> None:
|
|
181
|
+
consequence = REPLAY_FAILURE_CONSEQUENCE if self._is_replaying else "the app is unaffected"
|
|
182
|
+
self._drops.record(1, f"irimi failed to {action}; {consequence}", True)
|
|
183
|
+
|
|
184
|
+
def _init_once(
|
|
185
|
+
self,
|
|
186
|
+
arguments: InitArguments,
|
|
187
|
+
environment_variables: Mapping[str, str],
|
|
188
|
+
working_directory: Path,
|
|
189
|
+
) -> InitResult:
|
|
190
|
+
if self._first_arguments is not None:
|
|
191
|
+
if arguments != self._first_arguments:
|
|
192
|
+
logger.warning("irimi.init was called again with different arguments; ignored")
|
|
193
|
+
return self._first_result
|
|
194
|
+
self._first_arguments = arguments
|
|
195
|
+
self._first_result = self._start_recording(
|
|
196
|
+
arguments, environment_variables, working_directory
|
|
197
|
+
)
|
|
198
|
+
return self._first_result
|
|
199
|
+
|
|
200
|
+
def _start_recording(
|
|
201
|
+
self,
|
|
202
|
+
arguments: InitArguments,
|
|
203
|
+
environment_variables: Mapping[str, str],
|
|
204
|
+
working_directory: Path,
|
|
205
|
+
) -> InitResult:
|
|
206
|
+
server_url = arguments.server_url or environment_variables.get(SERVER_URL_VARIABLE)
|
|
207
|
+
if not server_url:
|
|
208
|
+
logger.warning(
|
|
209
|
+
"irimi has no server URL, so nothing is recorded; set %s", SERVER_URL_VARIABLE
|
|
210
|
+
)
|
|
211
|
+
return NORMAL_RUN
|
|
212
|
+
destination = Destination(
|
|
213
|
+
server_url=server_url,
|
|
214
|
+
api_key=arguments.api_key or environment_variables.get("IRIMI_API_KEY"),
|
|
215
|
+
)
|
|
216
|
+
settings = RunSettings(
|
|
217
|
+
environment=arguments.environment or environment_variables.get("IRIMI_ENVIRONMENT"),
|
|
218
|
+
version=arguments.version or environment_variables.get("IRIMI_VERSION"),
|
|
219
|
+
commit=find_commit(working_directory),
|
|
220
|
+
)
|
|
221
|
+
recorder = self._start_exporting(destination)
|
|
222
|
+
report = patch_installed_libraries(Interception(recorder, self.report_failure))
|
|
223
|
+
self.recording = Recording(recorder, settings)
|
|
224
|
+
return InitResult(mode="normal", patched=report.patched, unpatched=report.unpatched)
|
|
225
|
+
|
|
226
|
+
def _start_exporting(self, destination: Destination) -> Recorder:
|
|
227
|
+
self._exporter = Exporter(ServerClient(destination).send_batch, self._drops)
|
|
228
|
+
return Recorder(self._exporter.enqueue, time.time_ns)
|
|
229
|
+
|
|
230
|
+
@property
|
|
231
|
+
def _is_replaying(self) -> bool:
|
|
232
|
+
return self.recording is not None and self.recording.replay is not None
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _require(environment_variables: Mapping[str, str], name: str) -> str:
|
|
236
|
+
value = environment_variables.get(name)
|
|
237
|
+
if not value:
|
|
238
|
+
raise ReplayRefusal(f"a replay needs {name} to be set")
|
|
239
|
+
return value
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _read_replayable_run(destination: Destination, source_run: str) -> RecordedRun:
|
|
243
|
+
events = load_recorded_events(destination, source_run)
|
|
244
|
+
try:
|
|
245
|
+
return read_recorded_run(events)
|
|
246
|
+
except NotReplayableError as error:
|
|
247
|
+
raise ReplayRefusal(f"run {source_run} cannot be replayed: {error}") from error
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
SDK = Sdk(os.environ)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def init(
|
|
254
|
+
*,
|
|
255
|
+
server_url: str | None = None,
|
|
256
|
+
api_key: str | None = None,
|
|
257
|
+
version: str | None = None,
|
|
258
|
+
environment: str | None = None,
|
|
259
|
+
dangerously_allow_unpatched: Sequence[str] = (),
|
|
260
|
+
) -> InitResult:
|
|
261
|
+
"""Start recording workflow runs and sending them to the irimi server.
|
|
262
|
+
|
|
263
|
+
Call it once, at startup. Each argument falls back to an environment variable:
|
|
264
|
+
`IRIMI_SERVER_URL`, `IRIMI_API_KEY`, `IRIMI_VERSION` and `IRIMI_ENVIRONMENT`. Without a server
|
|
265
|
+
URL nothing is recorded. `version` names the deployment and falls back to the git commit.
|
|
266
|
+
|
|
267
|
+
A replay stops when it finds a client irimi cannot intercept, such as a database driver: once
|
|
268
|
+
the workflow's module has been imported, and again whenever the workflow imports one later.
|
|
269
|
+
A client irimi does not know by name is not caught. `dangerously_allow_unpatched` names the
|
|
270
|
+
clients a replay may run with anyway, once every write through them is labeled
|
|
271
|
+
`@irimi.function(write=True)`. It has no effect outside a replay.
|
|
272
|
+
|
|
273
|
+
In a process a replay's workflow starts, such as a `multiprocessing` worker, it records
|
|
274
|
+
nothing and returns mode "shadow".
|
|
275
|
+
|
|
276
|
+
It never raises and never blocks: if the server cannot be reached, recording is dropped and
|
|
277
|
+
the app carries on. A second call is ignored.
|
|
278
|
+
"""
|
|
279
|
+
try:
|
|
280
|
+
arguments = InitArguments(
|
|
281
|
+
server_url=server_url,
|
|
282
|
+
api_key=api_key,
|
|
283
|
+
version=version,
|
|
284
|
+
environment=environment,
|
|
285
|
+
dangerously_allow_unpatched=_read_client_names(dangerously_allow_unpatched),
|
|
286
|
+
)
|
|
287
|
+
return SDK.init(arguments, os.environ, Path.cwd())
|
|
288
|
+
except Exception:
|
|
289
|
+
SDK.report_failure("initialise")
|
|
290
|
+
return NORMAL_RUN
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _read_client_names(names: object) -> tuple[str, ...]:
|
|
294
|
+
if isinstance(names, str):
|
|
295
|
+
return (names,)
|
|
296
|
+
try:
|
|
297
|
+
listed = tuple(names) if isinstance(names, Iterable) else (names,)
|
|
298
|
+
except Exception:
|
|
299
|
+
listed = (names,)
|
|
300
|
+
client_names = tuple(name for name in listed if isinstance(name, str))
|
|
301
|
+
if len(client_names) < len(listed):
|
|
302
|
+
logger.warning(IGNORED_CLIENT_NAME_WARNING)
|
|
303
|
+
return client_names
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def flush(timeout: float | None = None) -> bool:
|
|
307
|
+
"""Wait until everything recorded so far has been sent to the irimi server.
|
|
308
|
+
|
|
309
|
+
Returns whether everything was sent within `timeout` seconds; with no timeout it waits until
|
|
310
|
+
sending finishes or fails. It never raises. Sending already happens in the background and
|
|
311
|
+
at exit, so this is only needed where the process is frozen after a handler returns, as on
|
|
312
|
+
serverless platforms.
|
|
313
|
+
"""
|
|
314
|
+
try:
|
|
315
|
+
return SDK.flush(timeout)
|
|
316
|
+
except Exception:
|
|
317
|
+
SDK.report_failure("flush")
|
|
318
|
+
return False
|
irimi/_serialisation.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
from collections.abc import Mapping, Sequence
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
from irimi._object_fields import keeps_state_outside_attributes, read_fields
|
|
8
|
+
from irimi._wire import (
|
|
9
|
+
JsonValue,
|
|
10
|
+
escape_reserved_key,
|
|
11
|
+
field_names,
|
|
12
|
+
mark_object,
|
|
13
|
+
mark_unserialisable,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
SIZE_OF_A_SMALL_VALUE = 8
|
|
17
|
+
PLAIN_TYPES = frozenset({str, int, float, bool, type(None), list, tuple, dict})
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class Serialised:
|
|
22
|
+
value: JsonValue
|
|
23
|
+
is_complete: bool
|
|
24
|
+
approximate_size: int
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def serialise(value: object) -> Serialised:
|
|
28
|
+
snapshot = _Snapshot()
|
|
29
|
+
try:
|
|
30
|
+
taken = snapshot.take(value)
|
|
31
|
+
except RecursionError:
|
|
32
|
+
return Serialised(
|
|
33
|
+
mark_unserialisable(name_type(type(value))), is_complete=False, approximate_size=0
|
|
34
|
+
)
|
|
35
|
+
return Serialised(taken, snapshot.is_complete, snapshot.approximate_size)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def serialise_arguments(
|
|
39
|
+
arguments: Sequence[object], keyword_arguments: Mapping[str, object]
|
|
40
|
+
) -> Serialised:
|
|
41
|
+
return serialise(
|
|
42
|
+
{field_names.ARGS: list(arguments), field_names.KWARGS: dict(keyword_arguments)}
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def name_type(named: type) -> str:
|
|
47
|
+
return f"{named.__module__}.{named.__qualname__}"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _is_whole_text(text: str) -> bool:
|
|
51
|
+
if text.isascii():
|
|
52
|
+
return True
|
|
53
|
+
try:
|
|
54
|
+
text.encode()
|
|
55
|
+
except UnicodeEncodeError:
|
|
56
|
+
return False
|
|
57
|
+
return True
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _has_whole_names(items: dict[str, object]) -> bool:
|
|
61
|
+
return all(isinstance(name, str) and _is_whole_text(name) for name in items)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class _Snapshot:
|
|
65
|
+
def __init__(self) -> None:
|
|
66
|
+
self.is_complete = True
|
|
67
|
+
self.approximate_size = 0
|
|
68
|
+
|
|
69
|
+
def take(self, value: object) -> JsonValue:
|
|
70
|
+
try:
|
|
71
|
+
is_exactly_plain = type(value) in PLAIN_TYPES
|
|
72
|
+
except Exception:
|
|
73
|
+
is_exactly_plain = False
|
|
74
|
+
if not is_exactly_plain:
|
|
75
|
+
try:
|
|
76
|
+
fields = read_fields(value)
|
|
77
|
+
if fields is not None and keeps_state_outside_attributes(type(value)):
|
|
78
|
+
return self._record_by_type(value)
|
|
79
|
+
except RecursionError:
|
|
80
|
+
raise
|
|
81
|
+
except Exception:
|
|
82
|
+
return self._record_by_type(value)
|
|
83
|
+
if fields is not None:
|
|
84
|
+
return self._take_fields(value, fields)
|
|
85
|
+
if isinstance(value, str):
|
|
86
|
+
if not _is_whole_text(value):
|
|
87
|
+
return self._record_by_type(value)
|
|
88
|
+
self.approximate_size += len(value)
|
|
89
|
+
return value
|
|
90
|
+
if value is None or isinstance(value, int):
|
|
91
|
+
return value
|
|
92
|
+
if isinstance(value, float):
|
|
93
|
+
return value if math.isfinite(value) else self._record_by_type(value)
|
|
94
|
+
if isinstance(value, (list, tuple)):
|
|
95
|
+
self.approximate_size += SIZE_OF_A_SMALL_VALUE * len(value)
|
|
96
|
+
return [self.take(item) for item in value]
|
|
97
|
+
if isinstance(value, dict) and _has_whole_names(value):
|
|
98
|
+
return self._take_object(value)
|
|
99
|
+
return self._record_by_type(value)
|
|
100
|
+
|
|
101
|
+
def _take_fields(self, value: object, fields: dict[str, object]) -> JsonValue:
|
|
102
|
+
if not _has_whole_names(fields):
|
|
103
|
+
return self._record_by_type(value)
|
|
104
|
+
type_name = name_type(type(value))
|
|
105
|
+
self.approximate_size += len(type_name) + SIZE_OF_A_SMALL_VALUE
|
|
106
|
+
return mark_object(type_name, self._take_object(fields))
|
|
107
|
+
|
|
108
|
+
def _take_object(self, items: dict[str, object]) -> JsonValue:
|
|
109
|
+
self.approximate_size += sum(map(len, items)) + SIZE_OF_A_SMALL_VALUE * len(items)
|
|
110
|
+
return escape_reserved_key({name: self.take(item) for name, item in items.items()})
|
|
111
|
+
|
|
112
|
+
def _record_by_type(self, value: object) -> JsonValue:
|
|
113
|
+
self.is_complete = False
|
|
114
|
+
return mark_unserialisable(name_type(type(value)))
|
irimi/_status_reasons.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
from collections.abc import Collection, Iterable, Mapping, Sequence
|
|
5
|
+
from importlib.abc import MetaPathFinder
|
|
6
|
+
from importlib.machinery import ModuleSpec
|
|
7
|
+
from types import ModuleType
|
|
8
|
+
|
|
9
|
+
from irimi._replay_refusals import ReplayRefusal
|
|
10
|
+
from irimi._sdk import Replay
|
|
11
|
+
|
|
12
|
+
ALLOW_UNPATCHED_VARIABLE = "IRIMI_REPLAY_ALLOW_UNPATCHED"
|
|
13
|
+
KNOWN_UNPATCHED_CLIENTS: tuple[str, ...] = (
|
|
14
|
+
"psycopg",
|
|
15
|
+
"psycopg2",
|
|
16
|
+
"asyncpg",
|
|
17
|
+
"pymysql",
|
|
18
|
+
"MySQLdb",
|
|
19
|
+
"sqlalchemy",
|
|
20
|
+
"pymongo",
|
|
21
|
+
"redis",
|
|
22
|
+
"kafka",
|
|
23
|
+
"pika",
|
|
24
|
+
"grpc",
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def forget_libraries_only_irimi_loaded(
|
|
29
|
+
replay: Replay, modules_loaded_before_patching: Collection[str]
|
|
30
|
+
) -> None:
|
|
31
|
+
newly_loaded = [
|
|
32
|
+
module
|
|
33
|
+
for module in list(sys.modules)
|
|
34
|
+
if module.partition(".")[0] in replay.unpatched_libraries
|
|
35
|
+
and module.partition(".")[0] not in modules_loaded_before_patching
|
|
36
|
+
]
|
|
37
|
+
for module in newly_loaded:
|
|
38
|
+
del sys.modules[module]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def refuse_unallowed_clients(
|
|
42
|
+
replay: Replay, environment_variables: Mapping[str, str], loaded_modules: Iterable[str]
|
|
43
|
+
) -> None:
|
|
44
|
+
replay.allowed_unpatched.update(_read_allowed_clients(environment_variables))
|
|
45
|
+
allowed = frozenset(replay.allowed_unpatched)
|
|
46
|
+
_refuse_unallowed(tuple(loaded_modules), allowed, replay.unpatched_libraries)
|
|
47
|
+
sys.meta_path.insert(0, UnallowedClientImportTripwire(allowed, replay.unpatched_libraries))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class UnallowedClientImportTripwire(MetaPathFinder):
|
|
51
|
+
def __init__(self, allowed: frozenset[str], unpatched_libraries: tuple[str, ...]) -> None:
|
|
52
|
+
self._allowed = allowed
|
|
53
|
+
self._unpatched_libraries = unpatched_libraries
|
|
54
|
+
|
|
55
|
+
def find_spec(
|
|
56
|
+
self,
|
|
57
|
+
fullname: str,
|
|
58
|
+
path: Sequence[str] | None,
|
|
59
|
+
target: ModuleType | None = None,
|
|
60
|
+
) -> ModuleSpec | None:
|
|
61
|
+
_refuse_unallowed((fullname,), self._allowed, self._unpatched_libraries)
|
|
62
|
+
return None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _refuse_unallowed(
|
|
66
|
+
loaded_modules: Iterable[str], allowed: Collection[str], unpatched_libraries: Iterable[str]
|
|
67
|
+
) -> None:
|
|
68
|
+
loaded = tuple(loaded_modules)
|
|
69
|
+
drivers = find_unallowed_clients(loaded, allowed, KNOWN_UNPATCHED_CLIENTS)
|
|
70
|
+
libraries = find_unallowed_clients(loaded, allowed, unpatched_libraries)
|
|
71
|
+
if drivers or libraries:
|
|
72
|
+
raise ReplayRefusal(_describe_refusal(drivers, libraries))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def find_unallowed_clients(
|
|
76
|
+
loaded_modules: Iterable[str], allowed: Collection[str], clients: Iterable[str]
|
|
77
|
+
) -> tuple[str, ...]:
|
|
78
|
+
loaded = {module.partition(".")[0] for module in loaded_modules}
|
|
79
|
+
return tuple(sorted(name for name in loaded.intersection(clients) if name not in allowed))
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _describe_refusal(drivers: Sequence[str], libraries: Sequence[str]) -> str:
|
|
83
|
+
sentences = [_describe_unlabeled_drivers(drivers)] if drivers else []
|
|
84
|
+
sentences.extend(_describe_unpatchable_library(library) for library in libraries)
|
|
85
|
+
return "\n".join(sentences)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _describe_unlabeled_drivers(drivers: Sequence[str]) -> str:
|
|
89
|
+
return (
|
|
90
|
+
f"this replay would not see writes made through {', '.join(drivers)}; "
|
|
91
|
+
"label them with @irimi.function(write=True), "
|
|
92
|
+
"then allow the client with dangerously_allow_unpatched"
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _describe_unpatchable_library(library: str) -> str:
|
|
97
|
+
return (
|
|
98
|
+
f"irimi cannot intercept this version of {library} in a replay; upgrade it, "
|
|
99
|
+
"or allow it with dangerously_allow_unpatched if the workflow makes no calls through it"
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _read_allowed_clients(environment_variables: Mapping[str, str]) -> set[str]:
|
|
104
|
+
listed = environment_variables.get(ALLOW_UNPATCHED_VARIABLE, "").split(",")
|
|
105
|
+
return {name.strip() for name in listed if name.strip()}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from urllib.parse import urlsplit
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def remove_userinfo(url: str) -> str:
|
|
7
|
+
address = urlsplit(url).netloc
|
|
8
|
+
_, at_sign, host_and_port = address.rpartition("@")
|
|
9
|
+
if not at_sign:
|
|
10
|
+
return url
|
|
11
|
+
return url.replace(address, host_and_port, 1)
|