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,165 @@
1
+ """Inbound side: route envelopes received from a broker to handlers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ from collections.abc import Callable
7
+ from typing import Any
8
+
9
+ from pydantic import TypeAdapter, ValidationError
10
+
11
+ from resource_engine.domain.events import DomainEvent
12
+ from resource_engine.errors import ConfigurationError, MessageRejected, NoHandler
13
+ from resource_engine.messaging.envelope import EventEnvelope
14
+ from resource_engine.ports.messaging import MessageHandler
15
+
16
+
17
+ class EventRouter:
18
+ """Dispatches envelopes by ``type``.
19
+
20
+ Broker consumers (SQS poller, Service Bus receiver, Pub/Sub subscriber...) call
21
+ ``dispatch`` and acknowledge the message only if it returns without error.
22
+ Handlers typically call ``ResourceManager`` methods (an action, a transition).
23
+
24
+ A handler registered with ``payload=`` (a Pydantic model, dataclass or any
25
+ type Pydantic validates) gets the validated payload as a second argument:
26
+ ``handler(envelope, payload)``. A payload that does not validate raises
27
+ ``MessageRejected`` (RE-E406), so the message is dead-lettered without
28
+ retries. The payload types also describe the consumed events in the
29
+ AsyncAPI document.
30
+
31
+ Args:
32
+ ignore_unknown: Acknowledge types without a handler instead of
33
+ raising ``NoHandler``.
34
+ name: Consumer name used in the AsyncAPI document (its channel).
35
+ description: What this consumer does, for the AsyncAPI document.
36
+ """
37
+
38
+ def __init__(
39
+ self,
40
+ *,
41
+ ignore_unknown: bool = False,
42
+ name: str | None = None,
43
+ description: str | None = None,
44
+ ) -> None:
45
+ self._handlers: dict[str, list[tuple[MessageHandler, bool]]] = {}
46
+ #: Event type → the payload version its handlers are written for.
47
+ self._versions: dict[str, str] = {}
48
+ self._payloads: dict[str, Any] = {}
49
+ self._adapters: dict[str, TypeAdapter[Any]] = {}
50
+ self.ignore_unknown = ignore_unknown
51
+ self.name = name
52
+ self.description = description
53
+
54
+ def register(
55
+ self,
56
+ event_type: str | type[DomainEvent],
57
+ handler: MessageHandler,
58
+ *,
59
+ payload: Any = None,
60
+ schema_version: int | str | None = None,
61
+ ) -> MessageHandler:
62
+ """``schema_version``: the payload version the handler is written for;
63
+ other versions of the type (published side by side) are acknowledged
64
+ without calling it. ``None``: every version."""
65
+ name = event_type if isinstance(event_type, str) else event_type.__name__
66
+ if schema_version is not None:
67
+ known_version = self._versions.get(name)
68
+ if known_version is not None and known_version != str(schema_version):
69
+ raise ConfigurationError(
70
+ f"Event type {name!r} is registered for two schema versions",
71
+ hint="Handle one version of an event per router.",
72
+ doc="docs/versioning.md#events",
73
+ )
74
+ self._versions[name] = str(schema_version)
75
+ if payload is not None:
76
+ known = self._payloads.get(name)
77
+ if known is not None and known is not payload:
78
+ raise ConfigurationError(
79
+ f"Event type {name!r} is registered with two payload types",
80
+ hint="Use one payload model per event type.",
81
+ doc="docs/messaging.md#typed-payloads",
82
+ )
83
+ self._payloads[name] = payload
84
+ self._adapters[name] = TypeAdapter(payload)
85
+ self._handlers.setdefault(name, []).append((handler, payload is not None))
86
+ return handler
87
+
88
+ def include(self, other: EventRouter) -> EventRouter:
89
+ """Add ``other``'s handlers (and payload types) to this router, so one
90
+ consumer or one outbox feed serves both: ``processes.include(mailer.router())``.
91
+ Returns ``self``."""
92
+ for event_type, handlers in other._handlers.items():
93
+ for handler, typed in handlers:
94
+ payload = other._payloads.get(event_type) if typed else None
95
+ self.register(
96
+ event_type,
97
+ handler,
98
+ payload=payload,
99
+ schema_version=other._versions.get(event_type),
100
+ )
101
+ return self
102
+
103
+ def on(
104
+ self,
105
+ event_type: str | type[DomainEvent],
106
+ *,
107
+ payload: Any = None,
108
+ schema_version: int | str | None = None,
109
+ ) -> Callable[[MessageHandler], MessageHandler]:
110
+ """Decorator form of ``register``."""
111
+ return lambda handler: self.register(
112
+ event_type, handler, payload=payload, schema_version=schema_version
113
+ )
114
+
115
+ def schema_version(self, event_type: str) -> str | None:
116
+ """The payload version handled for ``event_type`` (``None``: any)."""
117
+ return self._versions.get(event_type)
118
+
119
+ @property
120
+ def event_types(self) -> list[str]:
121
+ """The event types with a handler."""
122
+ return list(self._handlers)
123
+
124
+ def payload_type(self, event_type: str) -> Any:
125
+ """The payload type registered for ``event_type``, or ``None``."""
126
+ return self._payloads.get(event_type)
127
+
128
+ def handlers(self, event_type: str) -> list[MessageHandler]:
129
+ """The handlers of ``event_type``, in registration order."""
130
+ return [h for h, _ in self._handlers.get(event_type, ())]
131
+
132
+ def parse(self, envelope: EventEnvelope) -> Any:
133
+ """The envelope's payload validated against its registered type."""
134
+ adapter = self._adapters.get(envelope.type)
135
+ if adapter is None:
136
+ return envelope.payload
137
+ try:
138
+ return adapter.validate_python(dict(envelope.payload))
139
+ except ValidationError as exc:
140
+ raise MessageRejected(
141
+ f"Invalid payload for {envelope.type!r}",
142
+ hint="The producer sent a payload that does not match the consumer's "
143
+ "model; fix the producer or the model, then replay the dead letter.",
144
+ details=exc.errors(include_url=False, include_context=False),
145
+ ) from exc
146
+
147
+ async def dispatch(self, envelope: EventEnvelope) -> None:
148
+ """Run the handlers of the envelope's type. Unknown types raise, unless
149
+ ``ignore_unknown``."""
150
+ handlers = self._handlers.get(envelope.type)
151
+ if not handlers:
152
+ if self.ignore_unknown:
153
+ return
154
+ raise NoHandler(
155
+ f"No handler registered for event type {envelope.type!r}",
156
+ hint=f"Registered types: {', '.join(self._handlers) or '(none)'}",
157
+ )
158
+ wanted = self._versions.get(envelope.type)
159
+ if wanted is not None and envelope.schema_version != wanted:
160
+ return # another version of the event, published for other consumers
161
+ payload = self.parse(envelope) if envelope.type in self._adapters else None
162
+ for handler, typed in handlers:
163
+ result = handler(envelope, payload) if typed else handler(envelope) # type: ignore[call-arg]
164
+ if inspect.isawaitable(result):
165
+ await result
@@ -0,0 +1,115 @@
1
+ """How the ResourceManager delivers the events recorded during an operation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from collections.abc import Sequence
7
+ from typing import TYPE_CHECKING, Any, Protocol, override
8
+
9
+ from resource_engine.domain.events import DomainEvent
10
+ from resource_engine.errors import OutboxNotSupported
11
+ from resource_engine.messaging.envelope import EventEnvelope, EventSerializer
12
+ from resource_engine.ports.event_publisher import EventPublisher
13
+ from resource_engine.ports.messaging import MessagePublisher, SupportsOutbox
14
+
15
+ if TYPE_CHECKING:
16
+ from resource_engine.application.context import OperationContext
17
+ from resource_engine.ports.unit_of_work import UnitOfWork
18
+
19
+ logger = logging.getLogger("resource_engine.messaging")
20
+
21
+
22
+ class EventDelivery(Protocol):
23
+ """Strategy called by the manager right before and right after commit."""
24
+
25
+ async def before_commit(self, ctx: OperationContext, uow: UnitOfWork) -> None:
26
+ """Called inside the transaction, right before commit."""
27
+ ...
28
+
29
+ async def after_commit(self, ctx: OperationContext) -> None:
30
+ """Called once the transaction has committed."""
31
+ ...
32
+
33
+
34
+ class AfterCommitDelivery(EventDelivery):
35
+ """Publish in-process after commit. Best effort: lost if the process dies."""
36
+
37
+ def __init__(self, publisher: EventPublisher) -> None:
38
+ self.publisher = publisher
39
+
40
+ @override
41
+ async def before_commit(self, ctx: OperationContext, uow: UnitOfWork) -> None:
42
+ return None
43
+
44
+ @override
45
+ async def after_commit(self, ctx: OperationContext) -> None:
46
+ if ctx.events:
47
+ await self.publisher.publish(list(ctx.events))
48
+
49
+
50
+ class TransportEventPublisher(EventPublisher):
51
+ """``EventPublisher`` that serialises events and sends them to a broker."""
52
+
53
+ def __init__(
54
+ self, transport: MessagePublisher, serializer: EventSerializer | None = None
55
+ ) -> None:
56
+ self.transport = transport
57
+ self.serializer = serializer or EventSerializer()
58
+
59
+ @override
60
+ async def publish(self, events: Sequence[DomainEvent]) -> None:
61
+ await self.transport.publish(
62
+ [envelope for e in events for envelope in self.serializer.to_envelopes(e)]
63
+ )
64
+
65
+
66
+ class OutboxDelivery(EventDelivery):
67
+ """Transactional outbox: events are stored with the business change.
68
+
69
+ Envelopes are written through ``uow.outbox()`` before commit, so they exist if
70
+ and only if the operation committed. An ``OutboxRelay`` sends them later.
71
+
72
+ ``live``: a ``MessagePublisher`` in this process (an ``EventHub``) that also
73
+ gets the same envelopes right after the commit, for live subscribers (the
74
+ explorer, GraphQL subscriptions). Best effort: a failure there is logged
75
+ and changes nothing; the outbox stays the source of delivery.
76
+ """
77
+
78
+ def __init__(self, serializer: EventSerializer | None = None, *, live: Any = None) -> None:
79
+ self.serializer = serializer or EventSerializer()
80
+ self.live = live
81
+
82
+ def envelopes(self, ctx: OperationContext) -> list[EventEnvelope]:
83
+ """The envelopes of the operation's events."""
84
+ return [
85
+ envelope
86
+ for e in ctx.events
87
+ for envelope in self.serializer.to_envelopes(
88
+ e, correlation_id=ctx.correlation_id, resource=ctx.resource.name
89
+ )
90
+ ]
91
+
92
+ @override
93
+ async def before_commit(self, ctx: OperationContext, uow: UnitOfWork) -> None:
94
+ if not ctx.events:
95
+ return
96
+ if not isinstance(uow, SupportsOutbox):
97
+ raise OutboxNotSupported(
98
+ f"{type(uow).__name__} has no outbox()",
99
+ hint="Use a unit of work with an outbox (SqlAlchemyUnitOfWork with "
100
+ "outbox_table, InMemoryUnitOfWork) or AfterCommitDelivery.",
101
+ doc="docs/messaging.md#outbox",
102
+ )
103
+ envelopes = self.envelopes(ctx)
104
+ ctx.extras["outbox_envelopes"] = envelopes
105
+ await uow.outbox().add(envelopes)
106
+
107
+ @override
108
+ async def after_commit(self, ctx: OperationContext) -> None:
109
+ envelopes = ctx.extras.get("outbox_envelopes")
110
+ if self.live is None or not envelopes:
111
+ return
112
+ try:
113
+ await self.live.publish(envelopes)
114
+ except Exception:
115
+ logger.exception("Live subscribers did not get the committed events")
@@ -0,0 +1,193 @@
1
+ """Transport-neutral representation of a domain event."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ import enum
7
+ import json
8
+ import uuid
9
+ from collections.abc import Mapping
10
+ from dataclasses import dataclass, field
11
+ from datetime import date, datetime, time
12
+ from decimal import Decimal
13
+ from typing import Any
14
+
15
+ from resource_engine.domain.events import DomainEvent
16
+ from resource_engine.tracing import get_tracer
17
+
18
+ #: The payload version of events that declare none (``DomainEvent.schema_version``).
19
+ SCHEMA_VERSION = "1"
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class EventEnvelope:
24
+ """A serialised event ready to travel through a broker.
25
+
26
+ Attributes:
27
+ id: Unique message id; transports use it for de-duplication.
28
+ type: Event type name (the event class name by default).
29
+ occurred_at: When the event happened (UTC, ISO-8601 on the wire).
30
+ payload: JSON-compatible event fields.
31
+ correlation_id: Id of the operation that produced the event.
32
+ resource: Resource name, when the event comes from a resource operation.
33
+ key: Ordering/partition key (FIFO group, session, ordering key).
34
+ trace: W3C trace context of the operation that produced the event
35
+ (``traceparent``, ``tracestate``), so consumers continue its trace.
36
+ schema_version: Version of the payload's shape for this event type
37
+ (``"1"`` unless the event declares one; older versions published
38
+ side by side carry theirs, see ``resource_engine.versions``).
39
+ tags: Extra string attributes (``origin=console`` on events published
40
+ by hand from the explorer), sent as broker attributes and as
41
+ CloudEvents extensions. Names are lowercase letters and digits.
42
+ """
43
+
44
+ type: str
45
+ payload: Mapping[str, Any]
46
+ occurred_at: datetime
47
+ id: str = field(default_factory=lambda: uuid.uuid4().hex)
48
+ correlation_id: str | None = None
49
+ resource: str | None = None
50
+ key: str | None = None
51
+ trace: Mapping[str, str] | None = None
52
+ schema_version: str = SCHEMA_VERSION
53
+ tags: Mapping[str, str] | None = None
54
+
55
+ def attributes(self) -> dict[str, str]:
56
+ """String attributes for broker-level routing and filtering."""
57
+ attrs = {
58
+ "event_type": self.type,
59
+ "event_id": self.id,
60
+ "schema_version": self.schema_version,
61
+ }
62
+ if self.resource:
63
+ attrs["resource"] = self.resource
64
+ if self.correlation_id:
65
+ attrs["correlation_id"] = self.correlation_id
66
+ attrs.update(self.trace or {})
67
+ for name, value in (self.tags or {}).items():
68
+ attrs.setdefault(name, value)
69
+ return attrs
70
+
71
+ def to_dict(self) -> dict[str, Any]:
72
+ """The envelope as JSON-ready data."""
73
+ data: dict[str, Any] = {
74
+ "id": self.id,
75
+ "type": self.type,
76
+ "occurred_at": self.occurred_at.isoformat(),
77
+ "correlation_id": self.correlation_id,
78
+ "resource": self.resource,
79
+ "key": self.key,
80
+ "schema_version": self.schema_version,
81
+ "payload": dict(self.payload),
82
+ }
83
+ if self.trace:
84
+ data["trace"] = dict(self.trace)
85
+ if self.tags:
86
+ data["tags"] = dict(self.tags)
87
+ return data
88
+
89
+ def to_json(self) -> str:
90
+ """The envelope as compact JSON."""
91
+ return json.dumps(self.to_dict(), ensure_ascii=False, separators=(",", ":"))
92
+
93
+ @classmethod
94
+ def from_dict(cls, data: Mapping[str, Any]) -> EventEnvelope:
95
+ """The envelope ``to_dict`` produced."""
96
+ return cls(
97
+ id=data["id"],
98
+ type=data["type"],
99
+ occurred_at=datetime.fromisoformat(data["occurred_at"]),
100
+ correlation_id=data.get("correlation_id"),
101
+ resource=data.get("resource"),
102
+ key=data.get("key"),
103
+ payload=data.get("payload") or {},
104
+ trace=data.get("trace") or None,
105
+ schema_version=str(data.get("schema_version") or SCHEMA_VERSION),
106
+ tags=dict(data["tags"]) if data.get("tags") else None,
107
+ )
108
+
109
+ @classmethod
110
+ def from_json(cls, raw: str | bytes) -> EventEnvelope:
111
+ """The envelope ``to_json`` produced."""
112
+ return cls.from_dict(json.loads(raw))
113
+
114
+
115
+ def to_jsonable(value: Any) -> Any:
116
+ """Convert common Python values into JSON-compatible ones (lossless as strings)."""
117
+ if value is None or isinstance(value, bool | int | float | str):
118
+ return value
119
+ if isinstance(value, Decimal):
120
+ return str(value)
121
+ if isinstance(value, datetime | date | time):
122
+ return value.isoformat()
123
+ if isinstance(value, uuid.UUID):
124
+ return str(value)
125
+ if isinstance(value, enum.Enum):
126
+ return to_jsonable(value.value)
127
+ if dataclasses.is_dataclass(value) and not isinstance(value, type):
128
+ return {f.name: to_jsonable(getattr(value, f.name)) for f in dataclasses.fields(value)}
129
+ if isinstance(value, Mapping):
130
+ return {str(k): to_jsonable(v) for k, v in value.items()}
131
+ if isinstance(value, list | tuple | set | frozenset):
132
+ return [to_jsonable(v) for v in value]
133
+ if hasattr(value, "model_dump"):
134
+ return to_jsonable(value.model_dump(mode="json"))
135
+ raise TypeError(f"Cannot serialise {type(value).__name__} in an event payload")
136
+
137
+
138
+ class EventSerializer:
139
+ """Turns domain events into envelopes.
140
+
141
+ The ordering key defaults to ``"<resource>:<entity_id>"`` for resource events,
142
+ so all messages about one entity keep their order on FIFO transports.
143
+ """
144
+
145
+ def to_envelopes(
146
+ self,
147
+ event: DomainEvent,
148
+ *,
149
+ correlation_id: str | None = None,
150
+ resource: str | None = None,
151
+ ) -> list[EventEnvelope]:
152
+ """The event's envelope, then one per older version it still
153
+ publishes (``previous_versions``), each with its own id
154
+ (``<id>.v<n>``), ``schema_version`` and converted payload."""
155
+ current = self.to_envelope(event, correlation_id=correlation_id, resource=resource)
156
+ envelopes = [current]
157
+ for number, version in sorted(getattr(event, "previous_versions", {}).items()):
158
+ envelopes.append(
159
+ dataclasses.replace(
160
+ current,
161
+ id=f"{current.id}.v{number}",
162
+ payload=to_jsonable(version.convert(dict(current.payload))),
163
+ schema_version=str(number),
164
+ )
165
+ )
166
+ return envelopes
167
+
168
+ def to_envelope(
169
+ self,
170
+ event: DomainEvent,
171
+ *,
172
+ correlation_id: str | None = None,
173
+ resource: str | None = None,
174
+ ) -> EventEnvelope:
175
+ """The envelope of ``event`` in its current version."""
176
+ payload = {
177
+ f.name: to_jsonable(getattr(event, f.name))
178
+ for f in dataclasses.fields(event)
179
+ if f.name != "occurred_at"
180
+ }
181
+ resource = payload.get("resource", resource)
182
+ entity_id = payload.get("entity_id")
183
+ key = f"{resource}:{entity_id}" if resource and entity_id is not None else resource
184
+ return EventEnvelope(
185
+ type=event.name,
186
+ payload=payload,
187
+ occurred_at=event.occurred_at,
188
+ correlation_id=correlation_id,
189
+ resource=resource,
190
+ key=key,
191
+ trace=get_tracer().inject() or None,
192
+ schema_version=str(getattr(event, "schema_version", SCHEMA_VERSION)),
193
+ )
@@ -0,0 +1,148 @@
1
+ """An in-process event hub: committed events fanned out to live subscribers
2
+ (GraphQL subscriptions, server-sent events, WebSockets).
3
+
4
+ Feed it like any broker (it is a ``MessagePublisher``):
5
+
6
+ - **directly after commit:** ``ResourceManager(event_publisher=TransportEventPublisher(hub))``;
7
+ - **from the outbox:** ``OutboxRelay(uow_factory, FanoutPublisher(broker, hub))``,
8
+ or ``ProcessFeed(..., then=hub)``;
9
+ - **with several instances:** each instance consumes a broadcast topic with
10
+ ``MessageConsumer(source, MessageProcessor(hub.router(), name=...))``, so
11
+ every instance's subscribers see every event.
12
+
13
+ Subscribers get envelopes as an async iterator. A slow subscriber's queue is
14
+ bounded: when it is full the oldest event is dropped and the subscriber is told
15
+ (``overflowed``), so one stuck client never holds the others back.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import asyncio
21
+ import logging
22
+ from collections.abc import AsyncIterator, Callable, Sequence
23
+ from typing import Any, override
24
+
25
+ from resource_engine.errors import PublishFailed
26
+ from resource_engine.messaging.consumer import EventRouter
27
+ from resource_engine.messaging.envelope import EventEnvelope
28
+ from resource_engine.ports.messaging import MessagePublisher
29
+
30
+ logger = logging.getLogger("resource_engine.hub")
31
+
32
+ type EventFilter = Callable[[EventEnvelope], bool]
33
+
34
+
35
+ class Subscription:
36
+ """One subscriber's queue of envelopes (``async for envelope in sub``)."""
37
+
38
+ def __init__(self, hub: EventHub, matches: EventFilter | None, size: int) -> None:
39
+ self.hub = hub
40
+ self.matches = matches
41
+ self.queue: asyncio.Queue[EventEnvelope | None] = asyncio.Queue(maxsize=size)
42
+ self.overflowed = 0
43
+ self.closed = False
44
+
45
+ def offer(self, envelope: EventEnvelope) -> None:
46
+ """Queue ``envelope`` if it matches; a full queue drops the oldest one."""
47
+ if self.closed or (self.matches is not None and not self.matches(envelope)):
48
+ return
49
+ if self.queue.full():
50
+ self.queue.get_nowait() # drop the oldest
51
+ self.overflowed += 1
52
+ self.queue.put_nowait(envelope)
53
+
54
+ def close(self) -> None:
55
+ """Stop receiving and end the iteration."""
56
+ if not self.closed:
57
+ self.closed = True
58
+ self.hub._subscriptions.discard(self)
59
+ if self.queue.full():
60
+ self.queue.get_nowait()
61
+ self.queue.put_nowait(None)
62
+
63
+ def __aiter__(self) -> AsyncIterator[EventEnvelope]:
64
+ return self._iterate()
65
+
66
+ async def _iterate(self) -> AsyncIterator[EventEnvelope]:
67
+ try:
68
+ while True:
69
+ envelope = await self.queue.get()
70
+ if envelope is None:
71
+ return
72
+ yield envelope
73
+ finally:
74
+ self.close()
75
+
76
+
77
+ class EventHub(MessagePublisher):
78
+ """Fans envelopes out to in-process subscribers.
79
+
80
+ Args:
81
+ queue_size: Events kept per subscriber before the oldest are dropped.
82
+ """
83
+
84
+ def __init__(self, *, queue_size: int = 100) -> None:
85
+ self.queue_size = queue_size
86
+ self._subscriptions: set[Subscription] = set()
87
+
88
+ @property
89
+ def subscribers(self) -> int:
90
+ """How many subscriptions are open."""
91
+ return len(self._subscriptions)
92
+
93
+ def subscribe(self, matches: EventFilter | None = None) -> Subscription:
94
+ """A new subscription to the envelopes ``matches`` accepts (all by default)."""
95
+ subscription = Subscription(self, matches, self.queue_size)
96
+ self._subscriptions.add(subscription)
97
+ return subscription
98
+
99
+ @override
100
+ async def publish(self, messages: Sequence[EventEnvelope]) -> None:
101
+ for envelope in messages:
102
+ for subscription in list(self._subscriptions):
103
+ try:
104
+ subscription.offer(envelope)
105
+ except Exception: # a broken filter must not stop the others
106
+ logger.exception("Hub subscriber filter failed")
107
+
108
+ def router(self, name: str = "hub") -> EventRouter:
109
+ """An ``EventRouter`` that hands every event to the hub (for consumers)."""
110
+ hub = self
111
+
112
+ class _Everything(EventRouter):
113
+ async def dispatch(self, envelope: EventEnvelope) -> None:
114
+ await hub.publish([envelope])
115
+
116
+ return _Everything(name=name, description="Live subscribers (GraphQL, SSE)")
117
+
118
+ def close(self) -> None:
119
+ """Close every subscription."""
120
+ for subscription in list(self._subscriptions):
121
+ subscription.close()
122
+
123
+
124
+ class FanoutPublisher(MessagePublisher):
125
+ """Publishes to several publishers (a broker and the hub). A failure in one
126
+ is reported with the ids it rejected; the others still get the messages."""
127
+
128
+ def __init__(self, *publishers: Any) -> None:
129
+ self.publishers = publishers
130
+
131
+ @override
132
+ async def publish(self, messages: Sequence[EventEnvelope]) -> None:
133
+ failed: list[str] = []
134
+ errors: list[str] = []
135
+ for publisher in self.publishers:
136
+ try:
137
+ await publisher.publish(messages)
138
+ except PublishFailed as exc:
139
+ failed += [i for i in exc.failed_ids if i not in failed]
140
+ errors.append(exc.message)
141
+ except Exception as exc:
142
+ failed += [m.id for m in messages if m.id not in failed]
143
+ errors.append(f"{type(exc).__name__}: {exc}")
144
+ if failed:
145
+ raise PublishFailed("; ".join(errors), failed_ids=failed)
146
+
147
+
148
+ __all__ = ["EventHub", "FanoutPublisher", "Subscription"]