resource-engine 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.
Files changed (128) hide show
  1. resource_engine/__init__.py +96 -0
  2. resource_engine/application/__init__.py +1 -0
  3. resource_engine/application/actions.py +48 -0
  4. resource_engine/application/context.py +111 -0
  5. resource_engine/application/events.py +54 -0
  6. resource_engine/application/hooks.py +272 -0
  7. resource_engine/application/idempotency.py +277 -0
  8. resource_engine/application/manager.py +1987 -0
  9. resource_engine/application/query.py +47 -0
  10. resource_engine/application/registry.py +137 -0
  11. resource_engine/application/relations.py +470 -0
  12. resource_engine/application/resource.py +984 -0
  13. resource_engine/application/searching.py +162 -0
  14. resource_engine/application/settings.py +169 -0
  15. resource_engine/application/slots.py +67 -0
  16. resource_engine/application/state_machines.py +177 -0
  17. resource_engine/application/timers.py +347 -0
  18. resource_engine/application/transaction.py +100 -0
  19. resource_engine/application/views.py +239 -0
  20. resource_engine/audit/__init__.py +40 -0
  21. resource_engine/audit/export.py +280 -0
  22. resource_engine/audit/history.py +165 -0
  23. resource_engine/audit/janitor.py +257 -0
  24. resource_engine/audit/model.py +98 -0
  25. resource_engine/audit/recorder.py +145 -0
  26. resource_engine/audit/resource.py +68 -0
  27. resource_engine/audit/seal.py +327 -0
  28. resource_engine/audit/sink.py +69 -0
  29. resource_engine/authz/__init__.py +72 -0
  30. resource_engine/authz/apikeys.py +300 -0
  31. resource_engine/authz/base.py +143 -0
  32. resource_engine/authz/catalog.py +291 -0
  33. resource_engine/authz/conditions.py +416 -0
  34. resource_engine/authz/config.py +77 -0
  35. resource_engine/authz/evaluator.py +382 -0
  36. resource_engine/authz/external.py +249 -0
  37. resource_engine/authz/fields.py +44 -0
  38. resource_engine/authz/model.py +145 -0
  39. resource_engine/authz/resources.py +289 -0
  40. resource_engine/authz/roles.py +101 -0
  41. resource_engine/cache.py +144 -0
  42. resource_engine/calls.py +100 -0
  43. resource_engine/capabilities.py +145 -0
  44. resource_engine/composite.py +295 -0
  45. resource_engine/documents/__init__.py +69 -0
  46. resource_engine/documents/content.py +57 -0
  47. resource_engine/documents/events.py +49 -0
  48. resource_engine/documents/janitor.py +93 -0
  49. resource_engine/documents/machine.py +38 -0
  50. resource_engine/documents/manager.py +704 -0
  51. resource_engine/documents/model.py +91 -0
  52. resource_engine/documents/pipeline.py +98 -0
  53. resource_engine/documents/processors.py +320 -0
  54. resource_engine/documents/resource.py +39 -0
  55. resource_engine/domain/__init__.py +10 -0
  56. resource_engine/domain/events.py +50 -0
  57. resource_engine/domain/exceptions.py +23 -0
  58. resource_engine/email.py +417 -0
  59. resource_engine/errors.py +562 -0
  60. resource_engine/explorer.py +133 -0
  61. resource_engine/exports.py +687 -0
  62. resource_engine/generation.py +233 -0
  63. resource_engine/i18n.py +251 -0
  64. resource_engine/identity.py +46 -0
  65. resource_engine/integration.py +80 -0
  66. resource_engine/jobs.py +390 -0
  67. resource_engine/locale/ca/LC_MESSAGES/resource_engine.mo +0 -0
  68. resource_engine/locale/ca/LC_MESSAGES/resource_engine.po +206 -0
  69. resource_engine/locale/es/LC_MESSAGES/resource_engine.mo +0 -0
  70. resource_engine/locale/es/LC_MESSAGES/resource_engine.po +206 -0
  71. resource_engine/logs.py +201 -0
  72. resource_engine/messaging/__init__.py +73 -0
  73. resource_engine/messaging/asyncapi.py +529 -0
  74. resource_engine/messaging/cloudevents.py +98 -0
  75. resource_engine/messaging/consumer.py +165 -0
  76. resource_engine/messaging/delivery.py +115 -0
  77. resource_engine/messaging/envelope.py +193 -0
  78. resource_engine/messaging/hub.py +148 -0
  79. resource_engine/messaging/inbound.py +76 -0
  80. resource_engine/messaging/inspection.py +113 -0
  81. resource_engine/messaging/janitor.py +136 -0
  82. resource_engine/messaging/live.py +179 -0
  83. resource_engine/messaging/processing.py +357 -0
  84. resource_engine/messaging/publishing.py +318 -0
  85. resource_engine/messaging/relay.py +84 -0
  86. resource_engine/messaging/worker.py +166 -0
  87. resource_engine/nosql.py +394 -0
  88. resource_engine/ports/__init__.py +13 -0
  89. resource_engine/ports/activity.py +171 -0
  90. resource_engine/ports/audit.py +42 -0
  91. resource_engine/ports/authz.py +132 -0
  92. resource_engine/ports/cache.py +41 -0
  93. resource_engine/ports/email.py +118 -0
  94. resource_engine/ports/event_publisher.py +34 -0
  95. resource_engine/ports/idempotency.py +69 -0
  96. resource_engine/ports/identity.py +112 -0
  97. resource_engine/ports/locks.py +28 -0
  98. resource_engine/ports/messaging.py +197 -0
  99. resource_engine/ports/observability.py +60 -0
  100. resource_engine/ports/ratelimit.py +59 -0
  101. resource_engine/ports/repository.py +56 -0
  102. resource_engine/ports/storage.py +93 -0
  103. resource_engine/ports/templates.py +54 -0
  104. resource_engine/ports/tracing.py +61 -0
  105. resource_engine/ports/unit_of_work.py +46 -0
  106. resource_engine/processes.py +408 -0
  107. resource_engine/py.typed +0 -0
  108. resource_engine/querying.py +319 -0
  109. resource_engine/ratelimit.py +217 -0
  110. resource_engine/reporting.py +230 -0
  111. resource_engine/schema_examples.py +51 -0
  112. resource_engine/templates.py +143 -0
  113. resource_engine/tenancy.py +68 -0
  114. resource_engine/testing/__init__.py +34 -0
  115. resource_engine/testing/activity.py +123 -0
  116. resource_engine/testing/contracts.py +1416 -0
  117. resource_engine/testing/email.py +36 -0
  118. resource_engine/testing/engine.py +40 -0
  119. resource_engine/testing/memory.py +603 -0
  120. resource_engine/testing/storage.py +110 -0
  121. resource_engine/testing/tracing.py +100 -0
  122. resource_engine/tracing.py +156 -0
  123. resource_engine/translatable.py +80 -0
  124. resource_engine/versions.py +189 -0
  125. resource_engine-0.1.0.dist-info/METADATA +36 -0
  126. resource_engine-0.1.0.dist-info/RECORD +128 -0
  127. resource_engine-0.1.0.dist-info/WHEEL +4 -0
  128. resource_engine-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,40 @@
