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,84 @@
1
+ """The outbox relay: publishes the events written to the outbox."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ import logging
8
+ from collections.abc import Callable
9
+ from typing import Any
10
+
11
+ from resource_engine.errors import PublishFailed
12
+ from resource_engine.ports.messaging import MessagePublisher, SupportsOutbox
13
+ from resource_engine.reporting import report_error
14
+ from resource_engine.tracing import get_tracer
15
+
16
+ logger = logging.getLogger("resource_engine.outbox")
17
+
18
+
19
+ class OutboxRelay:
20
+ """Moves pending outbox records to a broker. At-least-once.
21
+
22
+ Run ``run_once`` from a scheduled job, or ``run_forever`` in a worker process.
23
+ Several relays may run concurrently on SQL stores that lock rows (SKIP LOCKED).
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ uow_factory: Callable[[], Any],
29
+ transport: MessagePublisher,
30
+ *,
31
+ batch_size: int = 100,
32
+ max_attempts: int = 10,
33
+ ) -> None:
34
+ self.uow_factory = uow_factory
35
+ self.transport = transport
36
+ self.batch_size = batch_size
37
+ self.max_attempts = max_attempts
38
+
39
+ async def run_once(self) -> int:
40
+ """Publish one batch. Returns how many messages were published."""
41
+ async with self.uow_factory() as uow:
42
+ if not isinstance(uow, SupportsOutbox):
43
+ raise TypeError(f"{type(uow).__name__} has no outbox()")
44
+ unit: Any = uow # a unit of work with an outbox: it commits too
45
+ outbox = uow.outbox()
46
+ records = [
47
+ r for r in await outbox.pending(self.batch_size) if r.attempts < self.max_attempts
48
+ ]
49
+ if not records:
50
+ return 0
51
+ ids = [r.envelope.id for r in records]
52
+ failed: list[str] = []
53
+ try:
54
+ async with get_tracer().span(
55
+ "outbox publish",
56
+ kind="producer",
57
+ attributes={"messaging.batch.message_count": len(records)},
58
+ ):
59
+ await self.transport.publish([r.envelope for r in records])
60
+ except PublishFailed as exc:
61
+ failed = list(exc.failed_ids)
62
+ await outbox.mark_failed(failed, exc.message)
63
+ logger.warning("Outbox: %d of %d messages failed", len(failed), len(ids))
64
+ await report_error(exc, where="outbox", failed=len(failed), batch=len(ids))
65
+ except Exception as exc:
66
+ await outbox.mark_failed(ids, f"{type(exc).__name__}: {exc}")
67
+ await unit.commit()
68
+ await report_error(exc, where="outbox", force=True, batch=len(ids))
69
+ return 0
70
+ published = [i for i in ids if i not in set(failed)]
71
+ await outbox.mark_published(published)
72
+ await unit.commit()
73
+ return len(published)
74
+
75
+ async def run_forever(
76
+ self, *, interval: float = 1.0, stop: asyncio.Event | None = None
77
+ ) -> None:
78
+ """Relay until ``stop`` is set, waiting ``interval`` seconds when the outbox is empty."""
79
+ stop = stop or asyncio.Event()
80
+ while not stop.is_set():
81
+ published = await self.run_once()
82
+ if published < self.batch_size:
83
+ with contextlib.suppress(TimeoutError):
84
+ await asyncio.wait_for(stop.wait(), timeout=interval)
@@ -0,0 +1,166 @@
1
+ """Pull consumer loop over any ``MessageSource``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ import logging
8
+ from collections import defaultdict
9
+ from dataclasses import dataclass
10
+
11
+ from resource_engine.messaging.processing import MessageProcessor, Outcome, ProcessResult
12
+ from resource_engine.ports.messaging import MessageSource, ReceivedMessage, SupportsDeadLetter
13
+
14
+ log = logging.getLogger("resource_engine.messaging")
15
+
16
+
17
+ @dataclass
18
+ class ConsumerStats:
19
+ """Counts of what a consumer did with the messages it received."""
20
+
21
+ received: int = 0
22
+ acked: int = 0
23
+ duplicates: int = 0
24
+ retried: int = 0
25
+ dead_lettered: int = 0
26
+
27
+ def add(self, other: ConsumerStats) -> None:
28
+ """Add ``other``'s counts to these."""
29
+ for name in vars(self):
30
+ setattr(self, name, getattr(self, name) + getattr(other, name))
31
+
32
+
33
+ class MessageConsumer:
34
+ """Receives batches from a source and settles each message after processing.
35
+
36
+ Messages in a batch are processed in order. When a message fails, later
37
+ messages with the same ``key`` in that batch are retried without being
38
+ processed, so per-entity order holds on FIFO queues and ordered subscriptions.
39
+ With ``concurrency`` above 1, messages with different keys run concurrently
40
+ (up to that many at once) while each key keeps its order; messages without a
41
+ key are independent.
42
+
43
+ Dead-lettering uses the source's ``dead_letter`` when it has one; otherwise
44
+ the message is retried with the maximum delay and the broker's redrive policy
45
+ is expected to move it.
46
+
47
+ Args:
48
+ source: Where messages come from.
49
+ processor: What to do with each message.
50
+ batch_size: Messages per ``receive`` call.
51
+ wait_seconds: Long-poll wait when the source is empty.
52
+ concurrency: Keys processed at the same time within a batch.
53
+ """
54
+
55
+ def __init__(
56
+ self,
57
+ source: MessageSource,
58
+ processor: MessageProcessor,
59
+ *,
60
+ batch_size: int = 10,
61
+ wait_seconds: float = 20.0,
62
+ concurrency: int = 1,
63
+ ) -> None:
64
+ if concurrency < 1:
65
+ raise ValueError("concurrency must be at least 1")
66
+ self.source = source
67
+ self.processor = processor
68
+ self.batch_size = batch_size
69
+ self.wait_seconds = wait_seconds
70
+ self.concurrency = concurrency
71
+
72
+ async def run_once(self) -> ConsumerStats:
73
+ """Receive and settle one batch."""
74
+ messages = await self.source.receive(self.batch_size, self.wait_seconds)
75
+ stats = ConsumerStats(received=len(messages))
76
+ if self.concurrency == 1:
77
+ outcomes = await self._in_order(messages)
78
+ else:
79
+ outcomes = await self._by_key(messages)
80
+ await self._settle(list(zip(messages, outcomes, strict=True)), stats)
81
+ return stats
82
+
83
+ async def _in_order(self, messages: list[ReceivedMessage]) -> list[ProcessResult]:
84
+ """One by one; a failed key blocks its later messages."""
85
+ results: list[ProcessResult] = []
86
+ blocked: set[str] = set()
87
+ for message in messages:
88
+ key = message.envelope.key if message.envelope else None
89
+ if key is not None and key in blocked:
90
+ result = ProcessResult(
91
+ Outcome.RETRY, "an earlier message with this key failed", blocked=True
92
+ )
93
+ await self.processor.observe(message, result, 0.0)
94
+ else:
95
+ result = await self.processor.process(message)
96
+ if result.outcome is Outcome.RETRY and key is not None:
97
+ blocked.add(key)
98
+ results.append(result)
99
+ return results
100
+
101
+ async def _by_key(self, messages: list[ReceivedMessage]) -> list[ProcessResult]:
102
+ """Groups by key run concurrently; each group in order."""
103
+ groups: dict[object, list[int]] = {}
104
+ for index, message in enumerate(messages):
105
+ key = message.envelope.key if message.envelope else None
106
+ groups.setdefault(key if key is not None else object(), []).append(index)
107
+ results: list[ProcessResult | None] = [None] * len(messages)
108
+ limit = asyncio.Semaphore(self.concurrency)
109
+
110
+ async def run(indexes: list[int]) -> None:
111
+ async with limit:
112
+ outcomes = await self._in_order([messages[i] for i in indexes])
113
+ for i, result in zip(indexes, outcomes, strict=True):
114
+ results[i] = result
115
+
116
+ await asyncio.gather(*(run(indexes) for indexes in groups.values()))
117
+ return [r for r in results if r is not None]
118
+
119
+ async def _settle(
120
+ self, results: list[tuple[ReceivedMessage, ProcessResult]], stats: ConsumerStats
121
+ ) -> None:
122
+ settled = [m for m, r in results if r.outcome.settled]
123
+ stats.acked = sum(r.outcome is Outcome.ACK for _, r in results)
124
+ stats.duplicates = sum(r.outcome is Outcome.DUPLICATE for _, r in results)
125
+ if settled:
126
+ await self.source.ack(settled)
127
+
128
+ retries: dict[float, list[ReceivedMessage]] = defaultdict(list)
129
+ for message, result in results:
130
+ if result.outcome is Outcome.RETRY:
131
+ retries[result.delay_seconds].append(message)
132
+ stats.retried += 1
133
+ for delay, batch in retries.items():
134
+ await self.source.retry(batch, delay)
135
+
136
+ dead = [(m, r) for m, r in results if r.outcome is Outcome.DEAD_LETTER]
137
+ stats.dead_lettered = len(dead)
138
+ for message, result in dead:
139
+ if isinstance(self.source, SupportsDeadLetter):
140
+ await self.source.dead_letter([message], result.error or "rejected")
141
+ else:
142
+ log.error(
143
+ "Source %s cannot dead-letter; leaving message %s to the broker's "
144
+ "redrive policy",
145
+ type(self.source).__name__,
146
+ message.message_id,
147
+ )
148
+ await self.source.retry([message], self.processor.retry.max_delay)
149
+
150
+ async def run_forever(self, stop: asyncio.Event | None = None) -> ConsumerStats:
151
+ """Loop until ``stop`` is set. Source errors are logged and retried with backoff."""
152
+ stop = stop or asyncio.Event()
153
+ total = ConsumerStats()
154
+ backoff = 1.0
155
+ while not stop.is_set():
156
+ try:
157
+ total.add(await self.run_once())
158
+ backoff = 1.0
159
+ except asyncio.CancelledError:
160
+ raise
161
+ except Exception:
162
+ log.exception("Consumer %s failed; retrying in %.0fs", self.processor.name, backoff)
163
+ with contextlib.suppress(TimeoutError):
164
+ await asyncio.wait_for(stop.wait(), timeout=backoff)
165
+ backoff = min(backoff * 2, 60.0)
166
+ return total
@@ -0,0 +1,394 @@
1
+ """Building blocks for document-store repositories (DynamoDB, Cosmos DB,
2
+ Firestore): writes buffered in the unit of work and applied at commit in one
3
+ transaction of the store, records encoded as documents, generated ids, and
4
+ row filters rewritten without ``not``.
5
+
6
+ - **Writes at commit:** ``add``, ``update`` and ``delete`` are recorded and
7
+ sent together by ``commit`` (``TransactWriteItems``, a Cosmos transactional
8
+ batch, a Firestore commit), so an operation's writes are all or nothing
9
+ within the store's ``transaction_scope``. Past ``max_writes`` the commit
10
+ fails with ``TransactionTooLarge`` (RE-E012) and nothing is written.
11
+ - **Reads see the operation's writes** by id (``get``); ``list`` reads what
12
+ is committed.
13
+ - **Versions** are compared by the store when the writes are applied
14
+ (a condition on the version field), so two operations racing on one
15
+ record can't both win: the loser gets ``VersionConflict``.
16
+ - **Ids** are generated by type: random 53-bit integers for ``int`` ids (safe
17
+ in JSON), UUIDs for ``UUID``, 32 hex characters for ``str``.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import dataclasses
23
+ import secrets
24
+ import types
25
+ import typing
26
+ import uuid
27
+ from collections.abc import Mapping, Sequence
28
+ from dataclasses import dataclass
29
+ from typing import Any, Literal, override
30
+
31
+ from resource_engine.application.query import ListQuery, Page
32
+ from resource_engine.errors import TransactionTooLarge, VersionConflict
33
+ from resource_engine.ports.repository import Repository
34
+ from resource_engine.ports.unit_of_work import UnitOfWork
35
+
36
+ # ------------------------------------------------------------------- codec
37
+
38
+
39
+ class DocumentCodec:
40
+ """A model's records as plain documents (dicts of Python values) and back.
41
+
42
+ Values keep their Python types (``Decimal``, ``datetime``, ``date``); each
43
+ adapter maps them to its store's types. Decoding validates with pydantic,
44
+ so strings and numbers from the store come back as the model's types.
45
+ """
46
+
47
+ def __init__(self, model: type, *, id_field: str = "id") -> None:
48
+ from pydantic import TypeAdapter
49
+
50
+ self.model = model
51
+ self.id_field = id_field
52
+ try:
53
+ hints = typing.get_type_hints(model)
54
+ except Exception:
55
+ hints = {}
56
+ self.id_type = _base_type(hints.get(id_field, str))
57
+ self._fields: dict[str, Any] | None = None
58
+ self._adapter: Any = None
59
+ if dataclasses.is_dataclass(model) and not hasattr(model, "__pydantic_fields__"):
60
+ # field by field, then the constructor: mapped classes (SQLAlchemy) need __init__
61
+ names = [f.name for f in dataclasses.fields(model)]
62
+ self._fields = {n: TypeAdapter(hints.get(n, Any)) for n in names}
63
+ else:
64
+ try:
65
+ self._adapter = TypeAdapter(model)
66
+ except Exception:
67
+ self._adapter = None
68
+
69
+ def encode(self, entity: Any) -> dict[str, Any]:
70
+ """The document of ``entity``."""
71
+ if self._fields is not None:
72
+ return {
73
+ name: adapter.dump_python(getattr(entity, name), mode="python")
74
+ for name, adapter in self._fields.items()
75
+ }
76
+ if self._adapter is not None:
77
+ dumped: dict[str, Any] = self._adapter.dump_python(entity, mode="python")
78
+ return dumped
79
+ return {k: v for k, v in vars(entity).items() if not k.startswith("_")}
80
+
81
+ def decode(self, document: Mapping[str, Any]) -> Any:
82
+ """The entity of ``document``."""
83
+ if self._fields is not None:
84
+ return self.model(
85
+ **{
86
+ name: adapter.validate_python(document[name])
87
+ for name, adapter in self._fields.items()
88
+ if name in document
89
+ }
90
+ )
91
+ if self._adapter is not None:
92
+ return self._adapter.validate_python(dict(document))
93
+ return self.model(**dict(document))
94
+
95
+ def new_id(self) -> Any:
96
+ """A new id of the model's id type."""
97
+ if self.id_type is int:
98
+ return secrets.randbits(53) or 1
99
+ if self.id_type is uuid.UUID:
100
+ return uuid.uuid4()
101
+ return uuid.uuid4().hex
102
+
103
+
104
+ def _base_type(hint: Any) -> type:
105
+ if typing.get_origin(hint) in (typing.Union, types.UnionType):
106
+ args = [a for a in typing.get_args(hint) if a is not type(None)]
107
+ hint = args[0] if args else str
108
+ return hint if isinstance(hint, type) else str
109
+
110
+
111
+ # ------------------------------------------------------------------ writes
112
+
113
+
114
+ @dataclass
115
+ class Write:
116
+ """One buffered write, applied by the unit of work at commit."""
117
+
118
+ kind: Literal["put", "delete"]
119
+ resource: str
120
+ key: Any
121
+ document: dict[str, Any] | None = None
122
+ #: The write creates the record: it fails if the id is taken.
123
+ create: bool = False
124
+ #: Compare-and-set: the stored version must still be this one.
125
+ expected_version: int | None = None
126
+ version_field: str = "version"
127
+
128
+
129
+ def version_conflict(write: Write, current: Any = None) -> VersionConflict:
130
+ """The conflict to raise when a conditional write lost (a record already existed, or its version
131
+ changed)."""
132
+ if write.create:
133
+ return VersionConflict(
134
+ f"{write.resource} {write.key!r} already exists",
135
+ hint="Retry: another record took the same id.",
136
+ details={"resource": write.resource, "id": write.key, "reason": "already exists"},
137
+ )
138
+ return VersionConflict(
139
+ f"{write.resource} {write.key!r} changed since it was read",
140
+ hint="Reload the record and apply your change again.",
141
+ details={
142
+ "resource": write.resource,
143
+ "id": write.key,
144
+ "expected": write.expected_version,
145
+ "current": current,
146
+ "reason": "version conflict",
147
+ },
148
+ )
149
+
150
+
151
+ class DocumentUnitOfWork(UnitOfWork):
152
+ """Buffers the writes of its repositories and applies them at ``commit``.
153
+
154
+ Subclasses set ``transaction_scope`` and ``max_writes``, hand out
155
+ repositories (``repository``) and send the writes (``apply``)."""
156
+
157
+ transactional = True
158
+ transaction_scope: str = "unit_of_work"
159
+ max_writes: int | None = None
160
+
161
+ def __init__(self) -> None:
162
+ self.writes: dict[tuple[str, Any], Write] = {}
163
+ self._repositories: dict[str, Any] = {}
164
+
165
+ def make_repository(self, resource_name: str) -> Any: # pragma: no cover - abstract
166
+ """The store's repository for ``resource_name`` (implemented by each store)."""
167
+ raise NotImplementedError
168
+
169
+ @override
170
+ def repository(self, resource_name: str) -> Any:
171
+ if resource_name not in self._repositories:
172
+ self._repositories[resource_name] = self.make_repository(resource_name)
173
+ return self._repositories[resource_name]
174
+
175
+ async def apply(self, writes: Sequence[Write]) -> None: # pragma: no cover - abstract
176
+ """Send ``writes`` in one transaction; raise ``version_conflict(...)``
177
+ when a condition fails."""
178
+ raise NotImplementedError
179
+
180
+ def record(self, write: Write) -> None:
181
+ """Buffer ``write``, merged with an earlier write of the same record."""
182
+ slot = (write.resource, _hashable(write.key))
183
+ earlier = self.writes.pop(slot, None)
184
+ if earlier is not None:
185
+ if earlier.create and write.kind == "delete":
186
+ return # created and deleted in the same unit of work: nothing to send
187
+ write.create = write.create or earlier.create
188
+ if earlier.expected_version is not None:
189
+ write.expected_version = earlier.expected_version
190
+ self.writes[slot] = write
191
+
192
+ def pending(self, resource: str, key: Any) -> Write | None:
193
+ """The buffered write of a record, if any."""
194
+ return self.writes.get((resource, _hashable(key)))
195
+
196
+ @override
197
+ async def commit(self) -> None:
198
+ writes = list(self.writes.values())
199
+ if not writes:
200
+ return
201
+ if self.max_writes is not None and len(writes) > self.max_writes:
202
+ raise TransactionTooLarge(
203
+ f"{len(writes)} writes in one commit; the store takes {self.max_writes}",
204
+ hint="Split the operation, or move bulk changes to a job.",
205
+ details={"writes": len(writes), "max_writes": self.max_writes},
206
+ )
207
+ await self.apply(writes)
208
+ self.writes.clear()
209
+
210
+ @override
211
+ async def rollback(self) -> None:
212
+ self.writes.clear()
213
+
214
+ async def __aenter__(self) -> Any:
215
+ self.writes.clear()
216
+ self._repositories.clear()
217
+ return self
218
+
219
+ async def __aexit__(self, *exc: Any) -> None:
220
+ self.writes.clear()
221
+
222
+
223
+ def _hashable(key: Any) -> Any:
224
+ return key if isinstance(key, (str, int, uuid.UUID)) else repr(key)
225
+
226
+
227
+ class DocumentRepository(Repository[Any]):
228
+ """A ``Repository`` over a document store: reads from the store (``fetch``,
229
+ ``query``), writes buffered in its ``DocumentUnitOfWork``."""
230
+
231
+ supports_conditions = True
232
+ supports_versions = True
233
+ filterable: frozenset[str] | None = None
234
+ sortable: frozenset[str] | None = None
235
+ max_offset: int | None = None
236
+
237
+ def __init__(
238
+ self,
239
+ uow: DocumentUnitOfWork,
240
+ resource: str,
241
+ codec: DocumentCodec,
242
+ *,
243
+ version_field: str | None = None,
244
+ ) -> None:
245
+ self.uow = uow
246
+ self.resource = resource
247
+ self.codec = codec
248
+ self.version_field = version_field or "version"
249
+
250
+ # -- reads, implemented by the adapter
251
+ async def fetch(self, key: Any) -> dict[str, Any] | None: # pragma: no cover - abstract
252
+ """The stored document with ``key``, or ``None`` (implemented by each store)."""
253
+ raise NotImplementedError
254
+
255
+ async def query(self, query: ListQuery) -> tuple[list[dict[str, Any]], int]: # pragma: no cover
256
+ """The page's documents and the total matching."""
257
+ raise NotImplementedError
258
+
259
+ # -- the Repository port
260
+ @override
261
+ async def get(self, entity_id: Any) -> Any:
262
+ write = self.uow.pending(self.resource, entity_id)
263
+ if write is not None:
264
+ return None if write.kind == "delete" else self.codec.decode(write.document or {})
265
+ document = await self.fetch(entity_id)
266
+ return self.codec.decode(document) if document is not None else None
267
+
268
+ @override
269
+ async def list(self, query: ListQuery) -> Page[Any]:
270
+ documents, total = await self.query(query)
271
+ return Page([self.codec.decode(d) for d in documents], total, query.offset, query.limit)
272
+
273
+ def _key(self, entity: Any) -> Any:
274
+ return getattr(entity, self.codec.id_field)
275
+
276
+ @override
277
+ async def add(self, entity: Any) -> Any:
278
+ if self._key(entity) is None:
279
+ setattr(entity, self.codec.id_field, self.codec.new_id())
280
+ self.uow.record(
281
+ Write("put", self.resource, self._key(entity), self.codec.encode(entity), create=True)
282
+ )
283
+ return entity
284
+
285
+ @override
286
+ async def update(self, entity: Any, *, expected_version: int | None = None) -> Any:
287
+ if expected_version is not None:
288
+ setattr(entity, self.version_field, expected_version + 1)
289
+ self.uow.record(
290
+ Write(
291
+ "put",
292
+ self.resource,
293
+ self._key(entity),
294
+ self.codec.encode(entity),
295
+ expected_version=expected_version,
296
+ version_field=self.version_field,
297
+ )
298
+ )
299
+ return entity
300
+
301
+ @override
302
+ async def delete(self, entity: Any, *, expected_version: int | None = None) -> None:
303
+ self.uow.record(
304
+ Write(
305
+ "delete",
306
+ self.resource,
307
+ self._key(entity),
308
+ self.codec.encode(entity), # the record deleted (partition keys)
309
+ expected_version=expected_version,
310
+ version_field=self.version_field,
311
+ )
312
+ )
313
+
314
+
315
+ def select(entities: Sequence[Any], query: ListQuery) -> tuple[list[Any], int]:
316
+ """Filter, sort and page records in memory (for stores that read a key
317
+ range or a scan and can't sort): the page and the total matching."""
318
+ from resource_engine.authz.conditions import matches
319
+ from resource_engine.translatable import localise
320
+
321
+ def value(entity: Any, name: str) -> Any:
322
+ found = getattr(entity, name, None)
323
+ return localise(found, query.locales) if name in query.translatable else found
324
+
325
+ items = [
326
+ e
327
+ for e in entities
328
+ if all(value(e, k) == v for k, v in query.filters.items()) and matches(query.condition, e)
329
+ ]
330
+ for key in reversed(list(query.order_by)):
331
+ name = key.lstrip("-")
332
+ items.sort(
333
+ key=lambda e: (value(e, name) is None, value(e, name)), reverse=key.startswith("-")
334
+ )
335
+ return items[query.offset : query.offset + query.limit], len(items)
336
+
337
+
338
+ # -------------------------------------------------------------- conditions
339
+
340
+ _NEGATED = {"eq": "ne", "ne": "eq", "lt": "ge", "le": "gt", "gt": "le", "ge": "lt"}
341
+
342
+
343
+ def without_not(node: Any) -> Any:
344
+ """``node`` with ``not`` pushed down to the comparisons (``not lt`` →
345
+ ``ge``, ``not in`` → ``nin``, De Morgan for ``and``/``or``), for stores
346
+ whose queries have no negation. ``not`` stays around ``exists`` and
347
+ ``contains``. Records missing the field compare as in the store."""
348
+ if isinstance(node, bool) or not isinstance(node, Mapping) or len(node) != 1:
349
+ return node
350
+ op, args = next(iter(node.items()))
351
+ if op in ("and", "or"):
352
+ return {op: [without_not(a) for a in args]}
353
+ if op != "not":
354
+ return node
355
+ inner = args
356
+ if isinstance(inner, bool):
357
+ return not inner
358
+ if not isinstance(inner, Mapping) or len(inner) != 1:
359
+ return node
360
+ iop, iargs = next(iter(inner.items()))
361
+ if iop == "not":
362
+ return without_not(iargs)
363
+ if iop in _NEGATED:
364
+ return {_NEGATED[iop]: iargs}
365
+ if iop == "in":
366
+ return {"nin": iargs}
367
+ if iop == "nin":
368
+ return {"in": iargs}
369
+ if iop == "and":
370
+ return {"or": [without_not({"not": a}) for a in iargs]}
371
+ if iop == "or":
372
+ return {"and": [without_not({"not": a}) for a in iargs]}
373
+ return {"not": inner}
374
+
375
+
376
+ def field_of(operand: Any) -> str | None:
377
+ """The record field of an operand (``{"attr": "resource.x"}`` → ``x``)."""
378
+ if isinstance(operand, Mapping) and "attr" in operand:
379
+ path = str(operand["attr"])
380
+ if path.startswith("resource."):
381
+ return path.removeprefix("resource.")
382
+ return None
383
+
384
+
385
+ __all__ = [
386
+ "DocumentCodec",
387
+ "DocumentRepository",
388
+ "DocumentUnitOfWork",
389
+ "Write",
390
+ "field_of",
391
+ "select",
392
+ "version_conflict",
393
+ "without_not",
394
+ ]
@@ -0,0 +1,13 @@
1
+ """Ports the engine depends on. Adapters (SQLAlchemy, in-memory, ...) implement them."""
2
+
3
+ from resource_engine.ports.event_publisher import EventPublisher, NullEventPublisher
4
+ from resource_engine.ports.repository import Repository
5
+ from resource_engine.ports.unit_of_work import UnitOfWork, UnitOfWorkFactory
6
+
7
+ __all__ = [
8
+ "EventPublisher",
9
+ "NullEventPublisher",
10
+ "Repository",
11
+ "UnitOfWork",
12
+ "UnitOfWorkFactory",
13
+ ]