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,347 @@
1
+ """Timed transitions: deadlines declared on a resource, run by the worker.
2
+
3
+ ```python
4
+ class InvoiceResource(Resource):
5
+ # since_field: stamped by the engine on every state change
6
+ state_machine = Machine(InvoiceStateMachine, since_field="status_changed_at")
7
+ timers = [
8
+ Timer("reject", after=timedelta(days=30), data={"reason": "No answer in 30 days"}),
9
+ ]
10
+ ```
11
+
12
+ A record is due when it has been in one of the timer's states (by default the
13
+ event's source states) for ``after``, counted from ``since`` (by default the
14
+ resource's ``state_since_field``). ``TimerJob`` finds due records and runs the
15
+ transition through ``ResourceManager.transition`` as the system principal, so
16
+ guards, hooks, the audit trail, events and the record's history apply as for
17
+ any transition. See docs/timers.md.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import dataclasses
23
+ import logging
24
+ from collections.abc import Callable, Mapping, Sequence
25
+ from dataclasses import dataclass
26
+ from datetime import UTC, datetime, timedelta
27
+ from typing import TYPE_CHECKING, Any
28
+
29
+ from resource_engine.errors import ConfigurationError, EntityNotFound, TransitionNotAllowed
30
+
31
+ if TYPE_CHECKING:
32
+ from resource_engine.application.manager import ResourceManager
33
+ from resource_engine.application.resource import ResourceDefinition
34
+
35
+ logger = logging.getLogger("resource_engine.timers")
36
+ DOC = "docs/timers.md"
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class Timer:
41
+ """Run ``event`` once a record has waited ``after`` in one of ``states``.
42
+
43
+ Args:
44
+ event: The transition to run.
45
+ after: How long the record waits first.
46
+ since: Datetime field the wait is counted from (default: the resource's
47
+ ``state_since_field``, the moment it entered its current state).
48
+ states: States the record must be in (default: the event's sources).
49
+ data: Input of the transition, validated against its schema.
50
+ description: What the deadline means, for the generated docs.
51
+ """
52
+
53
+ event: str
54
+ after: timedelta
55
+ since: str | None = None
56
+ states: Sequence[str] | None = None
57
+ data: Mapping[str, Any] | None = None
58
+ description: str | None = None
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class TimerDefinition:
63
+ """A validated timer: ``states`` are the stored state values."""
64
+
65
+ resource: str
66
+ event: str
67
+ after: timedelta
68
+ since: str
69
+ states: tuple[Any, ...]
70
+ data: Mapping[str, Any] | None
71
+ description: str | None
72
+ field: str = "status" # the state field of the event's machine
73
+
74
+
75
+ def normalize_timers(
76
+ owner: str,
77
+ name: str,
78
+ timers: Sequence[Timer],
79
+ *,
80
+ machines: Mapping[str, Any],
81
+ transition_schemas: Mapping[str, Any],
82
+ known_fields: set[str],
83
+ ) -> tuple[TimerDefinition, ...]:
84
+ """Validate a resource's timers against its machines and fields, and give each its defaults."""
85
+ out: list[TimerDefinition] = []
86
+ if not timers:
87
+ return ()
88
+ if not machines:
89
+ raise ConfigurationError(f"{owner}: timers need a state machine", doc=DOC)
90
+ for timer in timers:
91
+ if not isinstance(timer, Timer):
92
+ raise ConfigurationError(
93
+ f"{owner}: timers must be Timer objects, not {timer!r}", doc=DOC
94
+ )
95
+ where = f"{owner} timer {timer.event!r}"
96
+ machine = next((m for m in machines.values() if timer.event in m.info.events), None)
97
+ if machine is None:
98
+ known = [e for m in machines.values() for e in m.info.events]
99
+ raise ConfigurationError(
100
+ f"{where}: the state machine has no transition {timer.event!r}",
101
+ hint=f"Transitions: {', '.join(known)}",
102
+ doc=DOC,
103
+ )
104
+ info = machine.info
105
+ value_of = {s.id: s.value if s.value is not None else s.id for s in info.states}
106
+ values = set(value_of.values())
107
+ sources = {value_of[t.source] for t in info.transitions if t.event == timer.event}
108
+ state_since_field = machine.since_field
109
+ if timer.after <= timedelta(0):
110
+ raise ConfigurationError(f"{where}: after must be positive", doc=DOC)
111
+ since = timer.since or state_since_field
112
+ if since is None:
113
+ raise ConfigurationError(
114
+ f"{where}: no since field",
115
+ hint="Set state_since_field on the resource (or since_field on its "
116
+ "Machine: the engine stamps it on every state change) or pass since= a "
117
+ "datetime field.",
118
+ doc=DOC,
119
+ )
120
+ if since not in known_fields:
121
+ raise ConfigurationError(
122
+ f"{where}: since field {since!r} is not part of the read or write schemas",
123
+ doc=DOC,
124
+ )
125
+ states = tuple(timer.states) if timer.states else tuple(sorted(sources, key=str))
126
+ unknown = [s for s in states if s not in values]
127
+ not_sources = [s for s in states if s in values and s not in sources]
128
+ if unknown or not_sources:
129
+ raise ConfigurationError(
130
+ f"{where}: "
131
+ + (f"unknown states {unknown}" if unknown else "")
132
+ + (f"; {timer.event!r} cannot run from {not_sources}" if not_sources else ""),
133
+ hint=f"{timer.event!r} runs from: {sorted(map(str, sources))}",
134
+ doc=DOC,
135
+ )
136
+ schema = transition_schemas.get(timer.event)
137
+ if schema is not None:
138
+ try:
139
+ schema.model_validate(dict(timer.data or {}))
140
+ except Exception as exc:
141
+ raise ConfigurationError(
142
+ f"{where}: data does not match the {schema.__name__} schema: {exc}",
143
+ doc=DOC,
144
+ ) from exc
145
+ elif timer.data:
146
+ raise ConfigurationError(f"{where}: {timer.event!r} takes no input data", doc=DOC)
147
+ out.append(
148
+ TimerDefinition(
149
+ resource=name,
150
+ event=timer.event,
151
+ after=timer.after,
152
+ since=since,
153
+ states=states,
154
+ field=machine.state_field,
155
+ data=dict(timer.data) if timer.data else None,
156
+ description=timer.description,
157
+ )
158
+ )
159
+ return tuple(out)
160
+
161
+
162
+ @dataclass(frozen=True)
163
+ class TimerRun:
164
+ """What one ``TimerJob.run_once`` did."""
165
+
166
+ fired: int = 0
167
+ skipped: int = 0
168
+ failed: int = 0
169
+ due: dict[str, int] = dataclasses.field(default_factory=dict)
170
+
171
+
172
+ class TimerJob:
173
+ """Runs the due timed transitions of every resource (a ``JobRunner`` job).
174
+
175
+ Args:
176
+ manager: The application's manager.
177
+ resources: Only these resources (default: every resource with timers).
178
+ batch: Records handled per timer and run; the rest wait for the next run.
179
+ actor: Who runs the transitions (default ``system_principal("timers")``).
180
+ clock: ``() -> datetime`` (UTC), for tests.
181
+
182
+ Run it with ``single=True`` so one worker fires each deadline. A record
183
+ whose state changed meanwhile is skipped; other failures are logged and
184
+ retried on the next run.
185
+ """
186
+
187
+ def __init__(
188
+ self,
189
+ manager: ResourceManager,
190
+ *,
191
+ resources: Sequence[str] | None = None,
192
+ batch: int = 100,
193
+ actor: Any = None,
194
+ clock: Callable[[], datetime] | None = None,
195
+ ) -> None:
196
+ from resource_engine.authz import system_principal
197
+
198
+ self.manager = manager
199
+ self.resources = resources
200
+ self.batch = batch
201
+ self.actor = actor if actor is not None else system_principal("timers")
202
+ self.clock = clock or (lambda: datetime.now(UTC))
203
+
204
+ def timers(self) -> list[tuple[ResourceDefinition, TimerDefinition]]:
205
+ """Every timer of the registered resources, with its resource."""
206
+ return [
207
+ (d, t)
208
+ for d in self.manager.registry
209
+ if self.resources is None or d.name in self.resources
210
+ for t in d.timers
211
+ ]
212
+
213
+ async def run_once(self) -> TimerRun:
214
+ """Fire the transitions whose timers are due; returns what ran."""
215
+ from resource_engine.application.query import ListQuery
216
+
217
+ now = self.clock()
218
+ fired = skipped = failed = 0
219
+ due: dict[str, int] = {}
220
+ for definition, timer in self.timers():
221
+ condition = {
222
+ "and": [
223
+ {"in": [{"attr": f"resource.{timer.field}"}, list(timer.states)]},
224
+ {"exists": {"attr": f"resource.{timer.since}"}},
225
+ {"le": [{"attr": f"resource.{timer.since}"}, now - timer.after]},
226
+ ]
227
+ }
228
+ page = await self.manager.list(
229
+ definition.name,
230
+ ListQuery(limit=self.batch),
231
+ actor=self.actor,
232
+ _condition=condition,
233
+ _unbounded=True,
234
+ )
235
+ key = f"{definition.name}.{timer.event}"
236
+ due[key] = page.total
237
+ for record in page.items:
238
+ entity_id = getattr(record, definition.id_field)
239
+ try:
240
+ await self.manager.transition(
241
+ definition.name,
242
+ entity_id,
243
+ timer.event,
244
+ dict(timer.data) if timer.data else None,
245
+ actor=self.actor,
246
+ )
247
+ except (TransitionNotAllowed, EntityNotFound):
248
+ skipped += 1 # the record moved on since it was listed
249
+ except Exception as exc:
250
+ from resource_engine.reporting import report_error
251
+
252
+ failed += 1
253
+ await report_error(
254
+ exc,
255
+ where="timer",
256
+ force=True,
257
+ timer=key,
258
+ resource=definition.name,
259
+ entity_id=entity_id,
260
+ )
261
+ else:
262
+ fired += 1
263
+ return TimerRun(fired, skipped, failed, due)
264
+
265
+ async def __call__(self) -> TimerRun:
266
+ """Run once (as a job)."""
267
+ return await self.run_once()
268
+
269
+
270
+ @dataclass(frozen=True)
271
+ class PendingTimer:
272
+ """A timed transition waiting on one record.
273
+
274
+ Attributes:
275
+ due_at: When the worker runs it (``None``: the record has no ``since``
276
+ date yet, or the caller may not read it).
277
+ overdue: Due already; the next ``TimerJob`` run fires it.
278
+ """
279
+
280
+ event: str
281
+ due_at: datetime | None
282
+ since: str
283
+ after: timedelta
284
+ states: tuple[Any, ...]
285
+ description: str | None
286
+ overdue: bool
287
+
288
+
289
+ def _plain(value: Any) -> Any:
290
+ return getattr(value, "value", value)
291
+
292
+
293
+ async def pending_timers(
294
+ manager: ResourceManager,
295
+ resource: str,
296
+ entity_id: Any,
297
+ *,
298
+ actor: Any = None,
299
+ tenant: str | None = None,
300
+ now: datetime | None = None,
301
+ ) -> list[PendingTimer]:
302
+ """The timers waiting on one record now: those whose states include its
303
+ current state. The record is read as ``actor`` (permission, row filter,
304
+ tenant); a ``since`` field hidden from them gives no ``due_at``."""
305
+ from pydantic import BaseModel
306
+
307
+ from resource_engine.authz.fields import hidden_fields
308
+
309
+ definition = manager.registry.get(resource)
310
+ if not definition.timers:
311
+ return []
312
+ record = await manager.get(resource, entity_id, actor=actor, tenant=tenant)
313
+ hidden = hidden_fields(record) if isinstance(record, BaseModel) else frozenset()
314
+ now = now or datetime.now(UTC)
315
+ out = []
316
+ for timer in definition.timers:
317
+ state = _plain(getattr(record, timer.field, None))
318
+ if state not in {_plain(s) for s in timer.states}:
319
+ continue
320
+ since = None if timer.since in hidden else getattr(record, timer.since, None)
321
+ if isinstance(since, datetime) and since.tzinfo is None:
322
+ since = since.replace(tzinfo=UTC)
323
+ due = since + timer.after if isinstance(since, datetime) else None
324
+ out.append(
325
+ PendingTimer(
326
+ event=timer.event,
327
+ due_at=due,
328
+ since=timer.since,
329
+ after=timer.after,
330
+ states=timer.states,
331
+ description=timer.description,
332
+ overdue=due is not None and due <= now,
333
+ )
334
+ )
335
+ out.sort(key=lambda p: (p.due_at is None, p.due_at or now))
336
+ return out
337
+
338
+
339
+ __all__ = [
340
+ "PendingTimer",
341
+ "Timer",
342
+ "TimerDefinition",
343
+ "TimerJob",
344
+ "TimerRun",
345
+ "normalize_timers",
346
+ "pending_timers",
347
+ ]
@@ -0,0 +1,100 @@
1
+ """``ResourceManager.transaction()``: several operations in one unit of work.
2
+
3
+ Operations called inside ``async with manager.transaction():`` join the shared
4
+ unit of work instead of committing their own. Their audit entries and outbox
5
+ events are written in it; their post-commit work (``ctx.on_commit``,
6
+ ``after_commit`` hooks, direct event delivery) runs only once the transaction
7
+ commits. If an operation fails after reaching its unit of work, the transaction
8
+ is *doomed*: it can only roll back (RE-E007), because the failed operation may
9
+ have written part of its changes.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from contextvars import ContextVar
15
+ from dataclasses import dataclass, field
16
+ from typing import TYPE_CHECKING, Any, override
17
+
18
+ from resource_engine.ports.unit_of_work import UnitOfWork
19
+
20
+ if TYPE_CHECKING:
21
+ from resource_engine.application.context import OperationContext
22
+ from resource_engine.ports.unit_of_work import UnitOfWork
23
+
24
+
25
+ @dataclass(eq=False)
26
+ class Transaction:
27
+ """The shared unit of work of ``manager.transaction()``.
28
+
29
+ Attributes:
30
+ uow: The unit of work (repositories, ``outbox()``, ``inbox()``).
31
+ doomed: The first failure of a joined operation, if any.
32
+ """
33
+
34
+ owner: Any
35
+ uow: UnitOfWork
36
+ doomed: BaseException | None = None
37
+ contexts: list[OperationContext] = field(default_factory=list)
38
+ after_commit: list[tuple[OperationContext, str | None]] = field(default_factory=list)
39
+ finished: bool = False
40
+
41
+ @property
42
+ def view(self) -> JoinedUnitOfWork:
43
+ """The unit of work joined operations see, without commit."""
44
+ return joined_view(self.uow)
45
+
46
+
47
+ class JoinedUnitOfWork(UnitOfWork):
48
+ """What a joined operation sees: the shared unit of work, without commit."""
49
+
50
+ def __init__(self, uow: UnitOfWork) -> None:
51
+ self._uow = uow
52
+
53
+ async def __aenter__(self) -> JoinedUnitOfWork:
54
+ return self
55
+
56
+ async def __aexit__(self, *exc: object) -> None:
57
+ return None
58
+
59
+ async def commit(self) -> None:
60
+ """Deferred to the transaction."""
61
+
62
+ async def rollback(self) -> None:
63
+ """Deferred to the transaction (which is doomed by the failure)."""
64
+
65
+ @override
66
+ def repository(self, resource_name: str) -> Any:
67
+ return self._uow.repository(resource_name)
68
+
69
+ def __getattr__(self, name: str) -> Any:
70
+ return getattr(self._uow, name)
71
+
72
+
73
+ #: Optional capabilities a joined view forwards when the shared unit of work has them.
74
+ CAPABILITIES = ("outbox", "inbox", "idempotency")
75
+
76
+ _views: dict[frozenset[str], type[JoinedUnitOfWork]] = {}
77
+
78
+
79
+ def _forward(name: str) -> Any:
80
+ def method(self: JoinedUnitOfWork) -> Any:
81
+ return getattr(self._uow, name)()
82
+
83
+ method.__name__ = name
84
+ return method
85
+
86
+
87
+ def joined_view(uow: UnitOfWork) -> JoinedUnitOfWork:
88
+ """A view with the same capabilities (``outbox()``, ``inbox()``,
89
+ ``idempotency()``) as ``uow``: runtime protocol checks look at the class,
90
+ not at ``__getattr__``, so the methods are defined on it."""
91
+ present = frozenset(name for name in CAPABILITIES if hasattr(uow, name))
92
+ cls = _views.get(present)
93
+ if cls is None:
94
+ name = "Joined" + "".join(n.capitalize() for n in sorted(present)) + "UnitOfWork"
95
+ cls = type(name, (JoinedUnitOfWork,), {n: _forward(n) for n in present})
96
+ _views[present] = cls
97
+ return cls(uow)
98
+
99
+
100
+ current: ContextVar[Transaction | None] = ContextVar("resource_engine_transaction", default=None)
@@ -0,0 +1,239 @@
1
+ """View resources: read-only resources whose records are computed by a query.
2
+
3
+ ```python
4
+ class CustomerBalanceResource(Resource):
5
+ name = "customer_balances"
6
+ model = CustomerBalance
7
+ schemas = {"read": CustomerBalanceRead}
8
+ operations = ["list", "get"]
9
+ id_field = "customer_id"
10
+ view = Aggregate(
11
+ "invoices",
12
+ group_by=["customer_id"],
13
+ values={
14
+ "invoices": Count(),
15
+ "total": Sum("amount"),
16
+ "pending": Sum("amount", where={"status": "pending"}),
17
+ "last_issued": Max("issue_date"),
18
+ },
19
+ )
20
+ ```
21
+
22
+ An ``Aggregate`` is neutral: every storage adapter computes it (SQL as one
23
+ ``GROUP BY`` query, in memory in Python). ``view = True`` declares a custom
24
+ view that the storage adapter defines (a mapped ``select`` in SQLAlchemy, a
25
+ function for ``InMemoryStore``). Either way the resource lists and reads with
26
+ the usual filters, sorting, paging, permissions, tenancy, ``expand``, docs,
27
+ GraphQL and MCP tools, and never writes. See docs/views.md.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import dataclasses
33
+ from collections.abc import Mapping, Sequence
34
+ from dataclasses import dataclass
35
+ from typing import TYPE_CHECKING, Any
36
+
37
+ from resource_engine.errors import ConfigurationError
38
+
39
+ if TYPE_CHECKING:
40
+ from resource_engine.application.registry import ResourceRegistry
41
+
42
+ DOC = "docs/views.md"
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class Measure:
47
+ """One computed value of an aggregate row.
48
+
49
+ Args:
50
+ field: Source field (``None`` for ``Count``).
51
+ where: Only source records matching these values count:
52
+ ``{"status": "pending"}`` or ``{"status": ["pending", "approved"]}``.
53
+ """
54
+
55
+ field: str | None = None
56
+ where: Mapping[str, Any] | None = None
57
+ kind: str = dataclasses.field(default="", init=False)
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class Count(Measure):
62
+ """Number of source records (in the group, matching ``where``)."""
63
+
64
+ kind: str = dataclasses.field(default="count", init=False)
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class Sum(Measure):
69
+ """Sum of ``field``; 0 when no record matches."""
70
+
71
+ kind: str = dataclasses.field(default="sum", init=False)
72
+
73
+
74
+ @dataclass(frozen=True)
75
+ class Min(Measure):
76
+ """Smallest ``field``; null when no record matches."""
77
+
78
+ kind: str = dataclasses.field(default="min", init=False)
79
+
80
+
81
+ @dataclass(frozen=True)
82
+ class Max(Measure):
83
+ """Largest ``field``; null when no record matches."""
84
+
85
+ kind: str = dataclasses.field(default="max", init=False)
86
+
87
+
88
+ @dataclass(frozen=True)
89
+ class Avg(Measure):
90
+ """Average of ``field``; null when no record matches."""
91
+
92
+ kind: str = dataclasses.field(default="avg", init=False)
93
+
94
+
95
+ @dataclass(frozen=True)
96
+ class Aggregate:
97
+ """Rows grouped from a source resource.
98
+
99
+ Args:
100
+ source: The resource whose records are grouped.
101
+ group_by: Source fields of the group: one row per distinct value.
102
+ Records without a value for the view's id field are left out.
103
+ values: The computed fields, by name: ``Count()``, ``Sum("amount")``...
104
+ where: Only source records matching these values are grouped.
105
+ """
106
+
107
+ source: str
108
+ group_by: Sequence[str]
109
+ values: Mapping[str, Measure]
110
+ where: Mapping[str, Any] | None = None
111
+
112
+
113
+ def matches_where(record: Any, where: Mapping[str, Any] | None) -> bool:
114
+ for name, expected in (where or {}).items():
115
+ value = getattr(record, name, None)
116
+ if isinstance(expected, list | tuple | set | frozenset):
117
+ if value not in expected:
118
+ return False
119
+ elif value != expected:
120
+ return False
121
+ return True
122
+
123
+
124
+ def compute(view: Aggregate, records: Sequence[Any], key: str) -> list[dict[str, Any]]:
125
+ """The aggregate rows of ``records`` (the in-memory implementation);
126
+ ``key`` is the view's id field."""
127
+ groups: dict[tuple[Any, ...], list[Any]] = {}
128
+ for record in records:
129
+ if not matches_where(record, view.where):
130
+ continue
131
+ if getattr(record, key, None) is None:
132
+ continue
133
+ group = tuple(getattr(record, f, None) for f in view.group_by)
134
+ groups.setdefault(group, []).append(record)
135
+ rows = []
136
+ for group, members in groups.items():
137
+ row = dict(zip(view.group_by, group, strict=True))
138
+ for name, measure in view.values.items():
139
+ row[name] = _measure(measure, members)
140
+ rows.append(row)
141
+ return rows
142
+
143
+
144
+ def _measure(measure: Measure, members: Sequence[Any]) -> Any:
145
+ chosen = [m for m in members if matches_where(m, measure.where)]
146
+ if measure.kind == "count":
147
+ return len(chosen)
148
+ values: list[Any] = [
149
+ v for m in chosen if (v := getattr(m, measure.field or "", None)) is not None
150
+ ]
151
+ if measure.kind == "sum":
152
+ return sum(values, start=type(values[0])(0)) if values else 0
153
+ if not values:
154
+ return None
155
+ if measure.kind == "min":
156
+ return min(values)
157
+ if measure.kind == "max":
158
+ return max(values)
159
+ return sum(values) / len(values)
160
+
161
+
162
+ def check_view(owner: str, definition_fields: set[str], id_field: str, view: Any) -> None:
163
+ """Shape of a view declaration (its source is checked with the registry)."""
164
+ if view is True:
165
+ return
166
+ if not isinstance(view, Aggregate):
167
+ raise ConfigurationError(
168
+ f"{owner}: view must be an Aggregate(...) or True (a custom view)", doc=DOC
169
+ )
170
+ if not view.group_by:
171
+ raise ConfigurationError(f"{owner}: the aggregate needs group_by fields", doc=DOC)
172
+ for name, measure in view.values.items():
173
+ if not isinstance(measure, Measure) or not measure.kind:
174
+ raise ConfigurationError(
175
+ f"{owner}: value {name!r} must be Count(), Sum(...), Min(...), Max(...) or "
176
+ "Avg(...)",
177
+ doc=DOC,
178
+ )
179
+ if measure.kind != "count" and not measure.field:
180
+ raise ConfigurationError(f"{owner}: value {name!r} needs a source field", doc=DOC)
181
+ produced = [*view.group_by, *view.values]
182
+ if set(produced) != definition_fields:
183
+ raise ConfigurationError(
184
+ f"{owner}: the read schema fields {sorted(definition_fields)} differ from the "
185
+ f"aggregate's {sorted(produced)}",
186
+ hint="Declare one read field per group_by field and value.",
187
+ doc=DOC,
188
+ )
189
+ if id_field not in view.group_by:
190
+ raise ConfigurationError(
191
+ f"{owner}: the id field {id_field!r} must be one of group_by {list(view.group_by)}",
192
+ hint="Set id_field to the group's key (customer_id for totals per customer).",
193
+ doc=DOC,
194
+ )
195
+
196
+
197
+ def check_views(registry: ResourceRegistry) -> None:
198
+ """Every aggregate's source and fields exist (run with the registry complete)."""
199
+ for d in registry:
200
+ view = d.view
201
+ if not isinstance(view, Aggregate):
202
+ continue
203
+ if view.source not in registry:
204
+ raise ConfigurationError(
205
+ f"{d.name}: the view's source {view.source!r} is not registered", doc=DOC
206
+ )
207
+ source = registry.get(view.source)
208
+ read = source.schemas.get("read")
209
+ known = set(read.model_fields) if read is not None else set()
210
+ used = {
211
+ *view.group_by,
212
+ *(view.where or {}),
213
+ *(m.field for m in view.values.values() if m.field),
214
+ *(f for m in view.values.values() for f in (m.where or {})),
215
+ }
216
+ unknown = sorted(used - known)
217
+ if unknown:
218
+ raise ConfigurationError(
219
+ f"{d.name}: fields {unknown} are not in {view.source}'s read schema", doc=DOC
220
+ )
221
+ if d.tenant_field and d.tenant_field not in view.group_by:
222
+ raise ConfigurationError(
223
+ f"{d.name}: the tenant field {d.tenant_field!r} must be in group_by",
224
+ hint="Each row then belongs to one tenant, like the records it sums up.",
225
+ doc=DOC,
226
+ )
227
+
228
+
229
+ __all__ = [
230
+ "Aggregate",
231
+ "Avg",
232
+ "Count",
233
+ "Max",
234
+ "Measure",
235
+ "Min",
236
+ "Sum",
237
+ "check_views",
238
+ "compute",
239
+ ]