1
+ """Audit trail: committed changes and refused attempts, retention and
2
+ tamper evidence. See docs/audit.md."""
3
+
4
+ from resource_engine.audit.export import (
5
+ AuditForwarder,
6
+ LoggingAuditExporter,
7
+ OutboxAuditSink,
8
+ SyslogAuditExporter,
9
+ entry_to_dict,
10
+ )
11
+ from resource_engine.audit.history import StateChange
12
+ from resource_engine.audit.janitor import AuditJanitor, AuditJanitorStats, Retention
13
+ from resource_engine.audit.model import AuditEntry, AuditEntryRead, AuditSeal, AuditSealRead
14
+ from resource_engine.audit.resource import AuditLogResource, AuditSealResource
15
+ from resource_engine.audit.seal import AuditProblem, AuditSealer, AuditVerification
16
+ from resource_engine.audit.sink import CompositeAuditSink, LoggingAuditSink, RepositoryAuditSink
17
+
18
+ __all__ = [
19
+ "AuditEntry",
20
+ "AuditEntryRead",
21
+ "AuditForwarder",
22
+ "AuditJanitor",
23
+ "AuditJanitorStats",
24
+ "AuditLogResource",
25
+ "AuditProblem",
26
+ "AuditSeal",
27
+ "AuditSealRead",
28
+ "AuditSealResource",
29
+ "AuditSealer",
30
+ "AuditVerification",
31
+ "CompositeAuditSink",
32
+ "LoggingAuditExporter",
33
+ "LoggingAuditSink",
34
+ "OutboxAuditSink",
35
+ "RepositoryAuditSink",
36
+ "Retention",
37
+ "StateChange",
38
+ "SyslogAuditExporter",
39
+ "entry_to_dict",
40
+ ]
@@ -0,0 +1,280 @@
1
+ """Shipping the audit trail to another system (a SIEM, a log platform, an
2
+ archive) without losing entries or sending ones that never happened.
3
+
4
+ ```python
5
+ sink = CompositeAuditSink(RepositoryAuditSink(uow_factory), OutboxAuditSink(uow_factory))
6
+ manager = ResourceManager(..., audit=sink)
7
+
8
+ forwarder = AuditForwarder(SyslogAuditExporter("siem.internal", 6514, transport="tcp"))
9
+ router = ProcessRunner(manager).router().include(forwarder.router())
10
+ ```
11
+
12
+ - ``OutboxAuditSink`` stores each entry as an ``AuditRecorded`` message in the
13
+ outbox, in the operation's own transaction: a change that rolls back leaves
14
+ no entry to ship, and a committed one always has one.
15
+ - ``AuditForwarder.router()`` hands each message to the exporters; run it
16
+ through ``MessageProcessor(manager=...)`` fed from the outbox (``ProcessFeed``)
17
+ or a broker, so an unreachable SIEM is retried and an entry is not shipped
18
+ twice. When one of several exporters fails, the retry repeats the others:
19
+ they dedupe by the entry's ``id``.
20
+ - Exporters (the ``AuditExporter`` port): ``LoggingAuditExporter`` and
21
+ ``SyslogAuditExporter`` (RFC 5424, JSON or CEF, UDP or TCP) here;
22
+ ``OtelAuditExporter`` in ``resource-engine-opentelemetry``;
23
+ ``HttpAuditExporter`` (JSON lines, Splunk HEC, Elastic) in
24
+ ``resource-engine-http``.
25
+
26
+ See docs/audit.md#shipping-entries.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import asyncio
32
+ import dataclasses
33
+ import json
34
+ import logging
35
+ import socket
36
+ from collections.abc import Callable, Sequence
37
+ from datetime import UTC, datetime
38
+ from typing import Any, Literal, override
39
+
40
+ from resource_engine.audit.model import AuditEntry
41
+ from resource_engine.audit.recorder import jsonable
42
+ from resource_engine.errors import RemoteCallFailed
43
+ from resource_engine.messaging.consumer import EventRouter
44
+ from resource_engine.messaging.envelope import EventEnvelope
45
+ from resource_engine.ports.audit import AuditExporter, AuditSink
46
+
47
+ AUDIT_EVENT = "AuditRecorded"
48
+
49
+ log = logging.getLogger("resource_engine.audit")
50
+
51
+
52
+ def entry_to_dict(entry: AuditEntry) -> dict[str, Any]:
53
+ """An audit entry as JSON-ready values."""
54
+ data: dict[str, Any] = jsonable(dataclasses.asdict(entry))
55
+ return data
56
+
57
+
58
+ def entry_from_dict(data: dict[str, Any]) -> AuditEntry:
59
+ """An audit entry back from :func:`entry_to_dict`'s output (unknown keys are ignored)."""
60
+ known = {f.name for f in dataclasses.fields(AuditEntry)}
61
+ values = {k: v for k, v in data.items() if k in known}
62
+ if isinstance(values.get("at"), str):
63
+ values["at"] = datetime.fromisoformat(values["at"])
64
+ return AuditEntry(**values)
65
+
66
+
67
+ class OutboxAuditSink(AuditSink):
68
+ """``AuditSink`` that queues each entry in the outbox for the exporters.
69
+
70
+ Args:
71
+ uow_factory: Opens a unit of work for entries written on their own
72
+ (refused attempts, audited reads); it needs an outbox.
73
+ """
74
+
75
+ def __init__(self, uow_factory: Callable[[], Any]) -> None:
76
+ self.uow_factory = uow_factory
77
+
78
+ @staticmethod
79
+ def envelopes(entries: Sequence[AuditEntry]) -> list[EventEnvelope]:
80
+ """One ``AuditRecorded`` envelope per entry."""
81
+ return [
82
+ EventEnvelope(
83
+ type=AUDIT_EVENT,
84
+ payload=entry_to_dict(entry),
85
+ occurred_at=entry.at,
86
+ correlation_id=entry.correlation_id,
87
+ resource=entry.resource,
88
+ key=f"audit:{entry.resource}",
89
+ )
90
+ for entry in entries
91
+ ]
92
+
93
+ @override
94
+ async def record(self, entries: Sequence[AuditEntry], *, uow: Any = None) -> None:
95
+ if not entries:
96
+ return
97
+ if uow is not None:
98
+ await uow.outbox().add(self.envelopes(entries))
99
+ return
100
+ async with self.uow_factory() as own:
101
+ await own.outbox().add(self.envelopes(entries))
102
+ await own.commit()
103
+
104
+
105
+ class AuditForwarder:
106
+ """Hands ``AuditRecorded`` messages to every exporter, in order."""
107
+
108
+ def __init__(self, *exporters: Any) -> None:
109
+ if not exporters:
110
+ raise ValueError("AuditForwarder needs at least one exporter")
111
+ self.exporters = exporters
112
+
113
+ async def handle(self, envelope: EventEnvelope) -> None:
114
+ """Export the entry an ``AuditRecorded`` message carries."""
115
+ entry = entry_from_dict(dict(envelope.payload))
116
+ for exporter in self.exporters:
117
+ await exporter.export([entry])
118
+
119
+ def router(self, *, name: str = "audit-export") -> EventRouter:
120
+ """A consumer router that forwards ``AuditRecorded`` messages."""
121
+ router = EventRouter(
122
+ ignore_unknown=True, name=name, description="Ships audit entries to other systems"
123
+ )
124
+ router.register(AUDIT_EVENT, lambda envelope: self.handle(envelope))
125
+ return router
126
+
127
+
128
+ class LoggingAuditExporter(AuditExporter):
129
+ """One JSON log line per entry (for a log shipper that tails the logs)."""
130
+
131
+ def __init__(self, logger: logging.Logger | None = None, level: int = logging.INFO) -> None:
132
+ self.logger = logger or log
133
+ self.level = level
134
+
135
+ @override
136
+ async def export(self, entries: Sequence[AuditEntry]) -> None:
137
+ for entry in entries:
138
+ self.logger.log(self.level, "audit %s", json.dumps(entry_to_dict(entry)))
139
+
140
+
141
+ # ------------------------------------------------------------------ syslog
142
+
143
+ #: RFC 5424 facility 13: log audit.
144
+ LOG_AUDIT = 13
145
+ _SEVERITY = {"ok": 6, "denied": 4, "failed": 3} # informational, warning, error
146
+
147
+
148
+ def cef(entry: AuditEntry, *, vendor: str, product: str, version: str) -> str:
149
+ """The entry in ArcSight Common Event Format, which most SIEMs parse."""
150
+
151
+ def header(value: Any) -> str:
152
+ return str(value).replace("\\", "\\\\").replace("|", "\\|")
153
+
154
+ def extension(value: Any) -> str:
155
+ text = value if isinstance(value, str) else json.dumps(value, default=str)
156
+ return text.replace("\\", "\\\\").replace("=", "\\=").replace("\n", "\\n").replace("\r", "")
157
+
158
+ severity = {"ok": 3, "denied": 6, "failed": 8}.get(entry.outcome, 5)
159
+ fields = {
160
+ "rt": int(entry.at.timestamp() * 1000),
161
+ "suser": entry.actor or "anonymous",
162
+ "act": entry.action,
163
+ "outcome": entry.outcome,
164
+ "cs1Label": "resource",
165
+ "cs1": entry.resource,
166
+ "cs2Label": "entityId",
167
+ "cs2": entry.entity_id or "",
168
+ "cs3Label": "tenant",
169
+ "cs3": entry.tenant or "",
170
+ "cs4Label": "roles",
171
+ "cs4": ",".join(entry.actor_roles),
172
+ "cs5Label": "correlationId",
173
+ "cs5": entry.correlation_id or "",
174
+ "cs6Label": "changes",
175
+ "cs6": entry.changes,
176
+ "externalId": entry.id,
177
+ }
178
+ ext = " ".join(f"{k}={extension(v)}" for k, v in fields.items())
179
+ name = f"{entry.resource} {entry.operation} {entry.outcome}"
180
+ return (
181
+ f"CEF:0|{header(vendor)}|{header(product)}|{header(version)}|"
182
+ f"{header(entry.resource + ':' + entry.action)}|{header(name)}|{severity}|{ext}"
183
+ )
184
+
185
+
186
+ class SyslogAuditExporter(AuditExporter):
187
+ """Sends entries as RFC 5424 syslog messages, the format SIEMs collect.
188
+
189
+ Args:
190
+ host / port: The collector (514 UDP or TCP; use TLS with a relay such as
191
+ rsyslog or a collector agent on the same host).
192
+ transport: ``udp`` (one datagram per entry) or ``tcp`` (octet counting).
193
+ format: ``cef`` (ArcSight Common Event Format) or ``json``.
194
+ app_name: The syslog APP-NAME and the CEF product.
195
+ hostname: The syslog HOSTNAME (default: this machine's).
196
+ timeout: Seconds for connecting and sending.
197
+ """
198
+
199
+ def __init__(
200
+ self,
201
+ host: str,
202
+ port: int = 514,
203
+ *,
204
+ transport: Literal["udp", "tcp"] = "udp",
205
+ format: Literal["cef", "json"] = "cef",
206
+ app_name: str = "resource-engine",
207
+ hostname: str | None = None,
208
+ timeout: float = 10.0,
209
+ ) -> None:
210
+ self.host = host
211
+ self.port = port
212
+ self.transport = transport
213
+ self.format = format
214
+ self.app_name = app_name
215
+ self.hostname = hostname or socket.gethostname()
216
+ self.timeout = timeout
217
+
218
+ def message(self, entry: AuditEntry) -> bytes:
219
+ """The RFC 5424 message for ``entry``."""
220
+ from resource_engine import __version__
221
+
222
+ priority = LOG_AUDIT * 8 + _SEVERITY.get(entry.outcome, 5)
223
+ timestamp = entry.at.astimezone(UTC).isoformat().replace("+00:00", "Z")
224
+ body = (
225
+ cef(entry, vendor="Resource Engine", product=self.app_name, version=__version__)
226
+ if self.format == "cef"
227
+ else json.dumps(entry_to_dict(entry))
228
+ )
229
+ msgid = "audit"
230
+ return (
231
+ f"<{priority}>1 {timestamp} {self.hostname} {self.app_name} - {msgid} - {body}"
232
+ ).encode()
233
+
234
+ @override
235
+ async def export(self, entries: Sequence[AuditEntry]) -> None:
236
+ messages = [self.message(e) for e in entries]
237
+ try:
238
+ if self.transport == "udp":
239
+ await asyncio.wait_for(self._udp(messages), self.timeout)
240
+ else:
241
+ await asyncio.wait_for(self._tcp(messages), self.timeout)
242
+ except (OSError, TimeoutError) as exc:
243
+ raise RemoteCallFailed(
244
+ f"syslog {self.host}:{self.port} failed: {exc or type(exc).__name__}",
245
+ service="syslog",
246
+ operation="export",
247
+ ) from exc
248
+
249
+ async def _udp(self, messages: list[bytes]) -> None:
250
+ loop = asyncio.get_running_loop()
251
+ transport, _ = await loop.create_datagram_endpoint(
252
+ asyncio.DatagramProtocol, remote_addr=(self.host, self.port)
253
+ )
254
+ try:
255
+ for message in messages:
256
+ transport.sendto(message)
257
+ finally:
258
+ transport.close()
259
+
260
+ async def _tcp(self, messages: list[bytes]) -> None:
261
+ _reader, writer = await asyncio.open_connection(self.host, self.port)
262
+ try:
263
+ for message in messages: # RFC 6587 octet counting
264
+ writer.write(f"{len(message)} ".encode() + message)
265
+ await writer.drain()
266
+ finally:
267
+ writer.close()
268
+ await writer.wait_closed()
269
+
270
+
271
+ __all__ = [
272
+ "AUDIT_EVENT",
273
+ "AuditForwarder",
274
+ "LoggingAuditExporter",
275
+ "OutboxAuditSink",
276
+ "SyslogAuditExporter",
277
+ "cef",
278
+ "entry_from_dict",
279
+ "entry_to_dict",
280
+ ]
@@ -0,0 +1,165 @@
1
+ """A record's state history, read from the audit trail. See docs/audit.md#history.
2
+
3
+ ``manager.history("invoices", 7)`` returns the record's state changes, oldest
4
+ first: its creation (with the initial state) and every committed transition,
5
+ with who made it and when. The caller needs to be able to ``get`` the record;
6
+ the audit trail itself stays restricted.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import itertools
12
+ from collections.abc import Sequence
13
+ from datetime import datetime
14
+ from typing import Any
15
+
16
+ from pydantic import BaseModel, Field
17
+
18
+ from resource_engine.application.query import ListQuery
19
+ from resource_engine.errors import HistoryNotAvailable
20
+
21
+ #: Audit operations that change a record's state.
22
+ STATE_OPERATIONS = ("create", "transition")
23
+ MAX_ENTRIES = 1000
24
+
25
+
26
+ class StateChange(BaseModel):
27
+ """One change of a record's state."""
28
+
29
+ at: datetime = Field(description="When it happened (UTC)")
30
+ operation: str = Field(description="create or transition")
31
+ machine: str | None = Field(
32
+ default=None, description="Which state machine (resources with several)"
33
+ )
34
+ event: str | None = Field(default=None, description="Transition event; null for create")
35
+ from_state: Any = Field(default=None, description="State before; null for create")
36
+ to_state: Any = Field(default=None, description="State after")
37
+ actor: str | None = Field(
38
+ default=None, description="Principal id, system:<job> or null (anonymous)"
39
+ )
40
+ correlation_id: str | None = Field(default=None, description="Shared with logs and events")
41
+
42
+
43
+ def history_resource(audit: Any) -> str | None:
44
+ """The audit resource a sink writes to (looking inside composite sinks)."""
45
+ if audit is None:
46
+ return None
47
+ resource = getattr(audit, "resource", None)
48
+ if isinstance(resource, str):
49
+ return resource
50
+ for sink in getattr(audit, "sinks", ()):
51
+ found = history_resource(sink)
52
+ if found is not None:
53
+ return found
54
+ return None
55
+
56
+
57
+ def require_history_resource(manager: Any, definition: Any) -> str:
58
+ """The audit resource to read a record's history from; refuses resources without a state
59
+ machine."""
60
+ if definition.state_field is None or definition.machine is None:
61
+ raise HistoryNotAvailable(
62
+ f"{definition.name} has no state machine, so it has no transition history",
63
+ hint="History covers resources with a state_machine; the audit_log has "
64
+ "every other change.",
65
+ doc="docs/audit.md#history",
66
+ )
67
+ resource = history_resource(manager.audit)
68
+ if resource is None or resource not in {d.name for d in manager.registry}:
69
+ raise HistoryNotAvailable(
70
+ "Transition history is read from the audit trail, which is not stored",
71
+ hint="Call registry.register_audit() and pass audit=True (or a "
72
+ "RepositoryAuditSink) to the ResourceManager.",
73
+ doc="docs/audit.md#history",
74
+ )
75
+ if not definition.audited:
76
+ raise HistoryNotAvailable(
77
+ f"{definition.name} is left out of the audit trail (audit = False)",
78
+ doc="docs/audit.md#history",
79
+ )
80
+ return resource
81
+
82
+
83
+ async def read_history(
84
+ uow: Any,
85
+ audit_resource: str,
86
+ definition: Any,
87
+ entity_id: Any,
88
+ tenant: Any = None,
89
+ machine: str | None = None,
90
+ ) -> list[StateChange]:
91
+ """A record's state changes, oldest first, from the audit trail."""
92
+ filters: dict[str, Any] = {
93
+ "resource": definition.name,
94
+ "entity_id": str(entity_id),
95
+ "outcome": "ok",
96
+ }
97
+ if tenant is not None:
98
+ filters["tenant"] = tenant
99
+ repo = uow.repository(audit_resource)
100
+ entries: list[Any] = []
101
+ offset = 0
102
+ while len(entries) < MAX_ENTRIES:
103
+ page = await repo.list(
104
+ ListQuery(offset=offset, limit=500, filters=filters, order_by=["at"])
105
+ )
106
+ entries += page.items
107
+ offset += len(page.items)
108
+ if not page.items or offset >= page.total:
109
+ break
110
+ machines = definition.machines
111
+ if machine is not None and machine not in machines:
112
+ from resource_engine.errors import UnknownTransition
113
+
114
+ raise UnknownTransition(
115
+ f"{definition.name} has no state machine {machine!r}",
116
+ hint=f"Machines: {', '.join(machines)}",
117
+ )
118
+ if len(machines) == 1:
119
+ return changes_from(entries, definition.state_field)
120
+ out: list[StateChange] = []
121
+ for name, runner in machines.items():
122
+ if machine is not None and name != machine:
123
+ continue
124
+ events = set(runner.info.events)
125
+ mine = [
126
+ e for e in entries if e.operation == "create" or _event(e.action, e.operation) in events
127
+ ]
128
+ for change in changes_from(mine, runner.state_field):
129
+ change.machine = name
130
+ out.append(change)
131
+ out.sort(key=lambda c: (c.at, c.operation != "create"))
132
+ return out
133
+
134
+
135
+ def changes_from(entries: Sequence[Any], state_field: str) -> list[StateChange]:
136
+ """The state changes recorded in audit entries, skipping masked values and other operations."""
137
+ changes: list[StateChange] = []
138
+ for entry in entries:
139
+ if entry.operation not in STATE_OPERATIONS:
140
+ continue
141
+ state = (entry.changes or {}).get(state_field) or {}
142
+ if not isinstance(state, dict) or "changed" in state: # masked
143
+ state = {}
144
+ changes.append(
145
+ StateChange(
146
+ at=entry.at,
147
+ operation=entry.operation,
148
+ event=_event(entry.action, entry.operation),
149
+ from_state=state.get("from"),
150
+ to_state=state.get("to"),
151
+ actor=entry.actor,
152
+ correlation_id=entry.correlation_id,
153
+ )
154
+ )
155
+ # entries written before creation recorded the initial state
156
+ for created, following in itertools.pairwise(changes):
157
+ if created.operation == "create" and created.to_state is None:
158
+ created.to_state = following.from_state
159
+ return changes
160
+
161
+
162
+ def _event(action: str | None, operation: str) -> str | None:
163
+ if operation != "transition" or not action:
164
+ return None
165
+ return action.split(":", 1)[1] if ":" in action else action