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,61 @@
1
+ """Tracing port: spans around operations, messages and jobs.
2
+
3
+ The core never imports a tracing library. It asks the configured ``Tracer``
4
+ (``resource_engine.tracing.set_tracer``) for spans, and puts the current trace
5
+ context on every event envelope so consumers continue the trace. The
6
+ OpenTelemetry implementation is ``resource_engine_opentelemetry.OtelTracer``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Mapping
12
+ from contextlib import AbstractAsyncContextManager
13
+ from typing import Any, Literal, Protocol
14
+
15
+ type SpanKind = Literal["internal", "client", "producer", "consumer"]
16
+
17
+
18
+ class Span(Protocol):
19
+ """A span of a trace, as tracers hand it out."""
20
+
21
+ def set_attribute(self, key: str, value: Any) -> None:
22
+ """Attach ``key``: ``value`` to the span."""
23
+ ...
24
+
25
+ def record_error(self, error: BaseException | str) -> None:
26
+ """Mark the span as failed. Exceptions raised through ``Tracer.span``
27
+ are recorded by the tracer itself."""
28
+ ...
29
+
30
+
31
+ class Tracer(Protocol):
32
+ """Port: opens spans for operations, calls and messages."""
33
+
34
+ def span(
35
+ self,
36
+ name: str,
37
+ *,
38
+ kind: SpanKind = "internal",
39
+ attributes: Mapping[str, Any] | None = None,
40
+ parent: Mapping[str, str] | None = None,
41
+ ) -> AbstractAsyncContextManager[Span]:
42
+ """A child of the current span, or of ``parent`` (a carrier from
43
+ ``inject``, e.g. an envelope's ``trace``). It is the current span inside
44
+ the block; an exception leaving the block is recorded and re-raised."""
45
+ ...
46
+
47
+ def current(self) -> Span:
48
+ """The current span (a no-op span when there is none)."""
49
+ ...
50
+
51
+ def inject(self) -> dict[str, str]:
52
+ """The current trace context as a carrier (W3C ``traceparent`` and
53
+ ``tracestate``); empty when there is no span."""
54
+ ...
55
+
56
+
57
+ __all__ = [
58
+ "Span",
59
+ "SpanKind",
60
+ "Tracer",
61
+ ]
@@ -0,0 +1,46 @@
1
+ """Port: the transaction boundary of an operation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from types import TracebackType
7
+ from typing import Any, Protocol, Self
8
+
9
+ from resource_engine.ports.repository import Repository
10
+
11
+
12
+ class UnitOfWork(Protocol):
13
+ """A transaction boundary that hands out repositories.
14
+
15
+ Leaving the ``async with`` block without calling ``commit`` must roll back.
16
+ """
17
+
18
+ def repository(self, resource_name: str) -> Repository[Any]:
19
+ """The repository of ``resource_name``, in this transaction."""
20
+ ...
21
+
22
+ async def commit(self) -> None:
23
+ """Make the transaction's changes permanent."""
24
+ ...
25
+
26
+ async def rollback(self) -> None:
27
+ """Discard the transaction's changes."""
28
+ ...
29
+
30
+ async def __aenter__(self) -> Self: ...
31
+
32
+ async def __aexit__(
33
+ self,
34
+ exc_type: type[BaseException] | None,
35
+ exc: BaseException | None,
36
+ tb: TracebackType | None,
37
+ ) -> None: ...
38
+
39
+
40
+ type UnitOfWorkFactory = Callable[[], UnitOfWork]
41
+
42
+
43
+ __all__ = [
44
+ "UnitOfWork",
45
+ "UnitOfWorkFactory",
46
+ ]
@@ -0,0 +1,408 @@
1
+ """Process managers: long-running processes across resources, as resources.
2
+
3
+ A process is a ``Resource`` whose records are its running instances. Its
4
+ state machine holds the steps, its timers the timeouts, its hooks the
5
+ compensations. It reacts to events (the engine's, its own domain events, other
6
+ services') with handlers that move the instance and act on other resources
7
+ through the manager:
8
+
9
+ ```python
10
+ class InvoicePaymentProcess(Process):
11
+ model = InvoicePayment
12
+ schemas = {"create": PaymentStart, "read": PaymentRead}
13
+ operations = ["list", "get", "create"]
14
+ state_machine = PaymentFlow
15
+ correlation = "invoice_id"
16
+ reacts = [
17
+ On("TransitionExecuted", start_payment, resource="invoices", transition="approve",
18
+ start=True),
19
+ On("PaymentReceived", record_payment, key="invoice_id", payload=PaymentReceived),
20
+ ]
21
+ ```
22
+
23
+ ``ProcessRunner(manager).router()`` is the ``EventRouter`` of every process;
24
+ run it with ``MessageProcessor(router, name=..., manager=manager)``
25
+ (one transaction with the inbox: exactly-once effects) from a broker
26
+ consumer, or from the outbox with ``ProcessFeed``. See docs/processes.md.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import inspect
32
+ import logging
33
+ import typing
34
+ from collections.abc import Awaitable, Callable, Sequence
35
+ from dataclasses import dataclass
36
+ from typing import TYPE_CHECKING, Any, ClassVar
37
+
38
+ from pydantic import TypeAdapter
39
+
40
+ from resource_engine.application.query import ListQuery
41
+ from resource_engine.application.resource import Resource, ResourceDefinition
42
+ from resource_engine.application.settings import Internal
43
+ from resource_engine.domain.events import DomainEvent
44
+ from resource_engine.errors import ConfigurationError, PublishFailed
45
+ from resource_engine.messaging.consumer import EventRouter
46
+ from resource_engine.messaging.envelope import EventEnvelope
47
+ from resource_engine.ports.messaging import ReceivedMessage
48
+
49
+ if TYPE_CHECKING:
50
+ from resource_engine.application.manager import ResourceManager
51
+ from resource_engine.messaging.processing import MessageProcessor
52
+
53
+ logger = logging.getLogger("resource_engine.processes")
54
+ DOC = "docs/processes.md"
55
+
56
+ type StepHandler = Callable[[ProcessStep], Awaitable[None] | None]
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class On:
61
+ """A process reacts to an event.
62
+
63
+ Args:
64
+ event: Event type (``"PaymentReceived"``) or a ``DomainEvent`` class.
65
+ handler: ``(step: ProcessStep) -> None`` (sync or async).
66
+ key: Where the correlation key is in the payload (dotted path; default
67
+ ``entity_id``, the record of an engine event), or ``(envelope) -> key``.
68
+ resource / transition / action: Only engine events of this resource,
69
+ transition or action.
70
+ start: Run the handler even when no instance matches the key (to start
71
+ one with ``step.start()``). Otherwise such events are ignored.
72
+ payload: Validate the payload against this model; ``step.payload`` is
73
+ then the parsed value (invalid payloads are dead-lettered).
74
+ description: What the step does, for the generated docs (default: the
75
+ handler's docstring).
76
+ """
77
+
78
+ event: str | type[DomainEvent]
79
+ handler: StepHandler
80
+ key: str | Callable[[EventEnvelope], Any] = "entity_id"
81
+ resource: str | None = None
82
+ transition: str | None = None
83
+ action: str | None = None
84
+ start: bool = False
85
+ payload: Any = None
86
+ description: str | None = None
87
+
88
+ @property
89
+ def event_type(self) -> str:
90
+ """The name of the event reacted to."""
91
+ return self.event if isinstance(self.event, str) else self.event.__name__
92
+
93
+ def matches(self, envelope: EventEnvelope) -> bool:
94
+ """Whether ``envelope`` triggers this reaction."""
95
+ payload = envelope.payload
96
+ if self.resource is not None and (envelope.resource or payload.get("resource")) != (
97
+ self.resource
98
+ ):
99
+ return False
100
+ if self.transition is not None and payload.get("transition") != self.transition:
101
+ return False
102
+ return self.action is None or payload.get("action") == self.action
103
+
104
+ def key_of(self, envelope: EventEnvelope) -> Any:
105
+ """The process instance key in ``envelope``."""
106
+ if callable(self.key):
107
+ return self.key(envelope)
108
+ value: Any = envelope.payload
109
+ for part in self.key.split("."):
110
+ value = value.get(part) if isinstance(value, dict) else None
111
+ return value
112
+
113
+
114
+ class Process(Resource):
115
+ """A process manager: a resource whose records are running instances.
116
+
117
+ Attributes:
118
+ correlation: Field holding the key that ties events to an instance
119
+ (``invoice_id``); one instance per key. It must be in the create
120
+ and read schemas; ``step.start()`` sets it.
121
+ reacts: ``On`` declarations: the events that move the process.
122
+
123
+ By default only code creates instances and runs transitions
124
+ (``internal = Internal(operations=["create"], transitions=True)``): the
125
+ process moves itself. Its records are readable through the API like any
126
+ resource (``list``, ``get``, ``history``), with the usual permissions.
127
+ """
128
+
129
+ correlation: ClassVar[str]
130
+ reacts: ClassVar[Sequence[On]] = ()
131
+ internal: ClassVar[Internal | Sequence[str]] = Internal(
132
+ operations=("create",), transitions=True
133
+ )
134
+
135
+
136
+ class ProcessStep:
137
+ """What a handler gets: the event, the instance and the means to act.
138
+
139
+ Attributes:
140
+ envelope / payload: The event (``payload`` parsed when ``On.payload`` is set).
141
+ key: The correlation key.
142
+ instance: The process record (read model), or ``None`` before it starts.
143
+ manager / actor: Run other operations as the process
144
+ (``await step.manager.transition("invoices", id, "pay", actor=step.actor)``).
145
+ """
146
+
147
+ def __init__(
148
+ self,
149
+ runner: ProcessRunner,
150
+ definition: ResourceDefinition,
151
+ envelope: EventEnvelope,
152
+ payload: Any,
153
+ key: Any,
154
+ instance: Any,
155
+ ) -> None:
156
+ self.runner = runner
157
+ self.definition = definition
158
+ self.envelope = envelope
159
+ self.payload = payload
160
+ self.key = key
161
+ self.instance = instance
162
+
163
+ @property
164
+ def manager(self) -> ResourceManager:
165
+ """The resource manager, to act on records."""
166
+ return self.runner.manager
167
+
168
+ @property
169
+ def actor(self) -> Any:
170
+ """Who the process acts as."""
171
+ return self.runner.actor
172
+
173
+ @property
174
+ def correlation_id(self) -> str | None:
175
+ """The event's correlation id, passed on to what the step does."""
176
+ return self.envelope.correlation_id
177
+
178
+ async def start(self, data: Any = None, *, tenant: str | None = None) -> Any:
179
+ """Create the instance for this key (once: an existing one is returned)."""
180
+ if self.instance is not None:
181
+ return self.instance
182
+ values = dict(data or {})
183
+ values[_process(self.definition).correlation] = self.key
184
+ self.instance = await self.manager.create(
185
+ self.definition.name, values, actor=self.actor, tenant=tenant
186
+ )
187
+ return self.instance
188
+
189
+ async def transition(self, event: str, data: Any = None) -> Any:
190
+ """Move the instance (its own state machine)."""
191
+ if self.instance is None:
192
+ raise ConfigurationError(
193
+ f"{self.definition.name}: transition {event!r} before the process started",
194
+ hint="Start it first (On(..., start=True) and step.start()).",
195
+ doc=DOC,
196
+ )
197
+ instance_id = getattr(self.instance, self.definition.id_field)
198
+ self.instance = await self.manager.transition(
199
+ self.definition.name, instance_id, event, data, actor=self.actor
200
+ )
201
+ return self.instance
202
+
203
+ def can(self, event: str) -> bool:
204
+ """Whether the instance's state allows ``event`` now."""
205
+ if self.instance is None or self.definition.machine is None:
206
+ return False
207
+ state = getattr(self.instance, self.definition.state_field or "", None)
208
+ info = self.definition.machine.info
209
+ value_of = {s.id: s.value if s.value is not None else s.id for s in info.states}
210
+ return any(t.event == event and value_of[t.source] == state for t in info.transitions)
211
+
212
+
213
+ class ProcessRunner:
214
+ """Dispatches events to every ``Process`` registered with ``manager``.
215
+
216
+ Args:
217
+ manager: The application's manager.
218
+ actor: Who processes act as (default ``system_principal("processes")``).
219
+ """
220
+
221
+ def __init__(self, manager: ResourceManager, *, actor: Any = None) -> None:
222
+ from resource_engine.authz import system_principal
223
+
224
+ self.manager = manager
225
+ self.actor = actor if actor is not None else system_principal("processes")
226
+ self.processes = [d for d in manager.registry if issubclass(d.resource_cls, Process)]
227
+ self._payloads: dict[int, TypeAdapter[Any]] = {}
228
+ for d in self.processes:
229
+ self._check(d)
230
+
231
+ def _check(self, d: ResourceDefinition) -> None:
232
+ cls = _process(d)
233
+ correlation = getattr(cls, "correlation", None)
234
+ where = f"process {d.name}"
235
+ if not correlation:
236
+ raise ConfigurationError(f"{where}: declare correlation", doc=DOC)
237
+ create = d.schemas.get("create")
238
+ read = d.schemas.get("read")
239
+ if not d.enabled("create") or create is None or correlation not in create.model_fields:
240
+ raise ConfigurationError(
241
+ f"{where}: create must be enabled with {correlation!r} in its schema",
242
+ hint="step.start() creates the instance with the correlation key.",
243
+ doc=DOC,
244
+ )
245
+ if read is None or correlation not in read.model_fields or not d.enabled("list"):
246
+ raise ConfigurationError(
247
+ f"{where}: list must be enabled with {correlation!r} in the read schema",
248
+ doc=DOC,
249
+ )
250
+ if not cls.reacts:
251
+ raise ConfigurationError(f"{where}: reacts lists no events", doc=DOC)
252
+ for on in cls.reacts:
253
+ if not isinstance(on, On):
254
+ raise ConfigurationError(f"{where}: reacts must hold On(...), not {on!r}")
255
+ if on.payload is not None:
256
+ self._payloads[id(on)] = TypeAdapter(on.payload)
257
+
258
+ def reactions(self) -> list[tuple[ResourceDefinition, On]]:
259
+ """Every reaction of the registered processes, with its process."""
260
+ return [(d, on) for d in self.processes for on in _process(d).reacts]
261
+
262
+ def router(self, name: str = "processes") -> EventRouter:
263
+ """An ``EventRouter`` with one handler per event type; events no process
264
+ listens to are acknowledged."""
265
+ router = EventRouter(
266
+ ignore_unknown=True,
267
+ name=name,
268
+ description="Process managers: " + ", ".join(d.name for d in self.processes),
269
+ )
270
+ by_type: dict[str, list[tuple[ResourceDefinition, On]]] = {}
271
+ for d, on in self.reactions():
272
+ by_type.setdefault(on.event_type, []).append((d, on))
273
+ for event_type, reactions in by_type.items():
274
+ router.register(event_type, self._dispatcher(reactions))
275
+ return router
276
+
277
+ def _dispatcher(
278
+ self, reactions: list[tuple[ResourceDefinition, On]]
279
+ ) -> Callable[[EventEnvelope], Awaitable[None]]:
280
+ async def dispatch(envelope: EventEnvelope) -> None:
281
+ for definition, on in reactions:
282
+ if on.matches(envelope):
283
+ await self._react(definition, on, envelope)
284
+
285
+ return dispatch
286
+
287
+ async def _react(self, definition: ResourceDefinition, on: On, envelope: EventEnvelope) -> None:
288
+ key = on.key_of(envelope)
289
+ if key is None:
290
+ logger.warning(
291
+ "%s: no correlation key at %r in %s", definition.name, on.key, envelope.type
292
+ )
293
+ return
294
+ payload: Any = envelope.payload
295
+ adapter = self._payloads.get(id(on))
296
+ if adapter is not None:
297
+ from pydantic import ValidationError
298
+
299
+ from resource_engine.errors import MessageRejected
300
+
301
+ try:
302
+ payload = adapter.validate_python(dict(envelope.payload))
303
+ except ValidationError as exc:
304
+ raise MessageRejected(
305
+ f"Invalid {envelope.type} payload for process {definition.name}",
306
+ details=exc.errors(include_url=False, include_context=False),
307
+ ) from exc
308
+ instance = await self.instance(definition, key)
309
+ if instance is None and not on.start:
310
+ logger.debug("%s: no instance for %r; %s ignored", definition.name, key, envelope.type)
311
+ return
312
+ step = ProcessStep(self, definition, envelope, payload, key, instance)
313
+ result = on.handler(step)
314
+ if inspect.isawaitable(result):
315
+ await result
316
+
317
+ async def instance(self, definition: ResourceDefinition, key: Any) -> Any:
318
+ """The process record for ``key``, or ``None``."""
319
+ correlation = _process(definition).correlation
320
+ page = await self.manager.list(
321
+ definition.name, ListQuery(limit=1), actor=self.actor, _within={correlation: key}
322
+ )
323
+ return page.items[0] if page.items else None
324
+
325
+
326
+ class ProcessFeed:
327
+ """Feeds the outbox to the processes, for services without a broker of
328
+ their own (a ``JobRunner`` job, like ``OutboxRelay``)::
329
+
330
+ runner.add("processes", ProcessFeed(uow_factory, processor), every=1, single=True)
331
+
332
+ Each run reads a batch of pending outbox records, runs each through
333
+ ``processor`` (``MessageProcessor`` with the processes' router and
334
+ ``manager=``: inbox and effects in one transaction, exactly once), then
335
+ marks them published, or failed (retried on later runs up to
336
+ ``max_attempts``). Records are processed outside the transaction that
337
+ read them, so a process's own writes never compete with the outbox's.
338
+ Permanent failures are logged and settled.
339
+
340
+ With ``then=`` (a ``MessagePublisher``) the batch also goes to a broker, so
341
+ one job empties the outbox for both; use it instead of ``OutboxRelay``.
342
+ """
343
+
344
+ def __init__(
345
+ self,
346
+ uow_factory: Callable[[], Any],
347
+ processor: MessageProcessor,
348
+ *,
349
+ then: Any = None,
350
+ batch_size: int = 100,
351
+ max_attempts: int = 10,
352
+ ) -> None:
353
+ self.uow_factory = uow_factory
354
+ self.processor = processor
355
+ self.then = then
356
+ self.batch_size = batch_size
357
+ self.max_attempts = max_attempts
358
+
359
+ async def run_once(self) -> int:
360
+ """Handle one batch; returns how many records were settled."""
361
+ from resource_engine.messaging.processing import Outcome
362
+
363
+ async with self.uow_factory() as uow:
364
+ records = [
365
+ r
366
+ for r in await uow.outbox().pending(self.batch_size)
367
+ if r.attempts < self.max_attempts
368
+ ]
369
+ if not records:
370
+ return 0
371
+ failed: dict[str, str] = {}
372
+ if self.then is not None:
373
+ try:
374
+ await self.then.publish([r.envelope for r in records])
375
+ except PublishFailed as exc:
376
+ failed.update(dict.fromkeys(exc.failed_ids, exc.message))
377
+ except Exception as exc:
378
+ failed.update(dict.fromkeys((r.envelope.id for r in records), repr(exc)))
379
+ for record in records:
380
+ envelope = record.envelope
381
+ if envelope.id in failed:
382
+ continue
383
+ result = await self.processor.process(
384
+ ReceivedMessage(
385
+ envelope, delivery_count=record.attempts + 1, message_id=envelope.id
386
+ )
387
+ )
388
+ if result.outcome is Outcome.RETRY:
389
+ failed[envelope.id] = result.error or "retry"
390
+ elif result.outcome is Outcome.DEAD_LETTER: # reported by the processor
391
+ logger.debug("Process message %s settled as dead letter", envelope.id)
392
+ settled = [r.envelope.id for r in records if r.envelope.id not in failed]
393
+ async with self.uow_factory() as uow:
394
+ outbox = uow.outbox()
395
+ if settled:
396
+ await outbox.mark_published(settled)
397
+ for envelope_id, error in failed.items():
398
+ await outbox.mark_failed([envelope_id], error)
399
+ await uow.commit()
400
+ return len(settled)
401
+
402
+
403
+ __all__ = ["On", "Process", "ProcessFeed", "ProcessRunner", "ProcessStep"]
404
+
405
+
406
+ def _process(definition: ResourceDefinition) -> type[Process]:
407
+ """The ``Process`` class of a process resource's definition."""
408
+ return typing.cast("type[Process]", definition.resource_cls)
File without changes