irimi-server 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.4
2
+ Name: irimi-server
3
+ Version: 0.2.0
4
+ Summary: The irimi server: takes recorded runs in and answers the reads. Installed by irimi.
5
+ License-Expression: Apache-2.0
6
+ Classifier: Development Status :: 2 - Pre-Alpha
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3 :: Only
9
+ Requires-Dist: irimi-sdk==0.2.0
10
+ Requires-Dist: starlette>=1.10.0
11
+ Requires-Dist: uvicorn>=0.54.0
12
+ Requires-Python: >=3.12
13
+ Project-URL: Homepage, https://github.com/irimi-io/Irimi
14
+ Project-URL: Issues, https://github.com/irimi-io/Irimi/issues
15
+ Project-URL: Source, https://github.com/irimi-io/Irimi
16
+ Description-Content-Type: text/markdown
17
+
18
+ # irimi-server
19
+
20
+ The irimi server: it takes recorded runs in from the irimi SDK, keeps them, and answers the reads
21
+ behind `irimi runs`, `irimi replay` and `irimi diff`.
22
+
23
+ It is installed by `pip install irimi` and started with `irimi server`.
24
+
25
+ Early development. Source and issues: https://github.com/irimi-io/Irimi
@@ -0,0 +1,8 @@
1
+ # irimi-server
2
+
3
+ The irimi server: it takes recorded runs in from the irimi SDK, keeps them, and answers the reads
4
+ behind `irimi runs`, `irimi replay` and `irimi diff`.
5
+
6
+ It is installed by `pip install irimi` and started with `irimi server`.
7
+
8
+ Early development. Source and issues: https://github.com/irimi-io/Irimi
@@ -0,0 +1,29 @@
1
+ [project]
2
+ name = "irimi-server"
3
+ version = "0.2.0"
4
+ description = "The irimi server: takes recorded runs in and answers the reads. Installed by irimi."
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ requires-python = ">=3.12"
8
+ dependencies = [
9
+ "irimi-sdk==0.2.0",
10
+ "starlette>=1.10.0",
11
+ "uvicorn>=0.54.0",
12
+ ]
13
+ classifiers = [
14
+ "Development Status :: 2 - Pre-Alpha",
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3 :: Only",
17
+ ]
18
+
19
+ [project.urls]
20
+ Homepage = "https://github.com/irimi-io/Irimi"
21
+ Issues = "https://github.com/irimi-io/Irimi/issues"
22
+ Source = "https://github.com/irimi-io/Irimi"
23
+
24
+ [build-system]
25
+ requires = ["uv_build>=0.12,<0.13"]
26
+ build-backend = "uv_build"
27
+
28
+ [tool.uv.sources.irimi-sdk]
29
+ workspace = true
@@ -0,0 +1,29 @@
1
+ [project]
2
+ name = "irimi-server"
3
+ version = "0.2.0"
4
+ description = "The irimi server: takes recorded runs in and answers the reads. Installed by irimi."
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ requires-python = ">=3.12"
8
+ dependencies = [
9
+ "irimi-sdk==0.2.0",
10
+ "starlette>=1.10.0",
11
+ "uvicorn>=0.54.0",
12
+ ]
13
+ classifiers = [
14
+ "Development Status :: 2 - Pre-Alpha",
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3 :: Only",
17
+ ]
18
+
19
+ [project.urls]
20
+ Homepage = "https://github.com/irimi-io/Irimi"
21
+ Issues = "https://github.com/irimi-io/Irimi/issues"
22
+ Source = "https://github.com/irimi-io/Irimi"
23
+
24
+ [build-system]
25
+ requires = ["uv_build>=0.12,<0.13"]
26
+ build-backend = "uv_build"
27
+
28
+ [tool.uv.sources]
29
+ irimi-sdk = { workspace = true }
File without changes
@@ -0,0 +1,9 @@
1
+ import json
2
+ from typing import Any
3
+
4
+ from starlette.responses import JSONResponse
5
+
6
+
7
+ class JsonAnswer(JSONResponse):
8
+ def render(self, content: Any) -> bytes:
9
+ return json.dumps(content, allow_nan=False, separators=(",", ":")).encode()
@@ -0,0 +1,120 @@
1
+ from irimi._wire import (
2
+ EVENTS_PATH,
3
+ RUN_EVENTS_PATH,
4
+ WIRE_VERSION,
5
+ Batch,
6
+ Event,
7
+ ParsedBatch,
8
+ parse_batch,
9
+ write_batch,
10
+ write_refused_events,
11
+ )
12
+ from irimi._wire.field_names import NEXT_CURSOR
13
+ from starlette.applications import Starlette
14
+ from starlette.concurrency import run_in_threadpool
15
+ from starlette.requests import Request
16
+ from starlette.routing import Route
17
+
18
+ from irimi_server.answers import JsonAnswer
19
+ from irimi_server.assembly import RunTooDeepError
20
+ from irimi_server.diff_routes import create_diff_routes
21
+ from irimi_server.page_requests import (
22
+ EVENT_PAGE_SIZE_LIMIT,
23
+ LARGEST_EVENT_PAGE_LIMIT,
24
+ InvalidPageRequestError,
25
+ PageRequest,
26
+ read_page_request,
27
+ )
28
+ from irimi_server.pages import InvalidCursorError, Page
29
+ from irimi_server.reader_documents import write_refusal
30
+ from irimi_server.reader_routes import create_reader_routes
31
+ from irimi_server.storage import DEFAULT_PROJECT, NotHeldError, StorageEngine
32
+ from irimi_server.strict_json import load_strict_json
33
+
34
+ ACCEPTED_VERSIONS = (WIRE_VERSION,)
35
+ DEFAULT_EVENT_PAGE_LIMIT = 500
36
+
37
+
38
+ def create_app(storage: StorageEngine) -> Starlette:
39
+ async def ingest_events(request: Request) -> JsonAnswer:
40
+ try:
41
+ parsed = await run_in_threadpool(_store_batch, storage, await request.body())
42
+ except (ValueError, RecursionError) as error:
43
+ return JsonAnswer(write_refusal(str(error)), status_code=400)
44
+ return JsonAnswer(write_refused_events(parsed.refused))
45
+
46
+ async def read_run_events(request: Request) -> JsonAnswer:
47
+ trace_id: str = request.path_params["trace_id"]
48
+ page_request = read_page_request(
49
+ request.query_params, DEFAULT_EVENT_PAGE_LIMIT, LARGEST_EVENT_PAGE_LIMIT
50
+ )
51
+ page = await run_in_threadpool(_read_event_page, storage, trace_id, page_request)
52
+ batch = Batch(events=page.items, fields={NEXT_CURSOR: page.next_cursor})
53
+ return JsonAnswer(write_batch(batch))
54
+
55
+ return Starlette(
56
+ routes=[
57
+ Route(EVENTS_PATH, ingest_events, methods=["POST"]),
58
+ Route(RUN_EVENTS_PATH, read_run_events, methods=["GET"]),
59
+ Route("/{version}/events", refuse_unknown_version, methods=["POST"]),
60
+ Route("/{version}/runs/{trace_id}/events", refuse_unknown_version, methods=["GET"]),
61
+ *create_diff_routes(storage),
62
+ *create_reader_routes(storage),
63
+ ],
64
+ exception_handlers={
65
+ InvalidPageRequestError: refuse_request,
66
+ InvalidCursorError: refuse_request,
67
+ NotHeldError: answer_not_held,
68
+ RunTooDeepError: refuse_run_too_deep,
69
+ },
70
+ )
71
+
72
+
73
+ async def refuse_request(request: Request, error: Exception) -> JsonAnswer:
74
+ return JsonAnswer(write_refusal(str(error)), status_code=400)
75
+
76
+
77
+ async def answer_not_held(request: Request, error: Exception) -> JsonAnswer:
78
+ return JsonAnswer(write_refusal(str(error)), status_code=404)
79
+
80
+
81
+ async def refuse_run_too_deep(request: Request, error: Exception) -> JsonAnswer:
82
+ events_path = RUN_EVENTS_PATH.format(**request.path_params)
83
+ reason = f"this run is {error}; read its events at {events_path}"
84
+ return JsonAnswer(write_refusal(reason), status_code=422)
85
+
86
+
87
+ async def refuse_unknown_version(request: Request) -> JsonAnswer:
88
+ version = request.path_params["version"]
89
+ return JsonAnswer(
90
+ {
91
+ **write_refusal(f"unknown wire format version: {version}"),
92
+ "accepted_versions": list(ACCEPTED_VERSIONS),
93
+ },
94
+ status_code=404,
95
+ )
96
+
97
+
98
+ def _store_batch(storage: StorageEngine, body: bytes) -> ParsedBatch:
99
+ parsed = parse_batch(load_strict_json(body))
100
+ storage.add_events(DEFAULT_PROJECT, parsed.batch.events)
101
+ return parsed
102
+
103
+
104
+ def _read_event_page(
105
+ storage: StorageEngine, trace_id: str, page_request: PageRequest
106
+ ) -> Page[Event]:
107
+ page = storage.read_run_events(
108
+ DEFAULT_PROJECT, trace_id, page_request.cursor, page_request.limit, EVENT_PAGE_SIZE_LIMIT
109
+ )
110
+ if page.items:
111
+ return page
112
+ is_first_page = page_request.cursor is None
113
+ if is_first_page or not _holds_run(storage, trace_id):
114
+ raise NotHeldError(f"no run with id {trace_id}")
115
+ return page
116
+
117
+
118
+ def _holds_run(storage: StorageEngine, trace_id: str) -> bool:
119
+ first_event = storage.read_run_events(DEFAULT_PROJECT, trace_id, None, 1, EVENT_PAGE_SIZE_LIMIT)
120
+ return bool(first_event.items)
@@ -0,0 +1,210 @@
1
+ from collections.abc import Callable, Mapping, Sequence
2
+ from dataclasses import dataclass, replace
3
+ from typing import Literal
4
+
5
+ from irimi._wire import EndEvent, Event, JsonValue, StartEvent, write_event
6
+ from irimi._wire.field_names import ENVIRONMENT, EVENTS_PRODUCED, MODE, STATUS
7
+
8
+ from irimi_server.flags import read_flags
9
+ from irimi_server.reader_documents import NODE_KEYS, Node, RunSummary, RunTree
10
+ from irimi_server.storage import StoredRoot
11
+
12
+ Condition = Literal["no_root", "unfinished", "incomplete", "not_replayable"]
13
+ NOT_REPLAYABLE = "not_replayable"
14
+ DEEPEST_TREE = 200
15
+
16
+
17
+ class RunTooDeepError(Exception):
18
+ pass
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class Span:
23
+ span_id: str
24
+ arrival: int
25
+ start: StartEvent | None
26
+ end: EndEvent | None
27
+ other_events: tuple[Event, ...]
28
+
29
+ @property
30
+ def parent_span_id(self) -> str | None:
31
+ return None if self.start is None else self.start.parent_span_id
32
+
33
+
34
+ NodeBuilder = Callable[[Span, tuple[Node, ...]], Node]
35
+
36
+
37
+ def assemble_run(trace_id: str, events: Sequence[Event]) -> RunTree:
38
+ return _assemble(trace_id, events, _build_tree_node)
39
+
40
+
41
+ def assemble_whole_run(trace_id: str, events: Sequence[Event]) -> RunTree:
42
+ return _assemble(trace_id, events, _build_whole_node)
43
+
44
+
45
+ def _assemble(trace_id: str, events: Sequence[Event], build_node: NodeBuilder) -> RunTree:
46
+ spans = _group_spans(events)
47
+ children = _group_children(spans)
48
+ placed: set[str] = set()
49
+ root_span = _pick_root(spans)
50
+ root = None if root_span is None else _build_subtree(root_span, children, placed, 1, build_node)
51
+ detached = [
52
+ _build_subtree(span, children, placed, 1, build_node)
53
+ for span in spans.values()
54
+ if span.span_id not in placed and _has_no_parent_in_the_run(span, spans)
55
+ ]
56
+ looping = [build_node(span, ()) for span in spans.values() if span.span_id not in placed]
57
+ return RunTree(
58
+ id=trace_id,
59
+ conditions=read_conditions(
60
+ None if root_span is None else root_span.start,
61
+ None if root_span is None else root_span.end,
62
+ sum(isinstance(event, StartEvent | EndEvent) for event in events),
63
+ ),
64
+ root=root,
65
+ detached=(*detached, *looping),
66
+ )
67
+
68
+
69
+ def assemble_call(events: Sequence[Event]) -> Node | None:
70
+ spans = _group_spans(events)
71
+ if not spans:
72
+ return None
73
+ return _build_call(next(iter(spans.values())))
74
+
75
+
76
+ def read_conditions(
77
+ start: StartEvent | None, end: EndEvent | None, events_held: int
78
+ ) -> tuple[Condition, ...]:
79
+ if start is None:
80
+ return ("no_root",)
81
+ conditions: list[Condition] = []
82
+ if end is None:
83
+ conditions.append("unfinished")
84
+ if end is not None and _holds_fewer_than_produced(end, events_held):
85
+ conditions.append("incomplete")
86
+ if NOT_REPLAYABLE in merge_flags(start.fields, {} if end is None else end.fields):
87
+ conditions.append("not_replayable")
88
+ return tuple(conditions)
89
+
90
+
91
+ def summarise_root(root: StoredRoot) -> RunSummary:
92
+ end_fields: Mapping[str, JsonValue] = {} if root.end is None else root.end.fields
93
+ return RunSummary(
94
+ id=root.start.trace_id,
95
+ span_id=root.start.span_id,
96
+ kind=root.start.kind,
97
+ name=root.start.name,
98
+ start_time_unix_nano=root.start.time_unix_nano,
99
+ end_time_unix_nano=None if root.end is None else root.end.time_unix_nano,
100
+ status=end_fields.get(STATUS),
101
+ flags=merge_flags(root.start.fields, end_fields),
102
+ environment=root.start.fields.get(ENVIRONMENT),
103
+ mode=root.start.fields.get(MODE),
104
+ conditions=read_conditions(root.start, root.end, root.events_held),
105
+ fields={},
106
+ )
107
+
108
+
109
+ def merge_flags(
110
+ start_fields: Mapping[str, JsonValue], end_fields: Mapping[str, JsonValue]
111
+ ) -> tuple[JsonValue, ...]:
112
+ start_flags = read_flags(start_fields)
113
+ return start_flags + tuple(flag for flag in read_flags(end_fields) if flag not in start_flags)
114
+
115
+
116
+ def _holds_fewer_than_produced(end: EndEvent, events_held: int) -> bool:
117
+ events_produced = end.fields.get(EVENTS_PRODUCED)
118
+ if isinstance(events_produced, bool) or not isinstance(events_produced, int):
119
+ return False
120
+ return events_held < events_produced
121
+
122
+
123
+ def _group_spans(events: Sequence[Event]) -> dict[str, Span]:
124
+ spans: dict[str, Span] = {}
125
+ for arrival, event in enumerate(events):
126
+ span = spans.get(event.span_id) or Span(event.span_id, arrival, None, None, ())
127
+ spans[event.span_id] = _add_event(span, event, arrival)
128
+ return spans
129
+
130
+
131
+ def _add_event(span: Span, event: Event, arrival: int) -> Span:
132
+ if isinstance(event, StartEvent) and span.start is None:
133
+ return replace(span, start=event, arrival=arrival)
134
+ if isinstance(event, EndEvent) and span.end is None:
135
+ return replace(span, end=event)
136
+ return replace(span, other_events=(*span.other_events, event))
137
+
138
+
139
+ def _group_children(spans: Mapping[str, Span]) -> dict[str, list[Span]]:
140
+ children: dict[str, list[Span]] = {}
141
+ for span in spans.values():
142
+ if span.start is not None and span.start.parent_span_id is not None:
143
+ children.setdefault(span.start.parent_span_id, []).append(span)
144
+ for siblings in children.values():
145
+ siblings.sort(key=_read_position)
146
+ return children
147
+
148
+
149
+ def _read_position(span: Span) -> tuple[int, int]:
150
+ return (0 if span.start is None else span.start.seq, span.arrival)
151
+
152
+
153
+ def _pick_root(spans: Mapping[str, Span]) -> Span | None:
154
+ roots = [
155
+ span for span in spans.values() if span.start is not None and span.parent_span_id is None
156
+ ]
157
+ return min(roots, key=_read_position, default=None)
158
+
159
+
160
+ def _has_no_parent_in_the_run(span: Span, spans: Mapping[str, Span]) -> bool:
161
+ return span.parent_span_id is None or span.parent_span_id not in spans
162
+
163
+
164
+ def _build_subtree(
165
+ span: Span,
166
+ children: Mapping[str, list[Span]],
167
+ placed: set[str],
168
+ depth: int,
169
+ build_node: NodeBuilder,
170
+ ) -> Node:
171
+ if depth > DEEPEST_TREE:
172
+ raise RunTooDeepError(f"nested more than {DEEPEST_TREE} calls deep")
173
+ placed.add(span.span_id)
174
+ child_nodes = tuple(
175
+ _build_subtree(child, children, placed, depth + 1, build_node)
176
+ for child in children.get(span.span_id, ())
177
+ if child.span_id not in placed
178
+ )
179
+ return build_node(span, child_nodes)
180
+
181
+
182
+ def _build_tree_node(span: Span, children: tuple[Node, ...]) -> Node:
183
+ return replace(_build_call(span), fields={}, events=(), children=children)
184
+
185
+
186
+ def _build_whole_node(span: Span, children: tuple[Node, ...]) -> Node:
187
+ return replace(_build_call(span), events=(), children=children)
188
+
189
+
190
+ def _build_call(span: Span) -> Node:
191
+ start_fields: Mapping[str, JsonValue] = {} if span.start is None else span.start.fields
192
+ end_fields: Mapping[str, JsonValue] = {} if span.end is None else span.end.fields
193
+ return Node(
194
+ span_id=span.span_id,
195
+ parent_span_id=span.parent_span_id,
196
+ kind=None if span.start is None else span.start.kind,
197
+ name=None if span.start is None else span.start.name,
198
+ seq=None if span.start is None else span.start.seq,
199
+ start_time_unix_nano=None if span.start is None else span.start.time_unix_nano,
200
+ end_time_unix_nano=None if span.end is None else span.end.time_unix_nano,
201
+ status=end_fields.get(STATUS),
202
+ flags=merge_flags(start_fields, end_fields),
203
+ fields={
204
+ name: value
205
+ for name, value in {**start_fields, **end_fields}.items()
206
+ if name not in NODE_KEYS
207
+ },
208
+ events=tuple(write_event(event) for event in span.other_events),
209
+ children=(),
210
+ )