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,36 @@
1
+ """An ``EmailSender`` that keeps the messages, for tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import override
7
+
8
+ from resource_engine.errors import EmailRejected, RemoteCallFailed
9
+ from resource_engine.ports.email import EmailMessage, EmailSender
10
+
11
+
12
+ @dataclass
13
+ class RecordingEmailSender(EmailSender):
14
+ """Keeps every message in ``sent``. ``reject`` lists addresses refused for
15
+ good (RE-E502); ``failures`` makes the next sends fail as unreachable (RE-E501)."""
16
+
17
+ sent: list[EmailMessage] = field(default_factory=list)
18
+ reject: set[str] = field(default_factory=set)
19
+ failures: int = 0
20
+
21
+ @override
22
+ async def send(self, message: EmailMessage) -> str | None:
23
+ if self.failures > 0:
24
+ self.failures -= 1
25
+ raise RemoteCallFailed("mail service down", service="email", operation="send")
26
+ refused = [r for r in message.recipients if r in self.reject]
27
+ if refused:
28
+ raise EmailRejected(
29
+ "Recipient refused", details={"recipients": refused, "reason": "test"}
30
+ )
31
+ self.sent.append(message)
32
+ return f"recorded-{len(self.sent)}"
33
+
34
+ def to(self, address: str) -> list[EmailMessage]:
35
+ """Messages that went to ``address``."""
36
+ return [m for m in self.sent if address in m.recipients]
@@ -0,0 +1,40 @@
1
+ """``ConditionEngine``: an in-memory ``PolicyEngine`` for tests and prototypes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from typing import Any, override
7
+
8
+ from resource_engine.authz.catalog import action_matches
9
+ from resource_engine.authz.conditions import Env, disjunction, partial
10
+ from resource_engine.ports.authz import AuthzRequest, PolicyEngine
11
+
12
+
13
+ class ConditionEngine(PolicyEngine):
14
+ """Rules as ``{action pattern: condition}`` in the engine-neutral condition
15
+ language (``True`` allows unconditionally). Deny by default; several
16
+ matching rules are OR-ed. Records the requests it answers in ``requests``.
17
+ """
18
+
19
+ def __init__(self, rules: Mapping[str, Any]) -> None:
20
+ self.rules = dict(rules)
21
+ self.requests: list[AuthzRequest] = []
22
+
23
+ @override
24
+ async def evaluate(self, request: AuthzRequest) -> Any:
25
+ self.requests.append(request)
26
+ if request.subject is None:
27
+ return False
28
+ namespaces: dict[str, Any] = {"subject": request.subject, "context": request.context}
29
+ if request.resource is not ...:
30
+ namespaces["resource"] = request.resource
31
+ if request.input is not ...:
32
+ namespaces["input"] = request.input
33
+ env = Env(**namespaces)
34
+ return disjunction(
35
+ *(
36
+ partial(None if condition is True else condition, env)
37
+ for pattern, condition in self.rules.items()
38
+ if action_matches(pattern, request.action)
39
+ )
40
+ )
@@ -0,0 +1,603 @@
1
+ """In-memory adapters for tests: store, repositories, outbox, inbox, idempotency and units of
2
+ work."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import asyncio
7
+ import copy
8
+ import itertools
9
+ import time
10
+ from collections.abc import Sequence
11
+ from dataclasses import dataclass, field
12
+ from datetime import UTC, datetime
13
+ from types import TracebackType
14
+ from typing import TYPE_CHECKING, Any, Self, override
15
+
16
+ from resource_engine.application.query import ListQuery, Page
17
+ from resource_engine.domain.events import DomainEvent
18
+ from resource_engine.messaging.envelope import EventEnvelope
19
+ from resource_engine.ports.event_publisher import EventPublisher
20
+ from resource_engine.ports.idempotency import IdempotencyStore, SupportsIdempotency
21
+ from resource_engine.ports.locks import LockProvider
22
+ from resource_engine.ports.messaging import (
23
+ InboxStore,
24
+ InspectableOutbox,
25
+ MessagePublisher,
26
+ MessageSource,
27
+ OutboxRecord,
28
+ OutboxStore,
29
+ ReceivedMessage,
30
+ SupportsDeadLetter,
31
+ SupportsInbox,
32
+ SupportsOutbox,
33
+ )
34
+ from resource_engine.ports.repository import Repository
35
+ from resource_engine.ports.unit_of_work import UnitOfWork
36
+
37
+ OUTBOX_TABLE = "__outbox__"
38
+ INBOX_TABLE = "__inbox__"
39
+ IDEMPOTENCY_TABLE = "__idempotency__"
40
+
41
+ if TYPE_CHECKING:
42
+ from resource_engine.application.registry import ResourceRegistry
43
+
44
+
45
+ class InMemoryStore:
46
+ """Process-local storage shared by the units of work created from it.
47
+
48
+ Each unit of work works on a deep copy and swaps it in on commit, so rollback
49
+ is simply discarding the copy. Not meant for concurrent production use.
50
+ """
51
+
52
+ def __init__(
53
+ self,
54
+ id_fields: dict[str, str] | None = None,
55
+ version_fields: dict[str, str] | None = None,
56
+ families: dict[str, tuple[str, str, str]] | None = None,
57
+ views: dict[str, tuple[Any, Any]] | None = None,
58
+ ) -> None:
59
+ self.id_fields: dict[str, str] = dict(id_fields or {})
60
+ self.version_fields: dict[str, str] = dict(version_fields or {})
61
+ #: subtype -> (base, discriminator, identity): subtypes live in the base's table
62
+ self.families: dict[str, tuple[str, str, str]] = dict(families or {})
63
+ #: view -> (Aggregate or rows function, model)
64
+ self.views: dict[str, tuple[Any, Any]] = dict(views or {})
65
+ self.tables: dict[str, dict[Any, Any]] = {
66
+ name: {} for name in self.id_fields if name not in self.families | self.views
67
+ }
68
+ self._counters: dict[str, itertools.count[int]] = {}
69
+
70
+ @classmethod
71
+ def from_registry(
72
+ cls, registry: ResourceRegistry, *, views: dict[str, Any] | None = None
73
+ ) -> InMemoryStore:
74
+ """A store for every registered resource. ``views`` computes custom
75
+ views (``view = True``): ``{"name": lambda read: rows}``, where
76
+ ``read("invoices")`` returns that resource's records and each row is a
77
+ dict or an entity. Aggregate views need nothing."""
78
+ custom = dict(views or {})
79
+ declared: dict[str, tuple[Any, Any]] = {}
80
+ for d in registry:
81
+ if d.view is None:
82
+ continue
83
+ if d.view is True and d.name not in custom:
84
+ raise ValueError(
85
+ f"{d.name} is a custom view: pass views={{{d.name!r}: lambda read: [...]}}"
86
+ )
87
+ declared[d.name] = (custom.get(d.name, d.view), d.model)
88
+ return cls(
89
+ {d.name: d.id_field for d in registry},
90
+ {d.name: d.version_field for d in registry if d.version_field},
91
+ {
92
+ d.name: (d.parent.name, d.parent.discriminator or "", d.identity or d.name)
93
+ for d in registry
94
+ if d.parent is not None
95
+ },
96
+ declared,
97
+ )
98
+
99
+ def next_id(self, resource: str) -> int:
100
+ """The next id of ``resource``: 1, 2, 3..."""
101
+ counter = self._counters.setdefault(resource, itertools.count(1))
102
+ return next(counter)
103
+
104
+ def unit_of_work(self) -> InMemoryUnitOfWork:
105
+ """Use as ``uow_factory=store.unit_of_work``."""
106
+ return InMemoryUnitOfWork(self)
107
+
108
+ def outbox_records(self, *, published: bool | None = None) -> list[dict[str, Any]]:
109
+ """Copies of the outbox rows (only sent or unsent ones, with ``published``)."""
110
+ rows = self.tables.get(OUTBOX_TABLE, {}).values()
111
+ return [copy.deepcopy(r) for r in rows if published is None or r["published"] == published]
112
+
113
+ def all(self, resource: str) -> list[Any]:
114
+ """Every committed record of ``resource``."""
115
+ family = self.families.get(resource)
116
+ rows = self.tables.get(family[0] if family else resource, {}).values()
117
+ return [copy.deepcopy(e) for e in rows if _of_kind(e, family)]
118
+
119
+
120
+ def _of_kind(entity: Any, family: tuple[str, str, str] | None) -> bool:
121
+ return family is None or getattr(entity, family[1], None) == family[2]
122
+
123
+
124
+ def _now() -> datetime:
125
+ return datetime.now(UTC)
126
+
127
+
128
+ class InMemoryRepository[E](Repository[E]):
129
+ """A repository over a table of the in-memory store, with row conditions and versions."""
130
+
131
+ supports_conditions = True
132
+ supports_versions = True
133
+
134
+ def __init__(
135
+ self,
136
+ store: InMemoryStore,
137
+ table: dict[Any, E],
138
+ resource: str,
139
+ checks: list[tuple[str, Any, int]] | None = None,
140
+ ) -> None:
141
+ self._store = store
142
+ self._table = table
143
+ self._resource = resource
144
+ self._id_field = store.id_fields.get(resource, "id")
145
+ self._version_field = store.version_fields.get(resource, "version")
146
+ self._checks = checks if checks is not None else []
147
+ self._family = store.families.get(resource)
148
+ if self._family is not None: # a subtype: ids, versions and rows are the base's
149
+ self._resource = self._family[0]
150
+
151
+ def _compare(self, entity_id: Any, expected: int) -> None:
152
+ """Against the committed store; re-checked by the unit of work on commit."""
153
+ _check_committed(self._store, self._resource, entity_id, expected, self._version_field)
154
+ self._checks.append((self._resource, entity_id, expected))
155
+
156
+ @override
157
+ async def get(self, entity_id: Any) -> E | None:
158
+ entity = self._table.get(entity_id)
159
+ return entity if entity is not None and _of_kind(entity, self._family) else None
160
+
161
+ @override
162
+ async def list(self, query: ListQuery) -> Page[E]:
163
+ from resource_engine.authz.conditions import matches
164
+ from resource_engine.translatable import localise
165
+
166
+ def value(entity: Any, name: str) -> Any:
167
+ found = getattr(entity, name, None)
168
+ return localise(found, query.locales) if name in query.translatable else found
169
+
170
+ items = [
171
+ e
172
+ for e in self._table.values()
173
+ if _of_kind(e, self._family)
174
+ and all(value(e, k) == v for k, v in query.filters.items())
175
+ and matches(query.condition, e)
176
+ ]
177
+ for key in reversed(list(query.order_by)):
178
+ desc = key.startswith("-")
179
+ name = key.lstrip("-")
180
+ items.sort(key=lambda e: (value(e, name) is None, value(e, name)), reverse=desc)
181
+ total = len(items)
182
+ return Page(
183
+ items[query.offset : query.offset + query.limit], total, query.offset, query.limit
184
+ )
185
+
186
+ @override
187
+ async def add(self, entity: E) -> E:
188
+ if getattr(entity, self._id_field, None) is None:
189
+ setattr(entity, self._id_field, self._store.next_id(self._resource))
190
+ self._table[getattr(entity, self._id_field)] = entity
191
+ return entity
192
+
193
+ @override
194
+ async def update(self, entity: E, *, expected_version: int | None = None) -> E:
195
+ entity_id = getattr(entity, self._id_field)
196
+ if expected_version is not None:
197
+ self._compare(entity_id, expected_version)
198
+ setattr(entity, self._version_field, expected_version + 1)
199
+ self._table[entity_id] = entity
200
+ return entity
201
+
202
+ @override
203
+ async def delete(self, entity: E, *, expected_version: int | None = None) -> None:
204
+ entity_id = getattr(entity, self._id_field)
205
+ if expected_version is not None:
206
+ self._compare(entity_id, expected_version)
207
+ self._table.pop(entity_id, None)
208
+
209
+
210
+ def _check_committed(
211
+ store: InMemoryStore, resource: str, entity_id: Any, expected: int, version_field: str
212
+ ) -> None:
213
+ stored = store.tables.get(resource, {}).get(entity_id)
214
+ current = getattr(stored, version_field, None) if stored is not None else None
215
+ if current != expected:
216
+ from resource_engine.errors import VersionConflict
217
+
218
+ raise VersionConflict(
219
+ f"{resource} {entity_id!r} changed: version {current}, expected {expected}",
220
+ hint="Reload the record and apply your change again.",
221
+ details={
222
+ "resource": resource,
223
+ "id": entity_id,
224
+ "expected": expected,
225
+ "current": current,
226
+ "reason": "version conflict",
227
+ },
228
+ )
229
+
230
+
231
+ class InMemoryOutbox(OutboxStore, InspectableOutbox):
232
+ """The in-memory store's outbox."""
233
+
234
+ def __init__(self, table: dict[str, dict[str, Any]]) -> None:
235
+ self._table = table
236
+
237
+ @override
238
+ async def add(self, envelopes: Sequence[EventEnvelope]) -> None:
239
+ for env in envelopes:
240
+ self._table[env.id] = {
241
+ "envelope": env,
242
+ "attempts": 0,
243
+ "last_error": None,
244
+ "published": False,
245
+ "published_at": None,
246
+ }
247
+
248
+ @override
249
+ async def pending(self, limit: int) -> list[OutboxRecord]:
250
+ rows = [r for r in self._table.values() if not r["published"]][:limit]
251
+ return [OutboxRecord(r["envelope"], r["attempts"], r["last_error"]) for r in rows]
252
+
253
+ def _record(self, row: dict[str, Any]) -> OutboxRecord:
254
+ return OutboxRecord(
255
+ row["envelope"],
256
+ row["attempts"],
257
+ row["last_error"],
258
+ published=row["published"],
259
+ published_at=row["published_at"],
260
+ )
261
+
262
+ @override
263
+ async def unpublished(self, limit: int) -> list[OutboxRecord]:
264
+ return [self._record(r) for r in self._table.values() if not r["published"]][:limit]
265
+
266
+ @override
267
+ async def get(self, message_id: str) -> OutboxRecord | None:
268
+ row = self._table.get(message_id)
269
+ return self._record(row) if row is not None else None
270
+
271
+ @override
272
+ async def requeue(self, ids: Sequence[str]) -> int:
273
+ found = 0
274
+ for i in ids:
275
+ row = self._table.get(i)
276
+ if row is not None:
277
+ row.update(published=False, published_at=None, attempts=0, last_error=None)
278
+ found += 1
279
+ return found
280
+
281
+ @override
282
+ async def mark_published(self, ids: Sequence[str]) -> None:
283
+ now = datetime.now(UTC)
284
+ for i in ids:
285
+ self._table[i]["published"] = True
286
+ self._table[i]["published_at"] = now
287
+
288
+ @override
289
+ async def mark_failed(self, ids: Sequence[str], error: str) -> None:
290
+ for i in ids:
291
+ self._table[i]["attempts"] += 1
292
+ self._table[i]["last_error"] = error
293
+
294
+ @override
295
+ async def purge_published(self, before: datetime, limit: int) -> int:
296
+ old = [
297
+ i
298
+ for i, r in self._table.items()
299
+ if r["published"] and r["published_at"] is not None and r["published_at"] < before
300
+ ][:limit]
301
+ for i in old:
302
+ del self._table[i]
303
+ return len(old)
304
+
305
+
306
+ class InMemoryInbox(InboxStore):
307
+ """The in-memory store's inbox of processed message ids."""
308
+
309
+ def __init__(self, table: dict[tuple[str, str], datetime]) -> None:
310
+ self._table = table
311
+
312
+ @override
313
+ async def processed(self, consumer: str, message_ids: Sequence[str]) -> set[str]:
314
+ return {i for i in message_ids if (consumer, i) in self._table}
315
+
316
+ @override
317
+ async def mark_processed(self, consumer: str, message_ids: Sequence[str]) -> None:
318
+ now = datetime.now(UTC)
319
+ for i in message_ids:
320
+ self._table.setdefault((consumer, i), now)
321
+
322
+ @override
323
+ async def purge(self, before: datetime, limit: int) -> int:
324
+ old = [key for key, at in self._table.items() if at < before][:limit]
325
+ for key in old:
326
+ del self._table[key]
327
+ return len(old)
328
+
329
+
330
+ class IdempotencyConflict(RuntimeError):
331
+ """Another unit of work committed the same idempotency key first (what a
332
+ primary key violation is in SQL)."""
333
+
334
+
335
+ class InMemoryIdempotency(IdempotencyStore):
336
+ """The in-memory store's idempotency records."""
337
+
338
+ def __init__(self, table: dict[tuple[str, str], Any], new: set[tuple[str, str]]) -> None:
339
+ self._table = table
340
+ self._new = new
341
+
342
+ @override
343
+ async def get(self, scope: str, key: str) -> Any:
344
+ record = self._table.get((scope, key))
345
+ return copy.deepcopy(record) if record is not None else None
346
+
347
+ @override
348
+ async def put(self, record: Any) -> None:
349
+ self._table[(record.scope, record.key)] = copy.deepcopy(record)
350
+ self._new.add((record.scope, record.key))
351
+
352
+ @override
353
+ async def purge(self, before: datetime, limit: int) -> int:
354
+ old = [k for k, r in self._table.items() if r.expires_at and r.expires_at < before][:limit]
355
+ for k in old:
356
+ del self._table[k]
357
+ return len(old)
358
+
359
+
360
+ class InMemoryViewRepository:
361
+ """A view's rows, computed from the unit of work's tables on each read."""
362
+
363
+ supports_conditions = True
364
+ supports_versions = False
365
+
366
+ def __init__(self, store: InMemoryStore, working: dict[str, Any], resource: str) -> None:
367
+ self._store = store
368
+ self._working = working
369
+ self._resource = resource
370
+
371
+ def _read(self, resource: str) -> list[Any]:
372
+ family = self._store.families.get(resource)
373
+ rows = self._working.get(family[0] if family else resource, {}).values()
374
+ return [e for e in rows if _of_kind(e, family)]
375
+
376
+ def _rows(self) -> InMemoryRepository[Any]:
377
+ from resource_engine.application.views import Aggregate, compute
378
+
379
+ spec, model = self._store.views[self._resource]
380
+ id_field = self._store.id_fields.get(self._resource, "id")
381
+ raw = (
382
+ compute(spec, self._read(spec.source), id_field)
383
+ if isinstance(spec, Aggregate)
384
+ else spec(self._read)
385
+ )
386
+ entities = [model(**r) if isinstance(r, dict) else r for r in raw]
387
+ table = {getattr(e, id_field): e for e in entities}
388
+ return InMemoryRepository(self._store, table, self._resource)
389
+
390
+ async def get(self, entity_id: Any) -> Any:
391
+ """The view row with ``entity_id``, or ``None``."""
392
+ return await self._rows().get(entity_id)
393
+
394
+ async def list(self, query: ListQuery) -> Page[Any]:
395
+ """One page of the view's rows matching ``query``."""
396
+ return await self._rows().list(query)
397
+
398
+ async def add(self, entity: Any) -> Any:
399
+ """Refused: a view cannot be written."""
400
+ raise TypeError(f"{self._resource} is a view: it cannot be written")
401
+
402
+ update = delete = add
403
+
404
+
405
+ class InMemoryUnitOfWork(UnitOfWork, SupportsOutbox, SupportsInbox, SupportsIdempotency):
406
+ """A unit of work over the in-memory store: writes are applied on commit, with version
407
+ checks."""
408
+
409
+ def __init__(self, store: InMemoryStore) -> None:
410
+ self._store = store
411
+ self._working: dict[str, dict[Any, Any]] | None = None
412
+ self._checks: list[tuple[str, Any, int]] = []
413
+ self._new_keys: set[tuple[str, str]] = set()
414
+ self.committed = False
415
+
416
+ async def __aenter__(self) -> Self:
417
+ self._working = copy.deepcopy(self._store.tables)
418
+ self._checks = []
419
+ self._new_keys = set()
420
+ self.committed = False
421
+ return self
422
+
423
+ async def __aexit__(
424
+ self,
425
+ exc_type: type[BaseException] | None,
426
+ exc: BaseException | None,
427
+ tb: TracebackType | None,
428
+ ) -> None:
429
+ if not self.committed:
430
+ await self.rollback()
431
+
432
+ @override
433
+ def repository(self, resource_name: str) -> Any:
434
+ if self._working is None:
435
+ raise RuntimeError("Unit of work is not active")
436
+ if resource_name in self._store.views:
437
+ return InMemoryViewRepository(self._store, self._working, resource_name)
438
+ family = self._store.families.get(resource_name)
439
+ table = self._working.setdefault(family[0] if family else resource_name, {})
440
+ return InMemoryRepository(self._store, table, resource_name, self._checks)
441
+
442
+ @override
443
+ def outbox(self) -> InMemoryOutbox:
444
+ if self._working is None:
445
+ raise RuntimeError("Unit of work is not active")
446
+ return InMemoryOutbox(self._working.setdefault(OUTBOX_TABLE, {}))
447
+
448
+ @override
449
+ def inbox(self) -> InMemoryInbox:
450
+ if self._working is None:
451
+ raise RuntimeError("Unit of work is not active")
452
+ return InMemoryInbox(self._working.setdefault(INBOX_TABLE, {}))
453
+
454
+ @override
455
+ def idempotency(self) -> InMemoryIdempotency:
456
+ if self._working is None:
457
+ raise RuntimeError("Unit of work is not active")
458
+ return InMemoryIdempotency(self._working.setdefault(IDEMPOTENCY_TABLE, {}), self._new_keys)
459
+
460
+ @override
461
+ async def commit(self) -> None:
462
+ if self._working is None:
463
+ raise RuntimeError("Unit of work is not active")
464
+ committed_keys = self._store.tables.get(IDEMPOTENCY_TABLE, {})
465
+ for key in self._new_keys: # another unit of work stored the same key first
466
+ existing = committed_keys.get(key)
467
+ if existing is not None and existing.expires_at and existing.expires_at > _now():
468
+ raise IdempotencyConflict(f"Idempotency key {key[1]!r} already committed")
469
+ self._new_keys = set()
470
+ for resource, entity_id, expected in self._checks: # another unit of work won
471
+ field_name = self._store.version_fields.get(resource, "version")
472
+ _check_committed(self._store, resource, entity_id, expected, field_name)
473
+ self._checks = []
474
+ self._store.tables = self._working
475
+ self._working = copy.deepcopy(self._working)
476
+ self.committed = True
477
+
478
+ @override
479
+ async def rollback(self) -> None:
480
+ self._checks = []
481
+ self._working = copy.deepcopy(self._store.tables)
482
+
483
+
484
+ class RecordingMessagePublisher(MessagePublisher):
485
+ """In-memory ``MessagePublisher``. ``fail_ids`` simulates partial failures."""
486
+
487
+ def __init__(self) -> None:
488
+ self.messages: list[EventEnvelope] = []
489
+ self.fail_ids: set[str] = set()
490
+
491
+ @override
492
+ async def publish(self, messages: Sequence[EventEnvelope]) -> None:
493
+ from resource_engine.errors import PublishFailed
494
+
495
+ failed = [m.id for m in messages if m.id in self.fail_ids]
496
+ self.messages.extend(m for m in messages if m.id not in self.fail_ids)
497
+ if failed:
498
+ raise PublishFailed(f"{len(failed)} messages rejected", failed_ids=failed)
499
+
500
+
501
+ class RecordingEventPublisher(EventPublisher):
502
+ """Keeps published events in ``self.events``; handy for assertions."""
503
+
504
+ def __init__(self) -> None:
505
+ self.events: list[DomainEvent] = []
506
+
507
+ @override
508
+ async def publish(self, events: Sequence[DomainEvent]) -> None:
509
+ self.events.extend(events)
510
+
511
+ def names(self) -> list[str]:
512
+ """The names of the published events, in order."""
513
+ return [e.name for e in self.events]
514
+
515
+
516
+ @dataclass
517
+ class _Queued:
518
+ envelope: EventEnvelope
519
+ deliveries: int = 0
520
+ visible_at: float = 0.0
521
+ in_flight: bool = False
522
+
523
+
524
+ @dataclass
525
+ class InMemoryQueue(MessagePublisher, MessageSource, SupportsDeadLetter):
526
+ """In-process broker: a ``MessagePublisher`` and a ``MessageSource`` with
527
+ dead-lettering, delivery counts and retry delays. For tests and prototypes.
528
+
529
+ ``dead_letters`` keeps ``(envelope, reason)`` for dead-lettered messages.
530
+ """
531
+
532
+ messages: list[_Queued] = field(default_factory=list)
533
+ dead_letters: list[tuple[EventEnvelope, str]] = field(default_factory=list)
534
+
535
+ @override
536
+ async def publish(self, messages: Sequence[EventEnvelope]) -> None:
537
+ self.messages.extend(_Queued(m) for m in messages)
538
+
539
+ def _ready(self) -> list[_Queued]:
540
+ now = time.monotonic()
541
+ return [q for q in self.messages if not q.in_flight and q.visible_at <= now]
542
+
543
+ @override
544
+ async def receive(self, max_messages: int, wait_seconds: float) -> list[ReceivedMessage]:
545
+ deadline = time.monotonic() + wait_seconds
546
+ while not (ready := self._ready()) and time.monotonic() < deadline: # noqa: ASYNC110
547
+ await asyncio.sleep(min(0.01, wait_seconds))
548
+ batch = ready[:max_messages]
549
+ for q in batch:
550
+ q.in_flight = True
551
+ q.deliveries += 1
552
+ return [ReceivedMessage(q.envelope, q, q.deliveries, None, q.envelope.id) for q in batch]
553
+
554
+ @override
555
+ async def ack(self, messages: Sequence[ReceivedMessage]) -> None:
556
+ for m in messages:
557
+ if m.handle in self.messages:
558
+ self.messages.remove(m.handle)
559
+
560
+ @override
561
+ async def retry(self, messages: Sequence[ReceivedMessage], delay_seconds: float) -> None:
562
+ for m in messages:
563
+ m.handle.in_flight = False
564
+ m.handle.visible_at = time.monotonic() + delay_seconds
565
+
566
+ @override
567
+ async def dead_letter(self, messages: Sequence[ReceivedMessage], reason: str) -> None:
568
+ for m in messages:
569
+ await self.ack([m])
570
+ self.dead_letters.append((m.handle.envelope, reason))
571
+
572
+ @property
573
+ def pending(self) -> int:
574
+ """How many messages are in the queue (in flight included)."""
575
+ return len(self.messages)
576
+
577
+
578
+ class InMemoryLocks(LockProvider):
579
+ """``LockProvider`` for one process (tests, single-worker deployments)."""
580
+
581
+ def __init__(self, clock: Any = None) -> None:
582
+ self._leases: dict[str, tuple[str, datetime]] = {}
583
+ self._clock = clock or (lambda: datetime.now(UTC))
584
+
585
+ @override
586
+ async def acquire(self, name: str, owner: str, ttl: Any) -> bool:
587
+ now = self._clock()
588
+ held = self._leases.get(name)
589
+ if held is not None and held[0] != owner and held[1] > now:
590
+ return False
591
+ self._leases[name] = (owner, now + ttl)
592
+ return True
593
+
594
+ @override
595
+ async def release(self, name: str, owner: str) -> None:
596
+ held = self._leases.get(name)
597
+ if held is not None and held[0] == owner:
598
+ del self._leases[name]
599
+
600
+ def holder(self, name: str) -> str | None:
601
+ """Who holds the lease of ``name`` now, if anyone."""
602
+ held = self._leases.get(name)
603
+ return held[0] if held is not None and held[1] > self._clock() else None