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,357 @@
1
+ """What to do with one inbound message: handle, skip, retry or dead-letter.
2
+
3
+ ``MessageProcessor`` is shared by pull consumers (``MessageConsumer``) and push
4
+ endpoints (``resource_engine_fastapi.build_event_receiver``), so both behave the
5
+ same way.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import inspect
11
+ import logging
12
+ import time
13
+ from collections.abc import Callable, Sequence
14
+ from dataclasses import dataclass, field
15
+ from enum import StrEnum
16
+ from typing import TYPE_CHECKING, Any, override
17
+
18
+ from resource_engine.domain.exceptions import DomainError
19
+ from resource_engine.errors import (
20
+ ConfigurationError,
21
+ EmailRejected,
22
+ InboxNotSupported,
23
+ MessageRejected,
24
+ NoHandler,
25
+ TemplateFailed,
26
+ TemplateNotFound,
27
+ TransactionDoomed,
28
+ ValidationFailed,
29
+ )
30
+ from resource_engine.logs import bind_log_context
31
+ from resource_engine.messaging.consumer import EventRouter
32
+ from resource_engine.ports.messaging import (
33
+ MessageHandler,
34
+ MessageObserver,
35
+ ReceivedMessage,
36
+ SupportsInbox,
37
+ )
38
+ from resource_engine.ports.unit_of_work import UnitOfWork
39
+ from resource_engine.tracing import get_tracer
40
+
41
+ if TYPE_CHECKING:
42
+ from resource_engine.application.manager import ResourceManager
43
+
44
+ log = logging.getLogger("resource_engine.messaging")
45
+
46
+ #: Errors that will fail again on every delivery: dead-letter them at once.
47
+ PERMANENT_ERRORS: tuple[type[BaseException], ...] = (
48
+ NoHandler,
49
+ MessageRejected,
50
+ DomainError,
51
+ ValidationFailed,
52
+ EmailRejected,
53
+ TemplateNotFound,
54
+ TemplateFailed,
55
+ )
56
+
57
+
58
+ class Outcome(StrEnum):
59
+ """What happened to a message: acknowledged, a duplicate, to retry, or dead-lettered."""
60
+
61
+ ACK = "ack"
62
+ DUPLICATE = "duplicate"
63
+ RETRY = "retry"
64
+ DEAD_LETTER = "dead_letter"
65
+
66
+ @property
67
+ def settled(self) -> bool:
68
+ """True when the message must be removed from the broker."""
69
+ return self in (Outcome.ACK, Outcome.DUPLICATE)
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class RetryPolicy:
74
+ """Exponential backoff with a delivery limit.
75
+
76
+ ``delay(n)`` is the wait before delivery ``n + 1``. When ``delivery_count``
77
+ reaches ``max_deliveries`` the message is dead-lettered. Brokers that do not
78
+ report delivery counts rely on their own redrive policy instead.
79
+ """
80
+
81
+ max_deliveries: int = 5
82
+ base_delay: float = 1.0
83
+ factor: float = 2.0
84
+ max_delay: float = 300.0
85
+
86
+ def delay(self, delivery_count: int | None) -> float:
87
+ """Seconds to wait before the next delivery."""
88
+ n = max((delivery_count or 1) - 1, 0)
89
+ return min(self.base_delay * self.factor**n, self.max_delay)
90
+
91
+ def exhausted(self, delivery_count: int | None) -> bool:
92
+ """Whether the message has used up its deliveries."""
93
+ return delivery_count is not None and delivery_count >= self.max_deliveries
94
+
95
+
96
+ @dataclass(frozen=True)
97
+ class ProcessResult:
98
+ """What to do with a message.
99
+
100
+ ``blocked`` is true when the handler did not run because an earlier message
101
+ with the same key failed in this batch (``outcome`` is then ``RETRY``).
102
+ """
103
+
104
+ outcome: Outcome
105
+ error: str | None = None
106
+ delay_seconds: float = 0.0
107
+ blocked: bool = False
108
+ exception: BaseException | None = field(default=None, compare=False, repr=False)
109
+
110
+
111
+ class MessageProcessor:
112
+ """Runs the handler for one message and decides its outcome.
113
+
114
+ Args:
115
+ handler: An ``EventRouter`` or a single ``async (envelope) -> None``.
116
+ name: Consumer name; inbox entries are kept per consumer, so two consumers
117
+ of the same event each process it once.
118
+ manager: Run each message in ``manager.transaction()``: the inbox check,
119
+ every manager call of the handler and the inbox mark commit together,
120
+ so a message has its effect once. Its unit of work needs ``inbox()``.
121
+ inbox: Without ``manager``: unit of work factory whose units expose
122
+ ``inbox()``. Already-processed envelope ids are acknowledged without
123
+ running the handler, but the mark is written after the handler, in
124
+ its own transaction: a crash between the two can run a handler twice.
125
+ retry: Backoff and delivery limit.
126
+ permanent_errors: Exceptions that dead-letter immediately.
127
+ observers: Called after every message with ``(consumer, message, result,
128
+ seconds)`` (metrics); failures are logged and ignored.
129
+ """
130
+
131
+ def __init__(
132
+ self,
133
+ handler: EventRouter | MessageHandler,
134
+ *,
135
+ name: str,
136
+ manager: ResourceManager | None = None,
137
+ inbox: Callable[[], UnitOfWork] | None = None,
138
+ retry: RetryPolicy | None = None,
139
+ permanent_errors: tuple[type[BaseException], ...] = PERMANENT_ERRORS,
140
+ observers: Sequence[MessageObserver] = (),
141
+ ) -> None:
142
+ if manager is not None and inbox is not None:
143
+ raise ConfigurationError(
144
+ "Pass either manager= (one transaction) or inbox=, not both",
145
+ hint="With manager=, the inbox of the manager's unit of work is used.",
146
+ doc="docs/messaging.md#exactly-once-effects",
147
+ )
148
+ self.dispatch = handler.dispatch if isinstance(handler, EventRouter) else handler
149
+ self.name = name
150
+ self.manager = manager
151
+ self.inbox = inbox
152
+ self.retry = retry or RetryPolicy()
153
+ self.permanent_errors = permanent_errors
154
+ self.observers = list(observers)
155
+
156
+ async def _inbox_call(self, method: str, message_id: str) -> Any:
157
+ assert self.inbox is not None
158
+ async with self.inbox() as uow:
159
+ if not isinstance(uow, SupportsInbox):
160
+ raise InboxNotSupported(
161
+ f"{type(uow).__name__} has no inbox()",
162
+ hint="Pass inbox_table=inbox_table(metadata) to the SQLAlchemy unit of "
163
+ "work, or drop inbox= to run without de-duplication.",
164
+ )
165
+ result = await getattr(uow.inbox(), method)(self.name, [message_id])
166
+ if method == "mark_processed":
167
+ await uow.commit()
168
+ return result
169
+
170
+ async def process(self, message: ReceivedMessage) -> ProcessResult:
171
+ """Run the handler for ``message`` and decide its outcome: ack, retry or dead-letter."""
172
+ started = time.perf_counter()
173
+ envelope = message.envelope
174
+ attributes: dict[str, Any] = {"resource_engine.consumer": self.name}
175
+ if envelope is not None:
176
+ attributes |= {
177
+ "messaging.message.id": envelope.id,
178
+ "resource_engine.event_type": envelope.type,
179
+ "resource_engine.correlation_id": envelope.correlation_id or "",
180
+ }
181
+ if message.delivery_count is not None:
182
+ attributes["messaging.message.delivery_count"] = message.delivery_count
183
+ with bind_log_context(
184
+ consumer=self.name,
185
+ message_id=envelope.id if envelope else None,
186
+ event_type=envelope.type if envelope else None,
187
+ correlation_id=envelope.correlation_id if envelope else None,
188
+ ):
189
+ async with get_tracer().span(
190
+ f"{self.name} process",
191
+ kind="consumer",
192
+ attributes=attributes,
193
+ parent=envelope.trace if envelope is not None else None,
194
+ ) as span:
195
+ result = await self._process(message)
196
+ span.set_attribute("resource_engine.outcome", result.outcome.value)
197
+ if result.exception is not None:
198
+ from resource_engine.reporting import report_error
199
+
200
+ await report_error(
201
+ result.exception,
202
+ where="consumer",
203
+ force=result.outcome is Outcome.DEAD_LETTER,
204
+ outcome=result.outcome.value,
205
+ delivery_count=message.delivery_count,
206
+ )
207
+ if result.outcome in (Outcome.RETRY, Outcome.DEAD_LETTER) and result.error:
208
+ span.record_error(result.error)
209
+ await self.observe(message, result, time.perf_counter() - started)
210
+ return result
211
+
212
+ async def observe(
213
+ self, message: ReceivedMessage, result: ProcessResult, seconds: float
214
+ ) -> None:
215
+ """Tell every observer the outcome; their failures are logged."""
216
+ for observer in self.observers:
217
+ try:
218
+ outcome = observer(self.name, message, result, seconds)
219
+ if inspect.isawaitable(outcome):
220
+ await outcome
221
+ except Exception:
222
+ log.exception("Message observer %r failed", observer)
223
+
224
+ def _failure(self, message: ReceivedMessage, exc: BaseException) -> ProcessResult:
225
+ envelope = message.envelope
226
+ assert envelope is not None
227
+ cause = exc.__cause__ if isinstance(exc, TransactionDoomed) and exc.__cause__ else exc
228
+ if isinstance(cause, self.permanent_errors):
229
+ log.error("Message %s (%s) rejected: %s", envelope.id, envelope.type, cause)
230
+ return ProcessResult(
231
+ Outcome.DEAD_LETTER, f"{type(cause).__name__}: {cause}", exception=cause
232
+ )
233
+ error = f"{type(cause).__name__}: {cause}"
234
+ if self.retry.exhausted(message.delivery_count):
235
+ log.error("Message %s failed %s times: %s", envelope.id, message.delivery_count, error)
236
+ return ProcessResult(Outcome.DEAD_LETTER, error, exception=cause)
237
+ delay = self.retry.delay(message.delivery_count)
238
+ log.warning("Message %s failed, retrying in %.1fs: %s", envelope.id, delay, error)
239
+ return ProcessResult(Outcome.RETRY, error, delay, exception=cause)
240
+
241
+ async def _transactional(self, message: ReceivedMessage) -> ProcessResult:
242
+ """Inbox check, handler and inbox mark in one ``manager.transaction()``."""
243
+ envelope = message.envelope
244
+ assert envelope is not None and self.manager is not None
245
+
246
+ class _Duplicate(Exception):
247
+ pass
248
+
249
+ try:
250
+ async with self.manager.transaction() as tx:
251
+ if not isinstance(tx.uow, SupportsInbox):
252
+ raise InboxNotSupported(
253
+ f"{type(tx.uow).__name__} has no inbox()",
254
+ hint="Pass inbox_table=inbox_table(metadata) to the SQLAlchemy unit "
255
+ "of work, or use inbox= without manager=.",
256
+ )
257
+ inbox = tx.uow.inbox()
258
+ if envelope.id in await inbox.processed(self.name, [envelope.id]):
259
+ raise _Duplicate
260
+ result = self.dispatch(envelope)
261
+ if inspect.isawaitable(result):
262
+ await result
263
+ # a concurrent consumer may have committed it meanwhile: undo ours
264
+ if envelope.id in await inbox.processed(self.name, [envelope.id]):
265
+ raise _Duplicate
266
+ await inbox.mark_processed(self.name, [envelope.id])
267
+ except _Duplicate:
268
+ return ProcessResult(Outcome.DUPLICATE)
269
+ except InboxNotSupported:
270
+ raise
271
+ except Exception as exc: # handler, doomed transaction or commit (a racing consumer)
272
+ return self._failure(message, exc)
273
+ return ProcessResult(Outcome.ACK)
274
+
275
+ async def _process(self, message: ReceivedMessage) -> ProcessResult:
276
+ envelope = message.envelope
277
+ if envelope is None:
278
+ log.error("Undecodable message %s: %s", message.message_id, message.error)
279
+ return ProcessResult(Outcome.DEAD_LETTER, f"undecodable: {message.error}")
280
+ if self.manager is not None:
281
+ return await self._transactional(message)
282
+
283
+ if self.inbox is not None and envelope.id in await self._inbox_call(
284
+ "processed", envelope.id
285
+ ):
286
+ return ProcessResult(Outcome.DUPLICATE)
287
+
288
+ try:
289
+ result = self.dispatch(envelope)
290
+ if inspect.isawaitable(result):
291
+ await result
292
+ except Exception as exc:
293
+ return self._failure(message, exc)
294
+
295
+ if self.inbox is not None:
296
+ try:
297
+ await self._inbox_call("mark_processed", envelope.id)
298
+ except InboxNotSupported:
299
+ raise
300
+ except Exception: # e.g. a concurrent consumer marked it first
301
+ log.warning("Could not record %s in the inbox", envelope.id, exc_info=True)
302
+ return ProcessResult(Outcome.ACK)
303
+
304
+
305
+ class ActivityMessageObserver(MessageObserver):
306
+ """``MessageObserver`` recording each consumer's handling of each message
307
+ in an ``ActivityLog``, for the explorer's "who handled this event"
308
+ (docs/explorer.md). Undecodable messages have no event and aren't recorded."""
309
+
310
+ def __init__(self, log: Any) -> None:
311
+ self.log = log
312
+
313
+ @override
314
+ async def __call__(
315
+ self, consumer: str, message: ReceivedMessage, result: ProcessResult, seconds: float
316
+ ) -> None:
317
+ from resource_engine.ports.activity import DeliveryRecord
318
+
319
+ envelope = message.envelope
320
+ if envelope is None:
321
+ return
322
+ await self.log.record_delivery(
323
+ DeliveryRecord(
324
+ consumer=consumer,
325
+ message_id=envelope.id,
326
+ event_type=envelope.type,
327
+ outcome=result.outcome.value,
328
+ seconds=seconds,
329
+ error=result.error,
330
+ )
331
+ )
332
+
333
+
334
+ class LoggingObserver(MessageObserver):
335
+ """``MessageObserver`` writing one log line per message (logger
336
+ ``resource_engine.messaging.metrics``): outcome, type, key, delivery count
337
+ and duration. A model for metrics adapters (OpenTelemetry, Prometheus)."""
338
+
339
+ def __init__(self, logger: logging.Logger | None = None, level: int = logging.INFO) -> None:
340
+ self.logger = logger or logging.getLogger("resource_engine.messaging.metrics")
341
+ self.level = level
342
+
343
+ @override
344
+ def __call__(
345
+ self, consumer: str, message: ReceivedMessage, result: ProcessResult, seconds: float
346
+ ) -> None:
347
+ envelope = message.envelope
348
+ self.logger.log(
349
+ self.level,
350
+ "consumer=%s outcome=%s type=%s key=%s deliveries=%s seconds=%.4f",
351
+ consumer,
352
+ result.outcome.value,
353
+ envelope.type if envelope else None,
354
+ envelope.key if envelope else None,
355
+ message.delivery_count,
356
+ seconds,
357
+ )
@@ -0,0 +1,318 @@
1
+ """Publishing an event by hand: the explorer's PUB rows (docs/explorer.md#pub).
2
+
3
+ Testing a consumer often needs one particular event: an invoice approved
4
+ with an odd amount, an old schema version, a payment that never arrives.
5
+ ``EventPublishing`` lets an authorized person write that event and send it
6
+ the way the application sends its own:
7
+
8
+ ```python
9
+ publishing = EventPublishing(manager, consumers=[billing_router], allow_publish=True)
10
+ problems = await publishing.validate("InvoiceApproved", 2, payload, actor=user) # dry run
11
+ envelope = await publishing.publish("InvoiceApproved", 2, payload, actor=user)
12
+ ```
13
+
14
+ - **Which events:** those the application's resources declare
15
+ (``Resource.events``), in each version they publish (``schema_version`` and
16
+ ``previous_versions``). Engine events (``ResourceCreated``...) are not
17
+ published by hand: they describe changes that must really happen.
18
+ - **Permission:** ``events:publish:<Event>``, *exact*: no wildcard grants it,
19
+ only a role or policy naming it (``register_explorer`` adds the actions).
20
+ Even then, publishing needs ``allow_publish=True``; a dry run doesn't.
21
+ - **Dry run:** the payload is validated against the event's own model for
22
+ that version, then against each consumer's payload model for it (the
23
+ ``EventRouter``s given as ``consumers``). Problems come back with the check,
24
+ the field's path and the message. Nothing is written. Only the event's own
25
+ problems stop a publication: one a consumer will refuse can still be sent,
26
+ to test how it copes (retries, dead letters).
27
+ - **Publishing:** the envelope goes into the outbox in a transaction of its
28
+ own, with an audit entry, exactly as an operation's events do; the relay
29
+ sends it to the brokers. It never goes straight to a broker. The envelope
30
+ is tagged ``origin=console`` and ``publishedby=<actor>``. Publishing the
31
+ current version also publishes the older ones the event keeps, converted,
32
+ like any other publication; an older version is published alone.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import contextlib
38
+ import dataclasses
39
+ from collections.abc import Sequence
40
+ from dataclasses import dataclass, field
41
+ from datetime import UTC, datetime
42
+ from typing import Any
43
+
44
+ from pydantic import TypeAdapter, ValidationError
45
+
46
+ from resource_engine.errors import ConfigurationError, EntityNotFound, PermissionDenied
47
+ from resource_engine.explorer import publish_action, require
48
+ from resource_engine.messaging.envelope import EventEnvelope, EventSerializer, to_jsonable
49
+ from resource_engine.schema_examples import example
50
+
51
+
52
+ def publishable_events(registry: Any) -> list[type]:
53
+ """The events people may publish by hand: those the application's
54
+ resources declare, not the engine's own."""
55
+ return [e for e in registry.event_types() if not e.__module__.startswith("resource_engine.")]
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class Problem:
60
+ """Why a payload doesn't fit: ``check`` is ``event`` (its own model) or
61
+ ``consumer:<name>``; ``path`` the field (``amount``, ``lines.0.qty``)."""
62
+
63
+ check: str
64
+ path: str
65
+ message: str
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class PublishableVersion:
70
+ """A version of an event that can be published, with its schema and an example payload."""
71
+
72
+ version: str
73
+ schema: dict[str, Any]
74
+ example: dict[str, Any]
75
+ deprecated: bool = False
76
+
77
+
78
+ @dataclass(frozen=True)
79
+ class PublishableEvent:
80
+ """An event type that can be published from the explorer, with its versions."""
81
+
82
+ type: str
83
+ resource: str | None
84
+ summary: str
85
+ versions: tuple[PublishableVersion, ...] = field(default_factory=tuple)
86
+
87
+
88
+ def _fields_schema(model: Any) -> dict[str, Any]:
89
+ """The JSON schema of an event's payload (its fields but ``occurred_at``)."""
90
+ schema = TypeAdapter(model).json_schema()
91
+ properties = dict(schema.get("properties", {}))
92
+ properties.pop("occurred_at", None)
93
+ required = [r for r in schema.get("required", []) if r != "occurred_at"]
94
+ out = {**schema, "properties": properties}
95
+ if required:
96
+ out["required"] = required
97
+ else:
98
+ out.pop("required", None)
99
+ return out
100
+
101
+
102
+ class EventPublishing:
103
+ """Dry runs and publications of the application's events, by hand.
104
+
105
+ Args:
106
+ manager: The ``ResourceManager``: its registry, authorizer, outbox and audit.
107
+ consumers: ``EventRouter``s whose payload models a dry run checks too.
108
+ allow_publish: Publishing for real (a dry run is always possible).
109
+ open: Without an authorizer, allow it anyway (local development only).
110
+ """
111
+
112
+ def __init__(
113
+ self,
114
+ manager: Any,
115
+ *,
116
+ consumers: Sequence[Any] = (),
117
+ allow_publish: bool = False,
118
+ open: bool = False,
119
+ ) -> None:
120
+ self.manager = manager
121
+ self.consumers = list(consumers)
122
+ self.allow_publish = allow_publish
123
+ self.open = open
124
+ self.serializer = EventSerializer()
125
+ self.events = {e.__name__: e for e in publishable_events(manager.registry)}
126
+ self.owners: dict[str, str] = {}
127
+ for definition in manager.registry:
128
+ for event in definition.resource_cls.events:
129
+ self.owners.setdefault(event.__name__, definition.name)
130
+
131
+ # ------------------------------------------------------------ catalogue
132
+
133
+ def _event(self, event_type: str) -> type:
134
+ event = self.events.get(event_type)
135
+ if event is None:
136
+ raise EntityNotFound(
137
+ f"No event {event_type!r} can be published",
138
+ hint=f"Publishable events: {', '.join(sorted(self.events)) or '(none)'}",
139
+ )
140
+ return event
141
+
142
+ def _model(self, event_type: str, version: int | str | None) -> tuple[Any, int]:
143
+ """The payload model of that version, and the version as a number."""
144
+ event = self._event(event_type)
145
+ current = int(getattr(event, "schema_version", 1))
146
+ number = current if version in (None, "") else int(str(version).lstrip("v"))
147
+ if number == current:
148
+ return event, number
149
+ older = getattr(event, "previous_versions", {}) or {}
150
+ if number not in older:
151
+ raise EntityNotFound(
152
+ f"{event_type} has no version {number}",
153
+ hint=f"Versions: {sorted([current, *older])}",
154
+ )
155
+ return older[number].schema, number
156
+
157
+ def catalogue(self) -> list[PublishableEvent]:
158
+ """The events that can be published, with their versions."""
159
+ from resource_engine.domain.events import event_doc
160
+
161
+ out = []
162
+ for name, event in sorted(self.events.items()):
163
+ current = int(getattr(event, "schema_version", 1))
164
+ older = getattr(event, "previous_versions", {}) or {}
165
+ versions = []
166
+ for number in sorted([current, *older]):
167
+ model, _ = self._model(name, number)
168
+ schema = _fields_schema(model)
169
+ deprecation = (
170
+ older[number].deprecation
171
+ if number in older
172
+ else getattr(event, "deprecation", None)
173
+ )
174
+ versions.append(
175
+ PublishableVersion(
176
+ str(number),
177
+ schema,
178
+ example(schema, schema.get("$defs", {})) or {},
179
+ deprecation is not None,
180
+ )
181
+ )
182
+ doc = (event_doc(event) or "").strip().split("\n\n")[0].replace("\n", " ")
183
+ out.append(PublishableEvent(name, self.owners.get(name), doc, tuple(versions)))
184
+ return out
185
+
186
+ # --------------------------------------------------------------- checks
187
+
188
+ async def _require(self, actor: Any, event_type: str) -> None:
189
+ self._event(event_type) # an unknown type is "not found", not "not allowed"
190
+ await require(self.manager, actor, publish_action(event_type).name, open=self.open)
191
+
192
+ def problems(self, event_type: str, version: int | str | None, payload: Any) -> list[Problem]:
193
+ """What doesn't fit in ``payload`` (no permission check, nothing written)."""
194
+ model, number = self._model(event_type, version)
195
+ if not isinstance(payload, dict):
196
+ return [Problem("event", "", "The payload must be a JSON object")]
197
+ out = _validate("event", model, payload)
198
+ for router in self.consumers:
199
+ wanted = router.schema_version(event_type)
200
+ payload_type = router.payload_type(event_type)
201
+ if payload_type is None or (wanted is not None and wanted != str(number)):
202
+ continue
203
+ name = f"consumer:{getattr(router, 'name', None) or type(router).__name__}"
204
+ out += _validate(name, payload_type, payload)
205
+ return out
206
+
207
+ async def validate(
208
+ self, event_type: str, version: int | str | None, payload: Any, *, actor: Any = None
209
+ ) -> list[Problem]:
210
+ """A dry run: the permission, then ``problems``."""
211
+ await self._require(actor, event_type)
212
+ return self.problems(event_type, version, payload)
213
+
214
+ # ----------------------------------------------------------- publishing
215
+
216
+ async def publish(
217
+ self, event_type: str, version: int | str | None, payload: Any, *, actor: Any = None
218
+ ) -> list[EventEnvelope]:
219
+ """Validate and publish through the outbox, as ``actor``. Returns the
220
+ envelopes written (the current version brings its older ones)."""
221
+ await self._require(actor, event_type)
222
+ action = publish_action(event_type).name
223
+ if not self.allow_publish:
224
+ await self.manager.audit_event(actor, action, "denied", details={"why": "disabled"})
225
+ raise PermissionDenied(
226
+ "Publishing events by hand is turned off",
227
+ details={"action": action},
228
+ hint="EventPublishing(manager, allow_publish=True) turns it on.",
229
+ )
230
+ # a consumer that can't read it is worth testing (dead letters): only the
231
+ # event's own model blocks a publication
232
+ problems = [p for p in self.problems(event_type, version, payload) if p.check == "event"]
233
+ if problems:
234
+ from resource_engine.errors import ValidationFailed
235
+
236
+ raise ValidationFailed(
237
+ f"The {event_type} payload doesn't fit",
238
+ details=[dataclasses.asdict(p) for p in problems],
239
+ )
240
+ envelopes = self._envelopes(event_type, version, payload, actor)
241
+ async with self.manager.transaction() as tx:
242
+ outbox = getattr(tx.uow, "outbox", None)
243
+ if outbox is None:
244
+ raise ConfigurationError(
245
+ "Publishing events by hand needs a unit of work with an outbox",
246
+ hint="Events go out the way the application's own do: OutboxDelivery and "
247
+ "OutboxRelay.",
248
+ doc="docs/explorer.md#pub",
249
+ )
250
+ await outbox().add(envelopes)
251
+ await self.manager.audit_event(
252
+ actor,
253
+ action,
254
+ details={
255
+ "event": event_type,
256
+ "version": envelopes[0].schema_version,
257
+ "envelopes": [e.id for e in envelopes],
258
+ "payload": envelopes[0].payload,
259
+ },
260
+ uow=tx.uow,
261
+ )
262
+ live = getattr(self.manager.delivery, "live", None)
263
+ if live is not None: # the explorer's SUB rows see it at once, like any event
264
+ with contextlib.suppress(Exception): # best effort, as for OutboxDelivery
265
+ await live.publish(envelopes)
266
+ return envelopes
267
+
268
+ def _envelopes(
269
+ self, event_type: str, version: int | str | None, payload: dict[str, Any], actor: Any
270
+ ) -> list[EventEnvelope]:
271
+ from resource_engine.audit.recorder import actor_id
272
+
273
+ model, number = self._model(event_type, version)
274
+ who = actor if isinstance(actor, str) else actor_id(actor)
275
+ tags = {"origin": "console", **({"publishedby": str(who)} if who else {})}
276
+ resource = self.owners.get(event_type)
277
+ event = self._event(event_type)
278
+ if model is event:
279
+ instance = TypeAdapter(event).validate_python(payload)
280
+ envelopes = self.serializer.to_envelopes(instance, resource=resource)
281
+ else:
282
+ data = to_jsonable(TypeAdapter(model).dump_python(
283
+ TypeAdapter(model).validate_python(payload), mode="json"
284
+ )) # fmt: skip
285
+ data.pop("occurred_at", None)
286
+ entity_id = data.get("entity_id")
287
+ key = f"{resource}:{entity_id}" if resource and entity_id is not None else resource
288
+ envelopes = [
289
+ EventEnvelope(
290
+ type=event_type,
291
+ payload=data,
292
+ occurred_at=datetime.now(UTC),
293
+ resource=resource,
294
+ key=key,
295
+ schema_version=str(number),
296
+ )
297
+ ]
298
+ return [dataclasses.replace(e, tags=tags) for e in envelopes]
299
+
300
+
301
+ def _validate(check: str, model: Any, payload: dict[str, Any]) -> list[Problem]:
302
+ try:
303
+ TypeAdapter(model).validate_python(payload)
304
+ except ValidationError as exc:
305
+ return [
306
+ Problem(check, ".".join(str(p) for p in error["loc"]), error["msg"])
307
+ for error in exc.errors()
308
+ ]
309
+ return []
310
+
311
+
312
+ __all__ = [
313
+ "EventPublishing",
314
+ "Problem",
315
+ "PublishableEvent",
316
+ "PublishableVersion",
317
+ "publishable_events",
318
+ ]