parsefabric 0.1.0__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.
- parsefabric/__init__.py +79 -0
- parsefabric/_json.py +247 -0
- parsefabric/_summary_review.py +315 -0
- parsefabric/aggregation/__init__.py +30 -0
- parsefabric/aggregation/base.py +265 -0
- parsefabric/aggregation/codec.py +77 -0
- parsefabric/aggregation/evidence.py +667 -0
- parsefabric/aggregation/routing.py +161 -0
- parsefabric/aggregation/statistical.py +153 -0
- parsefabric/builtins/__init__.py +22 -0
- parsefabric/builtins/application_log.py +121 -0
- parsefabric/builtins/cli_output.py +159 -0
- parsefabric/builtins/code_detection.py +228 -0
- parsefabric/builtins/json_parser.py +140 -0
- parsefabric/builtins/mixed_content.py +655 -0
- parsefabric/builtins/python_traceback.py +120 -0
- parsefabric/builtins/timestamped_log.py +135 -0
- parsefabric/capabilities.py +109 -0
- parsefabric/compression.py +118 -0
- parsefabric/engine.py +462 -0
- parsefabric/errors.py +150 -0
- parsefabric/execution/__init__.py +15 -0
- parsefabric/execution/_executor.py +102 -0
- parsefabric/execution/async_backend.py +69 -0
- parsefabric/execution/base.py +143 -0
- parsefabric/execution/process_backend.py +41 -0
- parsefabric/execution/thread_backend.py +36 -0
- parsefabric/models.py +506 -0
- parsefabric/observability.py +252 -0
- parsefabric/parser/__init__.py +10 -0
- parsefabric/parser/_text.py +34 -0
- parsefabric/parser/async_parser.py +53 -0
- parsefabric/parser/base.py +205 -0
- parsefabric/parser/deterministic.py +219 -0
- parsefabric/parser/semantic.py +15 -0
- parsefabric/partitioning.py +172 -0
- parsefabric/patterns/__init__.py +19 -0
- parsefabric/patterns/base.py +98 -0
- parsefabric/patterns/exact.py +61 -0
- parsefabric/patterns/match.py +22 -0
- parsefabric/patterns/predicate.py +62 -0
- parsefabric/patterns/regex.py +78 -0
- parsefabric/patterns/structured.py +59 -0
- parsefabric/py.typed +0 -0
- parsefabric/registry.py +174 -0
- parsefabric/serialization.py +67 -0
- parsefabric/summarization.py +563 -0
- parsefabric-0.1.0.dist-info/METADATA +208 -0
- parsefabric-0.1.0.dist-info/RECORD +51 -0
- parsefabric-0.1.0.dist-info/WHEEL +4 -0
- parsefabric-0.1.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
"""Aggregate models and the aggregator contract.
|
|
2
|
+
|
|
3
|
+
Aggregates are typed Python objects with a fixed, package-owned JSON form.
|
|
4
|
+
`Aggregate.to_dict` and `Aggregate.from_dict` convert one concrete
|
|
5
|
+
aggregate type; there is no registry of aggregate kinds because every parser
|
|
6
|
+
produces the same `EvidenceAggregate` and
|
|
7
|
+
serializes it through the package-managed `Parser.serialize`.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from abc import ABC, abstractmethod
|
|
13
|
+
from collections.abc import AsyncIterable, Iterable, Sequence
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from datetime import datetime
|
|
16
|
+
from typing import Any, ClassVar, Self, override
|
|
17
|
+
|
|
18
|
+
from parsefabric._json import (
|
|
19
|
+
STRUCTURE_DEPTH,
|
|
20
|
+
check_text,
|
|
21
|
+
copy_json,
|
|
22
|
+
dumps,
|
|
23
|
+
require_object,
|
|
24
|
+
)
|
|
25
|
+
from parsefabric.errors import CapabilityError
|
|
26
|
+
from parsefabric.models import JSONValue, ParsedEvent
|
|
27
|
+
|
|
28
|
+
_TIME_FIELDS = frozenset(("first_seen", "last_seen"))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _time(fields: dict[str, Any], key: str) -> datetime | None:
|
|
32
|
+
if key not in fields:
|
|
33
|
+
return None
|
|
34
|
+
value = fields[key]
|
|
35
|
+
if not isinstance(value, str):
|
|
36
|
+
raise ValueError(f"{key} must be an ISO 8601 string")
|
|
37
|
+
return datetime.fromisoformat(value)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True, slots=True)
|
|
41
|
+
class Aggregate:
|
|
42
|
+
"""Fields shared by every aggregate: what was summarized, how often, when.
|
|
43
|
+
|
|
44
|
+
Attributes:
|
|
45
|
+
event_type: Event type the aggregate summarizes.
|
|
46
|
+
count: Number of events, at least one.
|
|
47
|
+
first_seen: Earliest event timestamp, if any event had one.
|
|
48
|
+
last_seen: Latest event timestamp, if any event had one.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
FIELDS: ClassVar[tuple[str, ...]] = ()
|
|
52
|
+
"""JSON fields of the concrete type beyond the common fields."""
|
|
53
|
+
|
|
54
|
+
event_type: str
|
|
55
|
+
count: int
|
|
56
|
+
first_seen: datetime | None
|
|
57
|
+
last_seen: datetime | None
|
|
58
|
+
|
|
59
|
+
def __post_init__(self) -> None:
|
|
60
|
+
if type(self.count) is not int or self.count < 1:
|
|
61
|
+
raise ValueError("aggregate count must be a positive integer")
|
|
62
|
+
if not isinstance(self.event_type, str) or not self.event_type:
|
|
63
|
+
raise ValueError("aggregate event_type must not be empty")
|
|
64
|
+
check_text(self.event_type, "aggregate event_type")
|
|
65
|
+
if any(
|
|
66
|
+
timestamp is not None
|
|
67
|
+
and (not isinstance(timestamp, datetime) or timestamp.utcoffset() is None)
|
|
68
|
+
for timestamp in (self.first_seen, self.last_seen)
|
|
69
|
+
):
|
|
70
|
+
raise ValueError("aggregate timestamps must be timezone-aware")
|
|
71
|
+
if (
|
|
72
|
+
self.first_seen is not None
|
|
73
|
+
and self.last_seen is not None
|
|
74
|
+
and self.first_seen > self.last_seen
|
|
75
|
+
):
|
|
76
|
+
raise ValueError("first_seen must not be later than last_seen")
|
|
77
|
+
|
|
78
|
+
def to_dict(self) -> dict[str, JSONValue]:
|
|
79
|
+
"""Return an independent copy of the canonical JSON representation.
|
|
80
|
+
|
|
81
|
+
``first_seen`` and ``last_seen`` are omitted when unknown.
|
|
82
|
+
"""
|
|
83
|
+
return copy_json(self._to_wire(), "aggregate", max_depth=STRUCTURE_DEPTH)
|
|
84
|
+
|
|
85
|
+
def _to_wire(self) -> dict[str, JSONValue]:
|
|
86
|
+
"""Return the representation sharing nested values, for encoding."""
|
|
87
|
+
data: dict[str, JSONValue] = {
|
|
88
|
+
"event_type": self.event_type,
|
|
89
|
+
"count": self.count,
|
|
90
|
+
}
|
|
91
|
+
if self.first_seen is not None:
|
|
92
|
+
data["first_seen"] = self.first_seen.isoformat()
|
|
93
|
+
if self.last_seen is not None:
|
|
94
|
+
data["last_seen"] = self.last_seen.isoformat()
|
|
95
|
+
return data | self._fields_to_wire()
|
|
96
|
+
|
|
97
|
+
@classmethod
|
|
98
|
+
def from_dict(cls, data: object) -> Self:
|
|
99
|
+
"""Rebuild an aggregate of this type from `to_dict` output.
|
|
100
|
+
|
|
101
|
+
Args:
|
|
102
|
+
data: A decoded JSON object.
|
|
103
|
+
|
|
104
|
+
Returns:
|
|
105
|
+
The validated aggregate.
|
|
106
|
+
|
|
107
|
+
Raises:
|
|
108
|
+
ValueError: If ``data`` does not have exactly the fields of this
|
|
109
|
+
aggregate type or a field is invalid.
|
|
110
|
+
"""
|
|
111
|
+
fields = require_object(
|
|
112
|
+
data,
|
|
113
|
+
cls.__name__,
|
|
114
|
+
frozenset(("event_type", "count", *cls.FIELDS)),
|
|
115
|
+
_TIME_FIELDS,
|
|
116
|
+
)
|
|
117
|
+
return cls(
|
|
118
|
+
event_type=fields["event_type"],
|
|
119
|
+
count=fields["count"],
|
|
120
|
+
first_seen=_time(fields, "first_seen"),
|
|
121
|
+
last_seen=_time(fields, "last_seen"),
|
|
122
|
+
**cls._fields_from_dict(fields),
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
def _fields_to_wire(self) -> dict[str, JSONValue]:
|
|
126
|
+
"""Return the type-specific fields; overridden by concrete types."""
|
|
127
|
+
return {}
|
|
128
|
+
|
|
129
|
+
@classmethod
|
|
130
|
+
def _fields_from_dict(cls, fields: dict[str, Any]) -> dict[str, Any]:
|
|
131
|
+
"""Return constructor arguments for the type-specific fields."""
|
|
132
|
+
return {}
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _time_range(
|
|
136
|
+
*values: datetime | None,
|
|
137
|
+
) -> tuple[datetime | None, datetime | None]:
|
|
138
|
+
present = [value for value in values if value is not None]
|
|
139
|
+
return (min(present), max(present)) if present else (None, None)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@dataclass(frozen=True, slots=True)
|
|
143
|
+
class CountAggregate(Aggregate):
|
|
144
|
+
"""Lossy statistical summary: a count and time range per attribute group.
|
|
145
|
+
|
|
146
|
+
Attributes:
|
|
147
|
+
key_attributes: Values of the grouping attributes; missing attributes
|
|
148
|
+
are ``None``.
|
|
149
|
+
"""
|
|
150
|
+
|
|
151
|
+
FIELDS: ClassVar[tuple[str, ...]] = ("key_attributes",)
|
|
152
|
+
|
|
153
|
+
key_attributes: dict[str, JSONValue]
|
|
154
|
+
|
|
155
|
+
@override
|
|
156
|
+
def __post_init__(self) -> None:
|
|
157
|
+
Aggregate.__post_init__(self)
|
|
158
|
+
if not isinstance(self.key_attributes, dict):
|
|
159
|
+
raise ValueError("aggregate key attributes must be a JSON object")
|
|
160
|
+
object.__setattr__(
|
|
161
|
+
self,
|
|
162
|
+
"key_attributes",
|
|
163
|
+
copy_json(self.key_attributes, "aggregate key attributes"),
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
@override
|
|
167
|
+
def _fields_to_wire(self) -> dict[str, JSONValue]:
|
|
168
|
+
return {"key_attributes": self.key_attributes}
|
|
169
|
+
|
|
170
|
+
@classmethod
|
|
171
|
+
@override
|
|
172
|
+
def _fields_from_dict(cls, fields: dict[str, Any]) -> dict[str, Any]:
|
|
173
|
+
return {"key_attributes": fields["key_attributes"]}
|
|
174
|
+
|
|
175
|
+
def merge(self, other: CountAggregate) -> CountAggregate:
|
|
176
|
+
"""Combine two partial summaries of the same group.
|
|
177
|
+
|
|
178
|
+
Args:
|
|
179
|
+
other: A summary with the same event type and key attributes.
|
|
180
|
+
|
|
181
|
+
Returns:
|
|
182
|
+
The combined summary.
|
|
183
|
+
|
|
184
|
+
Raises:
|
|
185
|
+
TypeError: If ``other`` is not a `CountAggregate`.
|
|
186
|
+
ValueError: If the summaries belong to different groups.
|
|
187
|
+
"""
|
|
188
|
+
if not isinstance(other, CountAggregate):
|
|
189
|
+
raise TypeError("can only merge CountAggregate partials")
|
|
190
|
+
if self.event_type != other.event_type or dumps(
|
|
191
|
+
self.key_attributes, sort_keys=True
|
|
192
|
+
) != dumps(other.key_attributes, sort_keys=True):
|
|
193
|
+
raise ValueError("cannot merge aggregates of different groups")
|
|
194
|
+
first_seen, last_seen = _time_range(
|
|
195
|
+
self.first_seen, self.last_seen, other.first_seen, other.last_seen
|
|
196
|
+
)
|
|
197
|
+
return CountAggregate(
|
|
198
|
+
event_type=self.event_type,
|
|
199
|
+
count=self.count + other.count,
|
|
200
|
+
first_seen=first_seen,
|
|
201
|
+
last_seen=last_seen,
|
|
202
|
+
key_attributes=self.key_attributes,
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
class Aggregator(ABC):
|
|
207
|
+
"""Aggregation strategy of a parser, with explicit merge behavior."""
|
|
208
|
+
|
|
209
|
+
@property
|
|
210
|
+
def lossless(self) -> bool:
|
|
211
|
+
"""Whether `materialize` can rebuild every original event."""
|
|
212
|
+
return False
|
|
213
|
+
|
|
214
|
+
@property
|
|
215
|
+
def requires_source(self) -> bool:
|
|
216
|
+
"""Whether `materialize` needs the events of a fresh re-parse."""
|
|
217
|
+
return False
|
|
218
|
+
|
|
219
|
+
async def materialize(
|
|
220
|
+
self,
|
|
221
|
+
aggregates: Sequence[Aggregate],
|
|
222
|
+
events: Sequence[ParsedEvent] | None = None,
|
|
223
|
+
) -> tuple[ParsedEvent, ...]:
|
|
224
|
+
"""Rebuild and verify the original events.
|
|
225
|
+
|
|
226
|
+
Args:
|
|
227
|
+
aggregates: Every aggregate of one source document.
|
|
228
|
+
events: Events of a fresh parse, for aggregators that require
|
|
229
|
+
the source.
|
|
230
|
+
|
|
231
|
+
Returns:
|
|
232
|
+
The verified original events.
|
|
233
|
+
|
|
234
|
+
Raises:
|
|
235
|
+
CapabilityError: Always, for lossy aggregators.
|
|
236
|
+
"""
|
|
237
|
+
raise CapabilityError(
|
|
238
|
+
f"{type(self).__name__} is a lossy aggregator and cannot materialize"
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
@abstractmethod
|
|
242
|
+
async def aggregate(
|
|
243
|
+
self, events: Iterable[ParsedEvent] | AsyncIterable[ParsedEvent]
|
|
244
|
+
) -> tuple[Aggregate, ...]:
|
|
245
|
+
"""Create aggregates from an event stream.
|
|
246
|
+
|
|
247
|
+
Args:
|
|
248
|
+
events: Events to aggregate.
|
|
249
|
+
|
|
250
|
+
Returns:
|
|
251
|
+
The aggregates.
|
|
252
|
+
"""
|
|
253
|
+
|
|
254
|
+
@abstractmethod
|
|
255
|
+
async def merge(
|
|
256
|
+
self, partials: Iterable[Aggregate] | AsyncIterable[Aggregate]
|
|
257
|
+
) -> tuple[Aggregate, ...]:
|
|
258
|
+
"""Merge partial aggregates into deterministic output.
|
|
259
|
+
|
|
260
|
+
Args:
|
|
261
|
+
partials: Aggregates produced by this aggregator.
|
|
262
|
+
|
|
263
|
+
Returns:
|
|
264
|
+
The merged aggregates.
|
|
265
|
+
"""
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Package-owned, versioned JSON encoding of parser output.
|
|
2
|
+
|
|
3
|
+
Every parser produces the same `EvidenceAggregate` documents, so there
|
|
4
|
+
is exactly one closed wire format and nothing to extend. The public entry
|
|
5
|
+
points are the package-managed `Parser.serialize` and
|
|
6
|
+
`Parser.deserialize`; this module is their implementation.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import Iterable
|
|
12
|
+
|
|
13
|
+
from parsefabric import _json
|
|
14
|
+
from parsefabric.aggregation.evidence import EvidenceAggregate
|
|
15
|
+
from parsefabric.errors import SerializationError
|
|
16
|
+
|
|
17
|
+
FORMAT = "parsefabric.aggregates/1"
|
|
18
|
+
"""Identifier of the aggregate wire format written by `encode`."""
|
|
19
|
+
|
|
20
|
+
_DOCUMENT_FIELDS = frozenset(("format", "aggregates"))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def encode(
|
|
24
|
+
aggregates: Iterable[EvidenceAggregate], *, indent: int | None = None
|
|
25
|
+
) -> str:
|
|
26
|
+
"""Encode evidence as JSON text, compact unless ``indent`` is given.
|
|
27
|
+
|
|
28
|
+
Args:
|
|
29
|
+
aggregates: Aggregates to encode.
|
|
30
|
+
indent: Indentation for human reading.
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
A ``parsefabric.aggregates/1`` document.
|
|
34
|
+
|
|
35
|
+
Raises:
|
|
36
|
+
TypeError: If an item is not an `EvidenceAggregate`.
|
|
37
|
+
"""
|
|
38
|
+
items = []
|
|
39
|
+
for aggregate in aggregates:
|
|
40
|
+
if not isinstance(aggregate, EvidenceAggregate):
|
|
41
|
+
raise TypeError(
|
|
42
|
+
"only EvidenceAggregate can be serialized, "
|
|
43
|
+
f"got {type(aggregate).__name__}"
|
|
44
|
+
)
|
|
45
|
+
items.append(aggregate._to_wire())
|
|
46
|
+
document = {"format": FORMAT, "aggregates": items}
|
|
47
|
+
if indent is None:
|
|
48
|
+
return _json.dumps_validated(document)
|
|
49
|
+
return _json.dumps(document, indent=indent)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def decode(text: str | bytes) -> tuple[EvidenceAggregate, ...]:
|
|
53
|
+
"""Decode and validate `encode` output.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
text: JSON text or UTF-8 bytes.
|
|
57
|
+
|
|
58
|
+
Returns:
|
|
59
|
+
The validated aggregates.
|
|
60
|
+
|
|
61
|
+
Raises:
|
|
62
|
+
TypeError: If ``text`` is not text or bytes.
|
|
63
|
+
SerializationError: For malformed JSON, an unsupported format, unknown
|
|
64
|
+
or missing fields, or any aggregate that fails validation.
|
|
65
|
+
"""
|
|
66
|
+
try:
|
|
67
|
+
document = _json.require_object(
|
|
68
|
+
_json.loads(text), "aggregates document", _DOCUMENT_FIELDS
|
|
69
|
+
)
|
|
70
|
+
if document["format"] != FORMAT:
|
|
71
|
+
raise ValueError(f"expected a {FORMAT} document")
|
|
72
|
+
aggregates = document["aggregates"]
|
|
73
|
+
if not isinstance(aggregates, list):
|
|
74
|
+
raise ValueError("aggregates must be a list")
|
|
75
|
+
return tuple(EvidenceAggregate.from_dict(item) for item in aggregates)
|
|
76
|
+
except ValueError as error:
|
|
77
|
+
raise SerializationError(f"invalid {FORMAT} document: {error}") from error
|