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,1987 @@
1
+ """The ResourceManager executes operations following the lifecycle contract.
2
+
3
+ The contract (see docs/lifecycle.md) for a writing operation is:
4
+
5
+ 1. resolve resource and operation
6
+ 2. authorization without the record (``Authorizer.check``; no-op without an authorizer)
7
+ 3. ``before_validate`` → validation → ``after_validate``
8
+ 4. open the unit of work
9
+ 5. load the entity (update / delete / transition / instance action), then
10
+ authorization on it (404 when invisible); ``list`` gets the row filter
11
+ 6. ``before_<op>``
12
+ 7. mutate: build+add / apply+update / delete / fire transition / execute action
13
+ 8. ``after_<op>`` (still transactional)
14
+ 9. build the result, stage events (``EventDelivery.before_commit``: outbox), commit
15
+ 10. ``after_commit`` hooks, then ``EventDelivery.after_commit`` (direct publishing)
16
+
17
+ Any exception before step 9 rolls the transaction back. Failures after commit are
18
+ logged and never undo a committed operation.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import builtins
24
+ import contextlib
25
+ import dataclasses
26
+ import inspect
27
+ import logging
28
+ from collections.abc import AsyncIterator, Collection, Mapping, Sequence
29
+ from contextlib import asynccontextmanager
30
+ from datetime import timedelta
31
+ from typing import TYPE_CHECKING, Any
32
+
33
+ from pydantic import BaseModel, ValidationError
34
+
35
+ from resource_engine.application.context import OperationContext
36
+ from resource_engine.application.events import (
37
+ ActionExecuted,
38
+ ResourceCreated,
39
+ ResourceDeleted,
40
+ ResourceUpdated,
41
+ TransitionExecuted,
42
+ )
43
+ from resource_engine.application.hooks import HookPoint
44
+ from resource_engine.application.idempotency import (
45
+ DEFAULT_TTL,
46
+ idempotent,
47
+ pending_for,
48
+ store_result,
49
+ )
50
+ from resource_engine.application.query import ListQuery, Page
51
+ from resource_engine.application.registry import ResourceRegistry
52
+ from resource_engine.application.relations import (
53
+ ReferenceDefinition,
54
+ related_filter_names,
55
+ split_filters,
56
+ )
57
+ from resource_engine.application.resource import Resource, ResourceDefinition
58
+ from resource_engine.application.transaction import Transaction
59
+ from resource_engine.application.transaction import current as current_transaction
60
+ from resource_engine.audit.history import StateChange
61
+ from resource_engine.errors import (
62
+ ActionNotFound,
63
+ AuthenticationFailed,
64
+ ConditionNotSupported,
65
+ ConfigurationError,
66
+ EntityNotFound,
67
+ FieldNotReadable,
68
+ FieldNotWritable,
69
+ InvalidQuery,
70
+ OperationNotEnabled,
71
+ PermissionDenied,
72
+ QueryNotSupported,
73
+ ReferenceInUse,
74
+ ReferenceNotFound,
75
+ TenantMismatch,
76
+ TenantRequired,
77
+ TransactionDoomed,
78
+ UnknownTransition,
79
+ ValidationFailed,
80
+ VersionConflict,
81
+ VersioningNotSupported,
82
+ VersionRequired,
83
+ )
84
+ from resource_engine.logs import log_context, update_log_context
85
+ from resource_engine.messaging.delivery import AfterCommitDelivery, EventDelivery
86
+ from resource_engine.ports.audit import AuditSink
87
+ from resource_engine.ports.authz import Authorizer
88
+ from resource_engine.ports.cache import Cache
89
+ from resource_engine.ports.event_publisher import EventPublisher, NullEventPublisher
90
+ from resource_engine.ports.observability import OperationObserver
91
+ from resource_engine.ports.ratelimit import RateLimiter
92
+ from resource_engine.ports.storage import BlobStore
93
+ from resource_engine.ports.unit_of_work import UnitOfWork, UnitOfWorkFactory
94
+ from resource_engine.reporting import report_error
95
+ from resource_engine.tracing import get_tracer, traced
96
+
97
+ if TYPE_CHECKING:
98
+ from resource_engine.documents.manager import DocumentManager
99
+ from resource_engine.generation import DocumentGenerator
100
+
101
+ #: Related records a filter like ``customer.country`` may match (docs/relationships.md).
102
+ MAX_RELATED_MATCHES = 1000
103
+ #: Records an inline reverse expansion embeds by default (``expand=["invoices"]``).
104
+ EXPAND_PAGE_SIZE = 10
105
+ #: Levels of a nested expansion (``invoices.customer_record`` is two).
106
+ MAX_EXPAND_DEPTH = 3
107
+
108
+ logger = logging.getLogger("resource_engine")
109
+
110
+ type ResourceRef = str | type[Resource]
111
+
112
+
113
+ class ResourceManager:
114
+ """Runs CRUD operations, transitions and actions of registered resources.
115
+
116
+ It knows nothing about HTTP or SQL: entry adapters call it, and persistence is
117
+ reached through the ``UnitOfWork`` port.
118
+ """
119
+
120
+ def __init__(
121
+ self,
122
+ registry: ResourceRegistry,
123
+ uow_factory: UnitOfWorkFactory,
124
+ *,
125
+ event_publisher: EventPublisher | None = None,
126
+ event_delivery: EventDelivery | None = None,
127
+ services: Mapping[str, Any] | None = None,
128
+ blob_store: BlobStore | None = None,
129
+ documents_resource: str = "documents",
130
+ authorizer: Authorizer | None = None,
131
+ audit: AuditSink | bool | None = None,
132
+ audit_failures: bool = False,
133
+ idempotency_ttl: timedelta = DEFAULT_TTL,
134
+ observers: Sequence[OperationObserver] = (),
135
+ rate_limiter: RateLimiter | None = None,
136
+ cache: Cache | None = None,
137
+ generator: DocumentGenerator | None = None,
138
+ ) -> None:
139
+ self.registry = registry
140
+ from resource_engine.generation import check_printouts
141
+
142
+ check_printouts(registry, generator)
143
+ #: The ``DocumentGenerator`` behind ``Resource.printouts`` (docs/documents.md).
144
+ self.generator = generator
145
+ from resource_engine.cache import RecordCache
146
+
147
+ #: Records read by id, for resources with ``cache_ttl`` (docs/caching.md).
148
+ self.records = RecordCache(cache) if cache is not None else None
149
+ #: ``RateLimiter`` whose ``actions`` limits apply to every operation (RE-E710).
150
+ self.rate_limiter = rate_limiter
151
+ self.observers: list[OperationObserver] = list(observers)
152
+ self.uow_factory = uow_factory
153
+ if event_publisher is not None and event_delivery is not None:
154
+ raise ValueError("Pass either event_publisher or event_delivery, not both")
155
+ self.delivery: EventDelivery = event_delivery or AfterCommitDelivery(
156
+ event_publisher or NullEventPublisher()
157
+ )
158
+ self.services = dict(services or {})
159
+ self.idempotency_ttl = idempotency_ttl
160
+ self.authorizer = authorizer
161
+ if authorizer is not None:
162
+ bind = getattr(authorizer, "bind", None)
163
+ if bind is not None:
164
+ bind(registry)
165
+ self.services.setdefault("authz", authorizer)
166
+ if audit is True:
167
+ from resource_engine.audit.sink import RepositoryAuditSink
168
+
169
+ audit = RepositoryAuditSink(uow_factory)
170
+ self.audit: AuditSink | None = audit or None
171
+ #: Also audit operations that failed inside their transaction
172
+ #: (``outcome="failed"``, with the error code), not only refusals.
173
+ self.audit_failures = audit_failures
174
+ target = getattr(self.audit, "resource", None)
175
+ if target is not None and target not in {d.name for d in registry}:
176
+ raise ConfigurationError(
177
+ f"The audit sink writes to {target!r}, which is not registered",
178
+ hint="Call registry.register_audit() (and map its table with SQLAlchemy).",
179
+ doc="docs/audit.md#setup",
180
+ )
181
+ from resource_engine.application.relations import check_references, reverse_relations
182
+ from resource_engine.application.views import check_views
183
+
184
+ check_views(registry)
185
+ #: References pointing to each resource, by target name (docs/relationships.md).
186
+ self.dependents = check_references(registry)
187
+ #: Reverse relations of each resource, by target and related name.
188
+ self.reverse = reverse_relations(registry, self.dependents)
189
+ self.documents: DocumentManager | None = None
190
+ if blob_store is not None:
191
+ from resource_engine.documents.manager import DocumentManager
192
+
193
+ self.documents = DocumentManager(self, blob_store, resource=documents_resource)
194
+ else:
195
+ with_slots = [d.name for d in registry if d.document_slots]
196
+ if with_slots:
197
+ raise ConfigurationError(
198
+ f"Resources {with_slots} declare document slots but no blob store is set",
199
+ hint="Pass blob_store=... (S3BlobStore, InMemoryBlobStore) and call "
200
+ "registry.register_documents().",
201
+ doc="docs/documents.md#setup",
202
+ )
203
+ from resource_engine.exports import ExportJobs
204
+
205
+ #: Background exports (docs/exports.md), when a blob store can hold the files.
206
+ self.exports: ExportJobs | None = (
207
+ ExportJobs(self, blob_store) if blob_store is not None else None
208
+ )
209
+
210
+ # ------------------------------------------------------------------ helpers
211
+
212
+ def _context(
213
+ self,
214
+ definition: ResourceDefinition,
215
+ operation: str,
216
+ *,
217
+ tenant: str | None = None,
218
+ expected_version: int | None = None,
219
+ **kw: Any,
220
+ ) -> OperationContext:
221
+ ctx = OperationContext(
222
+ resource=definition, operation=operation, services=self.services, **kw
223
+ )
224
+ ctx.extras["requested_tenant"] = tenant
225
+ ctx.extras["expected_version"] = expected_version
226
+ pending_for(ctx) # bind an idempotency key to this operation, if one was sent
227
+ context = log_context()
228
+ # the first context of the running operation (traced() opened its log context)
229
+ if context.get("operation") is not None and context.get("correlation_id") is None:
230
+ update_log_context(
231
+ correlation_id=ctx.correlation_id,
232
+ entity_id=None if ctx.entity_id is None else str(ctx.entity_id),
233
+ action=_action_of(ctx) if ctx.transition or ctx.action else None,
234
+ )
235
+ span = get_tracer().current()
236
+ span.set_attribute("resource_engine.correlation_id", ctx.correlation_id)
237
+ if ctx.entity_id is not None:
238
+ span.set_attribute("resource_engine.entity_id", str(ctx.entity_id))
239
+ if ctx.transition or ctx.action:
240
+ span.set_attribute("resource_engine.action", _action_of(ctx))
241
+ if self.documents is not None:
242
+ from resource_engine.documents.manager import ContextDocuments
243
+
244
+ ctx.documents = ContextDocuments(self.documents, ctx)
245
+ return ctx
246
+
247
+ def _require(self, definition: ResourceDefinition, operation: str) -> None:
248
+ if not definition.enabled(operation):
249
+ raise OperationNotEnabled(
250
+ f"Operation {operation!r} is not enabled for resource {definition.name!r}",
251
+ hint=f"Enabled operations: {', '.join(definition.operations) or '(none)'}. "
252
+ "Add it to `operations` on the resource if it should exist.",
253
+ )
254
+
255
+ async def _validate(
256
+ self, ctx: OperationContext, schema: type[BaseModel] | None, qualifier: str | None = None
257
+ ) -> None:
258
+ hooks = ctx.resource.dispatcher
259
+ await hooks.run(HookPoint.BEFORE_VALIDATE, ctx, None)
260
+ if schema is None:
261
+ ctx.data = None
262
+ elif isinstance(ctx.raw_input, schema):
263
+ ctx.data = ctx.raw_input
264
+ else:
265
+ raw = ctx.raw_input
266
+ if isinstance(raw, BaseModel):
267
+ raw = raw.model_dump(exclude_unset=True)
268
+ try:
269
+ ctx.data = schema.model_validate(raw if raw is not None else {})
270
+ except ValidationError as exc:
271
+ raise ValidationFailed(
272
+ f"Invalid input for {ctx.resource.name}.{qualifier or ctx.operation}",
273
+ hint="Check `details` for the offending fields.",
274
+ details=exc.errors(include_url=False, include_context=False),
275
+ ) from exc
276
+ await hooks.run(HookPoint.AFTER_VALIDATE, ctx, None)
277
+
278
+ async def _load(self, ctx: OperationContext) -> Any:
279
+ records = self.records
280
+ cached = records is not None and (
281
+ ctx.resource.cache_ttl is not None
282
+ and ctx.operation == "get" # reads only; writes load the stored record
283
+ and self._joined() is None
284
+ )
285
+ entity = await records.load(ctx.resource, ctx.entity_id) if records and cached else None
286
+ if entity is None:
287
+ entity = await ctx.repository().get(ctx.entity_id)
288
+ if records and cached and entity is not None:
289
+ await records.store(ctx.resource, entity)
290
+ if entity is None:
291
+ raise EntityNotFound(
292
+ f"{ctx.resource.name} {ctx.entity_id!r} does not exist",
293
+ details={"resource": ctx.resource.name, "id": ctx.entity_id},
294
+ )
295
+ await self._check_tenant(ctx, entity)
296
+ ctx.entity = entity
297
+ return entity
298
+
299
+ # ------------------------------------------------------------------ tenancy
300
+
301
+ async def _ensure_tenant(self, ctx: OperationContext) -> None:
302
+ """Resolve the caller's tenant scope once per operation (tenant-scoped
303
+ resources only): RE-E708 without a tenant, RE-E709 for another one."""
304
+ if ctx.resource.tenant_field is None or ctx._tenant_scope is not None:
305
+ return
306
+ if ctx.actor is None and self.authorizer is not None:
307
+ await self._refuse_anonymous(ctx, ctx.operation)
308
+ from resource_engine.tenancy import resolve_tenant
309
+
310
+ try:
311
+ scope = await resolve_tenant(
312
+ ctx.actor, self.authorizer, ctx.extras.get("requested_tenant")
313
+ )
314
+ except (TenantRequired, TenantMismatch) as error:
315
+ await self._audit_denied(ctx, ctx.operation, error)
316
+ raise
317
+ ctx._tenant_scope = scope
318
+ ctx.tenant = scope.tenant
319
+
320
+ async def _check_tenant(self, ctx: OperationContext, entity: Any) -> None:
321
+ """Records of other tenants do not exist for the caller (404)."""
322
+ field_name = ctx.resource.tenant_field
323
+ if field_name is None:
324
+ return
325
+ await self._ensure_tenant(ctx)
326
+ if ctx.tenant is not None and getattr(entity, field_name, None) != ctx.tenant:
327
+ await self._audit_denied(
328
+ ctx,
329
+ ctx.operation,
330
+ PermissionDenied("other tenant", details={"reason": "other tenant"}),
331
+ )
332
+ raise EntityNotFound(
333
+ f"{ctx.resource.name} {ctx.entity_id!r} does not exist",
334
+ details={"resource": ctx.resource.name, "id": ctx.entity_id},
335
+ )
336
+
337
+ async def _stamp_tenant(self, ctx: OperationContext, entity: Any) -> None:
338
+ """Create: the new record belongs to the scope's tenant."""
339
+ try:
340
+ self._stamp(ctx, entity)
341
+ except (TenantRequired, TenantMismatch) as error:
342
+ await self._audit_denied(ctx, "create", error)
343
+ raise
344
+
345
+ def _stamp(self, ctx: OperationContext, entity: Any) -> None:
346
+ field_name = ctx.resource.tenant_field
347
+ if field_name is None:
348
+ return
349
+ sent = getattr(entity, field_name, None)
350
+ scope = ctx._tenant_scope
351
+ target = ctx.tenant or sent
352
+ if sent is not None and target is not None and sent != target:
353
+ raise TenantMismatch(
354
+ f"Not allowed to create {ctx.resource.name} for tenant {sent!r}",
355
+ details={"reason": "other tenant", "tenant": sent},
356
+ doc="docs/tenancy.md",
357
+ )
358
+ if target is None:
359
+ raise TenantRequired(
360
+ f"Creating {ctx.resource.name} needs a tenant",
361
+ hint=f"Cross-tenant callers pass tenant=... (or set {field_name!r}).",
362
+ details={"reason": "no tenant", "cross_tenant": bool(scope and scope.cross)},
363
+ doc="docs/tenancy.md",
364
+ )
365
+ setattr(entity, field_name, target)
366
+ ctx.tenant = target
367
+
368
+ def _tenant_query(self, ctx: OperationContext, query: ListQuery) -> ListQuery | None:
369
+ """``list``: only the scope's tenant (``None`` when the client asked for
370
+ another one)."""
371
+ field_name = ctx.resource.tenant_field
372
+ if field_name is None or ctx.tenant is None:
373
+ return query
374
+ asked = query.filters.get(field_name)
375
+ if asked is not None and asked != ctx.tenant:
376
+ return None
377
+ return dataclasses.replace(query, filters={**query.filters, field_name: ctx.tenant})
378
+
379
+ def _id_of(self, ctx: OperationContext, entity: Any) -> Any:
380
+ return getattr(entity, ctx.resource.id_field, None)
381
+
382
+ # ------------------------------------------------------------- authorization
383
+
384
+ async def _gate(
385
+ self, ctx: OperationContext, action: str, *, resource: Any = ..., input: Any = ...
386
+ ) -> None:
387
+ """Step 2 (``resource`` unknown) or 5b (record known): raise when denied.
388
+ Tenant-scoped resources resolve the caller's tenant first."""
389
+ if resource is ... and self.rate_limiter is not None:
390
+ await self.rate_limiter.action(ctx.actor, f"{ctx.resource.name}:{action}")
391
+ await self._ensure_tenant(ctx)
392
+ if self.authorizer is None:
393
+ return
394
+ decision = await self.authorizer.check(
395
+ ctx.actor,
396
+ f"{ctx.resource.name}:{action}",
397
+ resource=resource,
398
+ input=input,
399
+ context={"operation": ctx.operation},
400
+ )
401
+ ctx.decision = decision
402
+ if decision.allowed is False or (decision.allowed is None and resource is not ...):
403
+ if ctx.actor is None:
404
+ await self._refuse_anonymous(ctx, action)
405
+ logger.info(
406
+ "denied %s:%s to %s: %s",
407
+ ctx.resource.name,
408
+ action,
409
+ getattr(ctx.actor, "id", None),
410
+ decision.reason,
411
+ )
412
+ error = PermissionDenied(
413
+ f"Not allowed: {ctx.resource.name}:{action}",
414
+ hint="Ask an administrator for a role or policy that grants it.",
415
+ details={"action": f"{ctx.resource.name}:{action}", "reason": decision.reason},
416
+ )
417
+ await self._audit_denied(ctx, action, error)
418
+ raise error
419
+
420
+ async def _refuse_anonymous(self, ctx: OperationContext, action: str) -> None:
421
+ """Nobody signed in, where permissions apply: RE-E701 (401), the same
422
+ answer on every resource and interface, before tenancy or policies."""
423
+ error = AuthenticationFailed(
424
+ f"Sign in to use {ctx.resource.name}",
425
+ reason="missing",
426
+ hint="Send the caller's credentials (a bearer token or an API key).",
427
+ )
428
+ await self._audit_denied(ctx, action, error)
429
+ raise error
430
+
431
+ async def _gate_record(
432
+ self, ctx: OperationContext, action: str, entity: Any, *, input: Any = ...
433
+ ) -> None:
434
+ """Step 5b: the record must be visible (else 404) and the action allowed."""
435
+ if self.authorizer is None:
436
+ return
437
+ if ctx.resource.enabled("get"):
438
+ visible = await self.authorizer.check(
439
+ ctx.actor, f"{ctx.resource.name}:get", resource=entity
440
+ )
441
+ if visible.allowed is not True:
442
+ error = EntityNotFound(
443
+ f"{ctx.resource.name} {ctx.entity_id!r} does not exist",
444
+ details={"resource": ctx.resource.name, "id": ctx.entity_id},
445
+ )
446
+ await self._audit_denied(
447
+ ctx,
448
+ action,
449
+ PermissionDenied("record not visible", details={"reason": "not visible"}),
450
+ )
451
+ raise error
452
+ if action != "get":
453
+ await self._gate(ctx, action, resource=entity, input=input)
454
+
455
+ async def _scoped(self, ctx: OperationContext, query: ListQuery) -> ListQuery | None:
456
+ """Row-level filter for ``list``; ``None`` when nothing is visible."""
457
+ if self.authorizer is None:
458
+ return query
459
+ scope = await self.authorizer.scope(ctx.actor, f"{ctx.resource.name}:list")
460
+ if scope is True:
461
+ return query
462
+ if scope is False:
463
+ return None
464
+ from resource_engine.authz.conditions import conjunction
465
+
466
+ if not getattr(ctx.repository(), "supports_conditions", False):
467
+ raise ConditionNotSupported(
468
+ f"The repository of {ctx.resource.name!r} cannot filter rows by policy",
469
+ hint="Use a repository with supports_conditions (in-memory, SQLAlchemy) "
470
+ "or grant list without conditions.",
471
+ )
472
+ return dataclasses.replace(query, condition=conjunction(query.condition, scope))
473
+
474
+ async def can(
475
+ self,
476
+ actor: Any,
477
+ resource: ResourceRef,
478
+ action: str,
479
+ entity_id: Any = None,
480
+ *,
481
+ tenant: str | None = None,
482
+ ) -> bool:
483
+ """Whether ``actor`` may perform ``action`` (``"update"``,
484
+ ``"transition:approve"``...), on ``entity_id`` if given. Without an
485
+ authorizer only tenant scoping applies."""
486
+ definition = self.registry.get(resource)
487
+ name = f"{definition.name}:{action}"
488
+ ctx = self._context(definition, "get", actor=actor, entity_id=entity_id, tenant=tenant)
489
+ try:
490
+ await self._ensure_tenant(ctx)
491
+ except (TenantRequired, TenantMismatch):
492
+ return False
493
+ if entity_id is None:
494
+ if self.authorizer is None:
495
+ return True
496
+ return (await self.authorizer.check(actor, name)).allowed is not False
497
+ async with self._reading(ctx) as uow:
498
+ entity = await uow.repository(definition.name).get(entity_id)
499
+ if entity is None:
500
+ return False
501
+ field_name = definition.tenant_field
502
+ if (
503
+ field_name
504
+ and ctx.tenant is not None
505
+ and getattr(entity, field_name, None) != ctx.tenant
506
+ ):
507
+ return False
508
+ if self.authorizer is None:
509
+ return True
510
+ return (await self.authorizer.check(actor, name, resource=entity)).allowed is True
511
+
512
+ # -------------------------------------------------------------- versions
513
+
514
+ def _versioned_repository(self, ctx: OperationContext) -> Any:
515
+ repository = ctx.repository()
516
+ if not getattr(repository, "supports_versions", False):
517
+ raise VersioningNotSupported(
518
+ f"The repository of {ctx.resource.name!r} cannot check versions",
519
+ hint="Use a repository with supports_versions (in-memory, SQLAlchemy), "
520
+ "or remove version_field: remote APIs own their concurrency.",
521
+ doc="docs/concurrency.md",
522
+ )
523
+ return repository
524
+
525
+ async def _check_version(self, ctx: OperationContext, entity: Any) -> None:
526
+ """Steps 5/5b: the client's version (``expected_version=`` or the version
527
+ field in the input) must be the loaded one."""
528
+ version_field = ctx.resource.version_field
529
+ if version_field is None:
530
+ return
531
+ self._versioned_repository(ctx)
532
+ expected = ctx.extras.get("expected_version")
533
+ data = ctx.data
534
+ if isinstance(data, BaseModel) and version_field in data.model_fields_set:
535
+ sent = getattr(data, version_field)
536
+ data.model_fields_set.discard(version_field) # not an input value
537
+ if expected is None:
538
+ expected = sent
539
+ current = getattr(entity, version_field, None)
540
+ ctx.extras["loaded_version"] = current
541
+ action = ctx.operation if ctx.operation in ("update", "delete") else _action_of(ctx)
542
+ if expected is None:
543
+ if ctx.resource.require_version:
544
+ error = VersionRequired(
545
+ f"{ctx.resource.name} {ctx.entity_id!r}: send the version you read",
546
+ hint="Send If-Match with the ETag of the record "
547
+ "(or expected_version=), see docs/concurrency.md.",
548
+ details={"resource": ctx.resource.name, "id": ctx.entity_id},
549
+ )
550
+ await self._audit_denied(ctx, action, error)
551
+ raise error
552
+ return
553
+ if expected != current:
554
+ conflict = _conflict(ctx, expected, current)
555
+ await self._audit_denied(ctx, action, conflict)
556
+ raise conflict
557
+
558
+ async def _write(self, ctx: OperationContext, entity: Any) -> Any:
559
+ """``Repository.update``, compare-and-set on versioned resources."""
560
+ if ctx.resource.version_field is None:
561
+ return await ctx.repository().update(entity)
562
+ repository = self._versioned_repository(ctx)
563
+ loaded = ctx.extras.get("loaded_version")
564
+ try:
565
+ return await repository.update(entity, expected_version=loaded)
566
+ except VersionConflict as error:
567
+ await self._audit_denied(ctx, _action_of(ctx), error)
568
+ raise
569
+
570
+ async def _remove(self, ctx: OperationContext, entity: Any) -> None:
571
+ if ctx.resource.version_field is None:
572
+ await ctx.repository().delete(entity)
573
+ return
574
+ repository = self._versioned_repository(ctx)
575
+ try:
576
+ await repository.delete(entity, expected_version=ctx.extras.get("loaded_version"))
577
+ except VersionConflict as error:
578
+ await self._audit_denied(ctx, "delete", error)
579
+ raise
580
+
581
+ # -------------------------------------------------------------------- audit
582
+
583
+ def _audited(self, ctx: OperationContext) -> bool:
584
+ return self.audit is not None and ctx.resource.audited
585
+
586
+ async def _actor_roles(self, actor: Any) -> list[str]:
587
+ from resource_engine.authz.base import SystemPrincipal
588
+ from resource_engine.ports.identity import Principal
589
+
590
+ if isinstance(actor, SystemPrincipal) or not isinstance(actor, Principal):
591
+ return []
592
+ roles_of = getattr(self.authorizer, "roles_of", None)
593
+ try:
594
+ return sorted(await roles_of(actor)) if roles_of else sorted(actor.roles)
595
+ except Exception: # pragma: no cover - roles are informative here
596
+ logger.exception("Could not resolve roles of %s for the audit trail", actor.id)
597
+ return sorted(actor.roles)
598
+
599
+ async def _before_commit(self, ctx: OperationContext, uow: UnitOfWork) -> None:
600
+ """Step 9, before commit: the idempotency record and the audit entry (same
601
+ transaction), then events."""
602
+ await store_result(self, ctx, uow)
603
+ if self._audited(ctx):
604
+ from resource_engine.audit.recorder import entry_for
605
+
606
+ entry = entry_for(ctx, roles=await self._actor_roles(ctx.actor))
607
+ await self.audit.record([entry], uow=uow) # type: ignore[union-attr]
608
+ await self.delivery.before_commit(ctx, uow)
609
+
610
+ async def _audit_alone(self, ctx: OperationContext, **kw: Any) -> None:
611
+ """Entries outside the operation's transaction (denials, reads): best
612
+ effort, never changes the operation's outcome."""
613
+ if not self._audited(ctx):
614
+ return
615
+ from resource_engine.audit.recorder import entry_for
616
+
617
+ try:
618
+ entry = entry_for(ctx, roles=await self._actor_roles(ctx.actor), **kw)
619
+ await self.audit.record([entry]) # type: ignore[union-attr]
620
+ except Exception:
621
+ logger.exception(
622
+ "Writing the audit entry failed for %s (correlation_id=%s)",
623
+ ctx.resource.name,
624
+ ctx.correlation_id,
625
+ )
626
+
627
+ async def audit_event(
628
+ self,
629
+ actor: Any,
630
+ action: str,
631
+ outcome: str = "ok",
632
+ *,
633
+ resource: str = "explorer",
634
+ entity_id: Any = None,
635
+ tenant: str | None = None,
636
+ details: Mapping[str, Any] | None = None,
637
+ uow: Any = None,
638
+ ) -> None:
639
+ """An audit entry for something that is not a resource operation (the
640
+ explorer's streams, job runs, events published by hand). With ``uow``
641
+ it is written in that transaction; otherwise on its own, best effort."""
642
+ if self.audit is None:
643
+ return
644
+ from resource_engine.audit.model import AuditEntry
645
+ from resource_engine.audit.recorder import actor_id, jsonable
646
+ from resource_engine.logs import log_context
647
+
648
+ context = log_context()
649
+ entry = AuditEntry(
650
+ resource=resource,
651
+ operation=action.split(":", 1)[0],
652
+ action=action,
653
+ outcome=outcome,
654
+ actor=actor_id(actor) if not isinstance(actor, str) else actor,
655
+ actor_roles=await self._actor_roles(actor),
656
+ entity_id=None if entity_id is None else str(entity_id),
657
+ tenant=tenant if tenant is not None else getattr(actor, "tenant", None),
658
+ details={k: jsonable(v) for k, v in (details or {}).items()},
659
+ correlation_id=context.get("correlation_id") or context.get("request_id"),
660
+ )
661
+ if uow is not None:
662
+ await self.audit.record([entry], uow=uow)
663
+ return
664
+ try:
665
+ await self.audit.record([entry])
666
+ except Exception:
667
+ logger.exception("Writing the audit entry for %s failed", action)
668
+
669
+ async def _audit_failed(self, ctx: OperationContext, error: BaseException) -> None:
670
+ """An operation failed after it started writing (``audit_failures``)."""
671
+ if not self.audit_failures or ctx.extras.get("audited_denial"):
672
+ return
673
+ if not isinstance(error, Exception):
674
+ return # cancellation, interpreter exit
675
+ from resource_engine.logs import error_type
676
+
677
+ await self._audit_alone(
678
+ ctx,
679
+ outcome="failed",
680
+ details={"code": error_type(error), "message": str(error)[:500]},
681
+ )
682
+
683
+ async def _audit_denied(self, ctx: OperationContext, action: str, error: Exception) -> None:
684
+ ctx.extras["audited_denial"] = True
685
+ await self._audit_alone(
686
+ ctx,
687
+ outcome="denied",
688
+ action=action,
689
+ details={
690
+ "code": getattr(error, "code", type(error).__name__),
691
+ "reason": (getattr(error, "details", None) or {}).get("reason") or str(error),
692
+ **(
693
+ {"fields": details["fields"]}
694
+ if isinstance(details := getattr(error, "details", None), dict)
695
+ and "fields" in details
696
+ else {}
697
+ ),
698
+ **(
699
+ {
700
+ "expected": error.details.get("expected"),
701
+ "current": error.details.get("current"),
702
+ }
703
+ if isinstance(error, VersionConflict)
704
+ else {}
705
+ ),
706
+ },
707
+ )
708
+
709
+ async def _audit_read(self, ctx: OperationContext, details: dict[str, Any]) -> None:
710
+ if ctx.resource.audit_reads:
711
+ await self._audit_alone(ctx, details=details)
712
+
713
+ async def _field_rules(self, ctx: OperationContext, mode: str) -> Any:
714
+ """Prepared field rules (``None`` when no field can be blocked)."""
715
+ prepare = getattr(self.authorizer, "field_rules", None)
716
+ if prepare is None:
717
+ return None
718
+ rules = await prepare(ctx.actor, ctx.resource.name, mode)
719
+ return None if getattr(rules, "empty", False) else rules
720
+
721
+ def _to_read(self, ctx: OperationContext, entity: Any, rules: Any = None) -> Any:
722
+ """Step 9 result: the read schema, without the fields the caller may not
723
+ read (omitted)."""
724
+ subtype = (
725
+ self.registry.subtype_of(ctx.resource, entity) if ctx.resource.discriminator else None
726
+ )
727
+ if subtype is not None:
728
+ # a base record reads as its subtype; the subtype's restricted fields
729
+ # need its own grants, so they stay hidden here
730
+ result = subtype.resource_cls.to_read(entity, ctx)
731
+ if subtype.restricted_fields:
732
+ from resource_engine.authz.fields import mask
733
+
734
+ result = mask(result, set(subtype.restricted_fields))
735
+ else:
736
+ result = ctx.resource.resource_cls.to_read(entity, ctx)
737
+ if rules is None:
738
+ return result
739
+ hidden = rules.decide(resource=entity).blocked
740
+ if hidden:
741
+ from resource_engine.authz.fields import mask
742
+
743
+ ctx.extras["hidden_fields"] = hidden
744
+ return mask(result, hidden)
745
+ return result
746
+
747
+ async def _read_rules(self, ctx: OperationContext) -> Any:
748
+ return await self._field_rules(ctx, "read") if self.authorizer is not None else None
749
+
750
+ async def _gate_fields(self, ctx: OperationContext, entity: Any, data: Any) -> None:
751
+ """Step 5b for writes: every field sent must be writable (RE-E706)."""
752
+ if self.authorizer is None or data is None:
753
+ return
754
+ rules = await self._field_rules(ctx, "write")
755
+ if rules is None:
756
+ return
757
+ sent = set(data.model_dump(exclude_unset=True)) if isinstance(data, BaseModel) else set()
758
+ blocked = sorted(sent & rules.decide(resource=entity, input=data).blocked)
759
+ if blocked:
760
+ error = FieldNotWritable(
761
+ f"Not allowed to write {', '.join(blocked)} of {ctx.resource.name}",
762
+ hint="GET /authz/me lists the fields you may write.",
763
+ details={"resource": ctx.resource.name, "fields": blocked},
764
+ )
765
+ await self._audit_denied(ctx, ctx.operation, error)
766
+ raise error
767
+
768
+ async def _gate_query(self, ctx: OperationContext, query: ListQuery, rules: Any) -> None:
769
+ """Filtering or sorting by hidden fields would reveal them (RE-E707)."""
770
+ if rules is None:
771
+ return
772
+ from resource_engine.application.searching import split_operator
773
+
774
+ used = {split_operator(f)[0] for f in query.filters} | {
775
+ o.lstrip("-") for o in query.order_by
776
+ }
777
+ blocked = sorted(used & rules.decide().blocked)
778
+ if blocked:
779
+ error = FieldNotReadable(
780
+ f"Not allowed to filter or sort {ctx.resource.name} by {', '.join(blocked)}",
781
+ details={"resource": ctx.resource.name, "fields": blocked},
782
+ )
783
+ await self._audit_denied(ctx, "list", error)
784
+ raise error
785
+
786
+ def _searched(self, ctx: OperationContext, query: ListQuery, rules: Any) -> ListQuery:
787
+ """Operator filters and the search as part of the query's condition. A
788
+ searched field the caller may not read is left out of their search."""
789
+ from resource_engine.application.searching import (
790
+ operator_filters,
791
+ search_condition,
792
+ search_words,
793
+ )
794
+ from resource_engine.authz.conditions import conjunction
795
+
796
+ resource = ctx.resource
797
+ plain, operators = operator_filters(
798
+ resource.name, query.filters, resource.schemas.get("read")
799
+ )
800
+ words = search_words(query.search)
801
+ if operators is None and not words:
802
+ return dataclasses.replace(query, search=None)
803
+ if not getattr(ctx.repository(), "supports_conditions", False):
804
+ raise QueryNotSupported(
805
+ f"The store of {resource.name!r} can't apply filter operators or a search",
806
+ hint="Use equality filters, or a store that applies conditions "
807
+ "(SQL, in memory, the query engines).",
808
+ doc="docs/frontend.md#lists",
809
+ )
810
+ hidden = rules.decide().blocked if rules is not None else frozenset()
811
+ searched = (
812
+ search_condition([f for f in resource.searchable if f not in hidden], words)
813
+ if words
814
+ else None
815
+ )
816
+ return dataclasses.replace(
817
+ query,
818
+ filters=plain,
819
+ search=None,
820
+ condition=conjunction(query.condition, operators, searched),
821
+ )
822
+
823
+ def _joined(self) -> Transaction | None:
824
+ tx = current_transaction.get()
825
+ return tx if tx is not None and tx.owner is self and not tx.finished else None
826
+
827
+ @asynccontextmanager
828
+ async def transaction(self) -> AsyncIterator[Transaction]:
829
+ """Run several operations in one unit of work (see
830
+ ``resource_engine.application.transaction``). Nested calls join the
831
+ outer transaction."""
832
+ joined = self._joined()
833
+ if joined is not None:
834
+ yield joined
835
+ return
836
+ async with self.uow_factory() as uow:
837
+ tx = Transaction(self, uow)
838
+ token = current_transaction.set(tx)
839
+ try:
840
+ yield tx
841
+ if tx.doomed is not None:
842
+ cause = tx.doomed
843
+ raise TransactionDoomed(
844
+ "An operation failed inside the transaction; it can only roll back",
845
+ hint="Let the error propagate, or check before calling the manager.",
846
+ details={
847
+ "code": getattr(cause, "code", type(cause).__name__),
848
+ "message": str(cause),
849
+ },
850
+ ) from cause
851
+ await uow.commit()
852
+ except BaseException:
853
+ for ctx in reversed(tx.contexts):
854
+ await _run_callbacks(reversed(ctx._on_rollback), "rollback", ctx)
855
+ raise
856
+ finally:
857
+ tx.finished = True
858
+ current_transaction.reset(token)
859
+ for ctx, qualifier in tx.after_commit:
860
+ await self._after_commit(ctx, qualifier)
861
+
862
+ @asynccontextmanager
863
+ async def _reading(self, ctx: OperationContext | None = None) -> AsyncIterator[Any]:
864
+ """A unit of work for reads: the transaction's, if one is open (reads then
865
+ see its uncommitted writes)."""
866
+ tx = self._joined()
867
+ if tx is not None:
868
+ if ctx is not None:
869
+ ctx.uow = tx.view
870
+ yield tx.view
871
+ return
872
+ async with self.uow_factory() as uow:
873
+ if ctx is not None:
874
+ ctx.uow = uow
875
+ yield uow
876
+
877
+ @asynccontextmanager
878
+ async def _transaction(self, ctx: OperationContext) -> AsyncIterator[UnitOfWork]:
879
+ """Steps 4-9: open the unit of work (or join ``transaction()``); on
880
+ failure run staged-effect compensations (or doom the transaction)."""
881
+ tx = self._joined()
882
+ if tx is not None:
883
+ ctx.uow = tx.view
884
+ ctx.extras["transaction"] = tx
885
+ tx.contexts.append(ctx)
886
+ try:
887
+ yield ctx.uow
888
+ except BaseException as exc:
889
+ if tx.doomed is None:
890
+ tx.doomed = exc
891
+ await self._audit_failed(ctx, exc)
892
+ raise
893
+ return
894
+ try:
895
+ async with self.uow_factory() as uow:
896
+ ctx.uow = uow
897
+ yield uow
898
+ except BaseException as exc:
899
+ await _run_callbacks(reversed(ctx._on_rollback), "rollback", ctx)
900
+ await self._audit_failed(ctx, exc)
901
+ raise
902
+
903
+ async def _after_commit(self, ctx: OperationContext, qualifier: str | None = None) -> None:
904
+ tx = ctx.extras.get("transaction")
905
+ if tx is not None and not tx.finished: # runs when the transaction commits
906
+ tx.after_commit.append((ctx, qualifier))
907
+ return
908
+ ctx.uow = None
909
+ if (
910
+ self.records is not None
911
+ and ctx.resource.cache_ttl is not None
912
+ and ctx.entity_id is not None
913
+ and ctx.operation != "get"
914
+ ):
915
+ try:
916
+ await self.records.forget(ctx.resource, ctx.entity_id)
917
+ except Exception as exc: # the change is committed: report, don't fail it
918
+ await report_error(exc, where="after_commit", force=True, cache="forget")
919
+ await _run_callbacks(ctx._on_commit, "on_commit", ctx)
920
+ for hook in ctx.resource.dispatcher.for_point(HookPoint.AFTER_COMMIT, None):
921
+ try:
922
+ result = hook(ctx)
923
+ if inspect.isawaitable(result):
924
+ await result
925
+ except Exception as exc:
926
+ await report_error(
927
+ exc,
928
+ where="after_commit",
929
+ force=True,
930
+ hook=getattr(hook, "__qualname__", repr(hook)),
931
+ resource=ctx.resource.name,
932
+ correlation_id=ctx.correlation_id,
933
+ )
934
+ ctx.extras.setdefault("after_commit_errors", []).append(hook)
935
+ try:
936
+ await self.delivery.after_commit(ctx)
937
+ except Exception as exc:
938
+ await report_error(
939
+ exc,
940
+ where="after_commit",
941
+ force=True,
942
+ events=len(ctx.events),
943
+ resource=ctx.resource.name,
944
+ correlation_id=ctx.correlation_id,
945
+ )
946
+
947
+ # --------------------------------------------------------------------- read
948
+
949
+ @traced("list")
950
+ async def list(
951
+ self,
952
+ resource: ResourceRef,
953
+ query: ListQuery | None = None,
954
+ *,
955
+ actor: Any = None,
956
+ tenant: str | None = None,
957
+ expand: Sequence[str] = (),
958
+ _within: Mapping[str, Any] | None = None,
959
+ _condition: Any = None,
960
+ _unbounded: bool = False,
961
+ ) -> Page[Any]:
962
+ """One page of ``resource``'s records matching ``query`` that ``actor`` may see, with
963
+ ``expand`` relations embedded."""
964
+ definition = self.registry.get(resource)
965
+ self._require(definition, "list")
966
+ query = query or ListQuery()
967
+ from resource_engine.application.searching import split_operator
968
+
969
+ own, related = split_filters(query.filters)
970
+ bad_filters = [f for f in own if split_operator(f)[0] not in definition.filterable]
971
+ for name, fields in related.items():
972
+ ref = definition.references.get(name)
973
+ target = self.registry.get(ref.target) if ref is not None else None
974
+ bad_filters += [
975
+ f"{name}.{f}" for f in fields if target is None or f not in target.filterable
976
+ ]
977
+ bad_order = [
978
+ o.lstrip("-") for o in query.order_by if o.lstrip("-") not in definition.sortable
979
+ ]
980
+ if bad_filters or bad_order:
981
+ related_names = related_filter_names(definition, self.registry)
982
+ raise InvalidQuery(
983
+ f"Invalid query for {definition.name}: "
984
+ + "; ".join(
985
+ part
986
+ for part in (
987
+ bad_filters and f"not filterable: {bad_filters}",
988
+ bad_order and f"not sortable: {bad_order}",
989
+ )
990
+ if part
991
+ ),
992
+ hint=(
993
+ f"Filterable: {[*definition.filterable, *related_names]}; "
994
+ f"sortable: {list(definition.sortable)}"
995
+ ),
996
+ )
997
+ if query.search and not definition.searchable:
998
+ raise InvalidQuery(
999
+ f"{definition.name} can't be searched",
1000
+ hint="Declare Listing(searchable=[...]) on the resource.",
1001
+ doc="docs/frontend.md#search",
1002
+ )
1003
+ self._check_expand(definition, expand)
1004
+ too_many = query.limit > definition.max_page_size and not _unbounded
1005
+ if query.limit < 1 or too_many or query.offset < 0:
1006
+ raise InvalidQuery(
1007
+ f"limit must be between 1 and {definition.max_page_size} and offset >= 0",
1008
+ )
1009
+ ctx = self._context(definition, "list", actor=actor, raw_input=query, tenant=tenant)
1010
+ await self._gate(ctx, "list")
1011
+ # _within: the parent of a reverse relation (not a client filter)
1012
+ query = dataclasses.replace(query, filters={**own, **(_within or {})})
1013
+ if _condition is not None: # internal: related records by id
1014
+ from resource_engine.authz.conditions import conjunction
1015
+
1016
+ query = dataclasses.replace(query, condition=conjunction(query.condition, _condition))
1017
+ tenant_query = self._tenant_query(ctx, query)
1018
+ if tenant_query is None:
1019
+ return Page([], 0, query.offset, query.limit)
1020
+ query = tenant_query
1021
+ rules = await self._read_rules(ctx)
1022
+ await self._gate_query(ctx, query, rules)
1023
+ async with self._reading(ctx):
1024
+ if _condition is not None and not getattr(
1025
+ ctx.repository(), "supports_conditions", False
1026
+ ):
1027
+ raise ConditionNotSupported(
1028
+ f"The repository of {definition.name!r} cannot select related records",
1029
+ hint="Many-to-many links need a repository with supports_conditions "
1030
+ "(in-memory, SQLAlchemy).",
1031
+ doc="docs/relationships.md#many-to-many",
1032
+ )
1033
+ scoped = await self._scoped(ctx, query)
1034
+ if scoped is not None and related:
1035
+ scoped = await self._related_scope(ctx, scoped, related)
1036
+ if scoped is None:
1037
+ return Page([], 0, query.offset, query.limit)
1038
+ scoped = self._searched(ctx, scoped, rules)
1039
+ if definition.translatable:
1040
+ from resource_engine.translatable import locale_chain
1041
+
1042
+ scoped = dataclasses.replace(
1043
+ scoped,
1044
+ translatable=frozenset(definition.translatable),
1045
+ locales=tuple(locale_chain(definition.default_locale)),
1046
+ )
1047
+ from resource_engine.capabilities import check_query
1048
+
1049
+ check_query(definition.name, ctx.repository(), scoped)
1050
+ page = await ctx.repository().list(scoped)
1051
+ result = page.map(lambda e: self._to_read(ctx, e, rules))
1052
+ if expand:
1053
+ await self._expand(ctx, page.items, result.items, expand)
1054
+ await self._audit_read(
1055
+ ctx,
1056
+ {
1057
+ "filters": {
1058
+ k: str(v)
1059
+ for k, v in {
1060
+ **query.filters,
1061
+ **{f"{n}.{f}": v for n, fs in related.items() for f, v in fs.items()},
1062
+ }.items()
1063
+ },
1064
+ "order_by": list(query.order_by),
1065
+ **({"search": query.search} if query.search else {}),
1066
+ "offset": query.offset,
1067
+ "returned": len(result.items),
1068
+ "total": result.total,
1069
+ },
1070
+ )
1071
+ return result
1072
+
1073
+ @traced("get")
1074
+ async def get(
1075
+ self,
1076
+ resource: ResourceRef,
1077
+ entity_id: Any,
1078
+ *,
1079
+ actor: Any = None,
1080
+ tenant: str | None = None,
1081
+ expand: Sequence[str] = (),
1082
+ ) -> Any:
1083
+ """The record ``entity_id`` of ``resource``, if ``actor`` may see it. Raises
1084
+ ``EntityNotFound`` otherwise."""
1085
+ definition = self.registry.get(resource)
1086
+ self._require(definition, "get")
1087
+ self._check_expand(definition, expand)
1088
+ ctx = self._context(definition, "get", actor=actor, entity_id=entity_id, tenant=tenant)
1089
+ await self._gate(ctx, "get")
1090
+ async with self._reading(ctx):
1091
+ entity = await self._load(ctx)
1092
+ await self._gate_record(ctx, "get", entity)
1093
+ result = self._to_read(ctx, entity, await self._read_rules(ctx))
1094
+ if expand:
1095
+ await self._expand(ctx, [entity], [result], expand)
1096
+ await self._audit_read(ctx, {})
1097
+ return result
1098
+
1099
+ # --------------------------------------------------------------- references
1100
+
1101
+ def _relation(self, definition: ResourceDefinition, name: str) -> tuple[str, Any, Any] | None:
1102
+ """``(kind, relation, definition of the related records)`` for a relation
1103
+ name: ``forward`` (a reference), ``reverse`` or ``link`` (many-to-many)."""
1104
+ from resource_engine.application.relations import LinkDefinition
1105
+
1106
+ if name in definition.references:
1107
+ ref = definition.references[name]
1108
+ return "forward", ref, self.registry.get(ref.target)
1109
+ rel = self.reverse.get(definition.name, {}).get(name)
1110
+ if rel is None:
1111
+ return None
1112
+ kind = "link" if isinstance(rel, LinkDefinition) else "reverse"
1113
+ return kind, rel, self.registry.get(rel.owner)
1114
+
1115
+ def _check_expand(self, definition: ResourceDefinition, expand: Sequence[str]) -> None:
1116
+ """Every path names relations (``invoices.customer_record``, at most
1117
+ ``MAX_EXPAND_DEPTH`` levels); sizes only on reverse and link relations."""
1118
+ from resource_engine.application.relations import parse_expand
1119
+
1120
+ for item in expand:
1121
+ path = item.split(".")
1122
+ if len(path) > MAX_EXPAND_DEPTH:
1123
+ raise InvalidQuery(
1124
+ f"expand {item!r} is nested more than {MAX_EXPAND_DEPTH} levels",
1125
+ doc="docs/relationships.md#nested-expansion",
1126
+ )
1127
+ current = definition
1128
+ for segment in path:
1129
+ name, size = parse_expand(segment)
1130
+ found = self._relation(current, name)
1131
+ if found is None:
1132
+ known = [*current.references, *self.reverse.get(current.name, {})]
1133
+ raise InvalidQuery(
1134
+ f"{current.name} has no relation {name!r} to expand",
1135
+ hint=f"Relations of {current.name}: {known or '(none)'}",
1136
+ doc="docs/relationships.md#expanding",
1137
+ )
1138
+ kind, _rel, related = found
1139
+ if size is not None:
1140
+ limit = related.max_page_size
1141
+ if kind == "forward" or not 1 <= size <= limit:
1142
+ raise InvalidQuery(
1143
+ f"Invalid expand {item!r}"
1144
+ + (
1145
+ ": only reverse relations take a page size"
1146
+ if kind == "forward"
1147
+ else f": the size must be between 1 and {limit}"
1148
+ ),
1149
+ doc="docs/relationships.md#reverse-relations",
1150
+ )
1151
+ current = related
1152
+
1153
+ async def _related_context(
1154
+ self, ctx: OperationContext, target: ResourceDefinition
1155
+ ) -> OperationContext | None:
1156
+ """A read context on ``target`` for the same caller and operation (no
1157
+ audit, no idempotency); ``None`` when the caller has no tenant scope there."""
1158
+ tctx = OperationContext(
1159
+ resource=target,
1160
+ operation="get",
1161
+ actor=ctx.actor,
1162
+ services=self.services,
1163
+ correlation_id=ctx.correlation_id,
1164
+ uow=ctx.uow,
1165
+ )
1166
+ tctx.extras["requested_tenant"] = ctx.extras.get("requested_tenant")
1167
+ if target.tenant_field is not None:
1168
+ from resource_engine.tenancy import resolve_tenant
1169
+
1170
+ try:
1171
+ scope = await resolve_tenant(
1172
+ ctx.actor, self.authorizer, ctx.extras.get("requested_tenant") or ctx.tenant
1173
+ )
1174
+ except (TenantRequired, TenantMismatch):
1175
+ return None
1176
+ tctx._tenant_scope = scope
1177
+ tctx.tenant = scope.tenant
1178
+ return tctx
1179
+
1180
+ async def _visible(self, tctx: OperationContext, entity: Any) -> bool:
1181
+ field_name = tctx.resource.tenant_field
1182
+ if (
1183
+ field_name
1184
+ and tctx.tenant is not None
1185
+ and getattr(entity, field_name, None) != tctx.tenant
1186
+ ):
1187
+ return False
1188
+ if self.authorizer is None:
1189
+ return True
1190
+ decision = await self.authorizer.check(
1191
+ tctx.actor, f"{tctx.resource.name}:get", resource=entity
1192
+ )
1193
+ return decision.allowed is True
1194
+
1195
+ async def _related(
1196
+ self,
1197
+ ctx: OperationContext,
1198
+ ref: ReferenceDefinition,
1199
+ ids: builtins.list[Any],
1200
+ *,
1201
+ read: bool = True,
1202
+ nested: Sequence[str] = (),
1203
+ ) -> dict[Any, Any]:
1204
+ """The records of ``ref.target`` with these ids that the caller may read
1205
+ (read models, or entities with ``read=False``), by id."""
1206
+ return await self._records(
1207
+ ctx, self.registry.get(ref.target), ids, read=read, nested=nested
1208
+ )
1209
+
1210
+ async def _records(
1211
+ self,
1212
+ ctx: OperationContext,
1213
+ target: ResourceDefinition,
1214
+ ids: builtins.list[Any],
1215
+ *,
1216
+ read: bool = True,
1217
+ nested: Sequence[str] = (),
1218
+ ) -> dict[Any, Any]:
1219
+ tctx = await self._related_context(ctx, target)
1220
+ if tctx is None or not ids:
1221
+ return {}
1222
+ repository = ctx.uow.repository(target.name) # type: ignore[union-attr]
1223
+ if len(ids) > 1 and getattr(repository, "supports_conditions", False):
1224
+ condition = {"in": [{"attr": f"resource.{target.id_field}"}, list(ids)]}
1225
+ entities = (await repository.list(ListQuery(limit=len(ids), condition=condition))).items
1226
+ else:
1227
+ entities = [e for i in ids if (e := await repository.get(i)) is not None]
1228
+ rules = await self._read_rules(tctx) if read else None
1229
+ found: dict[Any, Any] = {}
1230
+ visible: list[Any] = []
1231
+ for entity in entities:
1232
+ if await self._visible(tctx, entity):
1233
+ key = getattr(entity, target.id_field)
1234
+ found[key] = self._to_read(tctx, entity, rules) if read else entity
1235
+ visible.append(entity)
1236
+ if read and nested and visible:
1237
+ reads = [found[getattr(e, target.id_field)] for e in visible]
1238
+ await self._expand(tctx, visible, reads, nested)
1239
+ return found
1240
+
1241
+ async def _check_references(
1242
+ self, ctx: OperationContext, entity: Any, fields: Collection[str] | None = None
1243
+ ) -> None:
1244
+ """Writes: each reference set (or changed) points to a record the
1245
+ caller can read (RE-E108)."""
1246
+ for ref in ctx.resource.references.values():
1247
+ if fields is not None and ref.field not in fields:
1248
+ continue
1249
+ value = getattr(entity, ref.field, None)
1250
+ if value is None:
1251
+ continue
1252
+ found = await self._related(ctx, ref, [value], read=False)
1253
+ if value not in found:
1254
+ raise ReferenceNotFound(
1255
+ f"{ctx.resource.name}.{ref.field}: there is no {ref.target} record {value!r}",
1256
+ hint=f"Use the id of an existing {ref.target} record you can read.",
1257
+ details={"field": ref.field, "resource": ref.target, "id": value},
1258
+ doc="docs/relationships.md#integrity",
1259
+ )
1260
+
1261
+ async def _expand(
1262
+ self,
1263
+ ctx: OperationContext,
1264
+ entities: builtins.list[Any],
1265
+ results: builtins.list[Any],
1266
+ names: Sequence[str],
1267
+ ) -> None:
1268
+ """Attach the expanded relations to ``results`` (read models of
1269
+ ``entities``); nested paths continue on the related records."""
1270
+ from resource_engine.application.relations import attach, parse_expand, unique
1271
+
1272
+ groups: dict[str, tuple[int | None, list[str]]] = {}
1273
+ for item in names:
1274
+ head, _, rest = item.partition(".")
1275
+ name, size = parse_expand(head)
1276
+ known_size, nested = groups.setdefault(name, (size, []))
1277
+ if known_size is None and size is not None:
1278
+ groups[name] = (size, nested)
1279
+ if rest:
1280
+ nested.append(rest)
1281
+ for name, (size, nested) in groups.items():
1282
+ found = self._relation(ctx.resource, name)
1283
+ assert found is not None # checked by _check_expand
1284
+ kind, rel, _related = found
1285
+ if kind == "forward":
1286
+ ids = unique(getattr(e, rel.field, None) for e in entities)
1287
+ records = await self._related(ctx, rel, ids, nested=nested)
1288
+ for entity, result in zip(entities, results, strict=True):
1289
+ value = getattr(entity, rel.field, None)
1290
+ attach(result, {name: None if value is None else records.get(value)})
1291
+ continue
1292
+ parent_ids = [getattr(e, ctx.resource.id_field) for e in entities]
1293
+ pages = await self._related_pages(ctx, kind, rel, parent_ids, size, nested)
1294
+ for parent_id, result in zip(parent_ids, results, strict=True):
1295
+ attach(result, {name: pages.get(parent_id)})
1296
+
1297
+ async def _related_pages(
1298
+ self,
1299
+ ctx: OperationContext,
1300
+ kind: str,
1301
+ rel: Any,
1302
+ parent_ids: builtins.list[Any],
1303
+ size: int | None,
1304
+ nested: Sequence[str],
1305
+ ) -> dict[Any, Any]:
1306
+ """One ``RelatedPage`` per parent (``None`` when the caller may not list
1307
+ the records). Reverse relations of several parents load in one query
1308
+ when they match at most ``MAX_RELATED_MATCHES`` records."""
1309
+ from resource_engine.application.relations import RelatedPage
1310
+
1311
+ owner = self.registry.get(rel.owner)
1312
+ limit = min(size or EXPAND_PAGE_SIZE, owner.max_page_size)
1313
+ needed = [rel.owner] if kind == "reverse" else [rel.join, rel.target]
1314
+ for resource in needed:
1315
+ if not await self.can(ctx.actor, resource, "list"):
1316
+ return dict.fromkeys(parent_ids)
1317
+ tenant = ctx.extras.get("requested_tenant")
1318
+ out: dict[Any, Any] = {}
1319
+ try:
1320
+ if kind == "reverse" and len(parent_ids) > 1:
1321
+ batch = await self._reverse_batch(ctx, rel, parent_ids, limit, nested)
1322
+ if batch is not None:
1323
+ return batch
1324
+ for parent_id in parent_ids:
1325
+ if kind == "reverse":
1326
+ page = await self.list(
1327
+ rel.owner,
1328
+ ListQuery(limit=limit),
1329
+ actor=ctx.actor,
1330
+ tenant=tenant,
1331
+ expand=nested,
1332
+ _within={rel.field: parent_id},
1333
+ )
1334
+ else:
1335
+ page = await self._linked(
1336
+ rel, parent_id, ListQuery(limit=limit), ctx.actor, tenant, nested
1337
+ )
1338
+ out[parent_id] = RelatedPage(page.items, page.total, limit)
1339
+ except (PermissionDenied, TenantRequired, TenantMismatch):
1340
+ return dict.fromkeys(parent_ids)
1341
+ return out
1342
+
1343
+ async def _reverse_batch(
1344
+ self,
1345
+ ctx: OperationContext,
1346
+ rel: ReferenceDefinition,
1347
+ parent_ids: builtins.list[Any],
1348
+ limit: int,
1349
+ nested: Sequence[str],
1350
+ ) -> dict[Any, Any] | None:
1351
+ """Every parent's page from one query; ``None`` to fall back to one
1352
+ query per parent (too many records, no conditions, hidden field)."""
1353
+ from resource_engine.application.relations import RelatedPage
1354
+ from resource_engine.authz.fields import hidden_fields
1355
+
1356
+ owner = self.registry.get(rel.owner)
1357
+ repository_supports = await self._supports_conditions(owner.name)
1358
+ if not repository_supports:
1359
+ return None
1360
+ page = await self.list(
1361
+ rel.owner,
1362
+ ListQuery(limit=MAX_RELATED_MATCHES + 1),
1363
+ actor=ctx.actor,
1364
+ tenant=ctx.extras.get("requested_tenant"),
1365
+ expand=nested,
1366
+ _condition={"in": [{"attr": f"resource.{rel.field}"}, list(parent_ids)]},
1367
+ _unbounded=True,
1368
+ )
1369
+ if page.total > MAX_RELATED_MATCHES:
1370
+ return None
1371
+ grouped: dict[Any, list[Any]] = {p: [] for p in parent_ids}
1372
+ for item in page.items:
1373
+ if rel.field in hidden_fields(item) or not hasattr(item, rel.field):
1374
+ return None # cannot tell whose it is
1375
+ grouped.setdefault(getattr(item, rel.field), []).append(item)
1376
+ return {
1377
+ p: RelatedPage(items[:limit], len(items), limit)
1378
+ for p, items in grouped.items()
1379
+ if p in parent_ids or items
1380
+ }
1381
+
1382
+ async def _supports_conditions(self, resource: str) -> bool:
1383
+ async with self._reading() as uow:
1384
+ return bool(getattr(uow.repository(resource), "supports_conditions", False))
1385
+
1386
+ async def _linked(
1387
+ self,
1388
+ link: Any,
1389
+ source_id: Any,
1390
+ query: ListQuery | None,
1391
+ actor: Any,
1392
+ tenant: str | None,
1393
+ expand: Sequence[str],
1394
+ ) -> Page[Any]:
1395
+ """The ``link.target`` records linked to ``source_id`` through the join
1396
+ resource, with the caller's permissions on both."""
1397
+ target = self.registry.get(link.target)
1398
+ rows = await self.list(
1399
+ link.join,
1400
+ ListQuery(limit=MAX_RELATED_MATCHES + 1),
1401
+ actor=actor,
1402
+ tenant=tenant,
1403
+ _within={link.source_field: source_id},
1404
+ _unbounded=True,
1405
+ )
1406
+ if rows.total > MAX_RELATED_MATCHES:
1407
+ raise InvalidQuery(
1408
+ f"More than {MAX_RELATED_MATCHES} {link.join} records link this {link.source}",
1409
+ hint=f"List {link.join} filtered by {link.source_field} instead.",
1410
+ doc="docs/relationships.md#many-to-many",
1411
+ )
1412
+ from resource_engine.application.relations import unique
1413
+
1414
+ ids = unique(getattr(row, link.target_field, None) for row in rows.items)
1415
+ query = query or ListQuery()
1416
+ if not ids:
1417
+ return Page([], 0, query.offset, query.limit)
1418
+ return await self.list(
1419
+ link.target,
1420
+ query,
1421
+ actor=actor,
1422
+ tenant=tenant,
1423
+ expand=expand,
1424
+ _condition={"in": [{"attr": f"resource.{target.id_field}"}, ids]},
1425
+ )
1426
+
1427
+ async def get_many(
1428
+ self,
1429
+ resource: ResourceRef,
1430
+ ids: Collection[Any],
1431
+ *,
1432
+ actor: Any = None,
1433
+ tenant: str | None = None,
1434
+ expand: Sequence[str] = (),
1435
+ ) -> dict[Any, Any]:
1436
+ """The records with these ids that ``actor`` may read, by id, in one
1437
+ query where the repository supports it (batch loaders, GraphQL).
1438
+ Missing and unreadable ids are left out; nothing is audited."""
1439
+ definition = self.registry.get(resource)
1440
+ self._require(definition, "get")
1441
+ self._check_expand(definition, expand)
1442
+ ids = [i for i in dict.fromkeys(ids) if i is not None]
1443
+ if not ids or not await self.can(actor, definition.name, "get", tenant=tenant):
1444
+ return {}
1445
+ ctx = self._context(definition, "get", actor=actor, tenant=tenant)
1446
+ async with self._reading(ctx):
1447
+ return await self._records(ctx, definition, ids, nested=expand)
1448
+
1449
+ async def list_related(
1450
+ self,
1451
+ resource: ResourceRef,
1452
+ entity_id: Any,
1453
+ relation: str,
1454
+ query: ListQuery | None = None,
1455
+ *,
1456
+ actor: Any = None,
1457
+ tenant: str | None = None,
1458
+ expand: Sequence[str] = (),
1459
+ ) -> Page[Any]:
1460
+ """The records of a reverse relation or a many-to-many link:
1461
+ ``list_related("customers", 7, "invoices")`` lists the invoices of
1462
+ customer 7, ``list_related("invoices", 3, "tags")`` the tags of invoice 3.
1463
+ The record must be readable by the caller (``get``); the related records
1464
+ are listed with the caller's ``list`` permissions, filters and ordering."""
1465
+ definition = self.registry.get(resource)
1466
+ found = self._relation(definition, relation)
1467
+ if found is None or found[0] == "forward":
1468
+ raise InvalidQuery(
1469
+ f"{definition.name} has no reverse or many-to-many relation {relation!r}",
1470
+ hint=f"Relations: {list(self.reverse.get(definition.name, {}))}",
1471
+ doc="docs/relationships.md#reverse-relations",
1472
+ )
1473
+ kind, rel, _related = found
1474
+ await self.get(definition.name, entity_id, actor=actor, tenant=tenant)
1475
+ if kind == "link":
1476
+ return await self._linked(rel, entity_id, query, actor, tenant, expand)
1477
+ return await self.list(
1478
+ rel.owner,
1479
+ query,
1480
+ actor=actor,
1481
+ tenant=tenant,
1482
+ expand=expand,
1483
+ _within={rel.field: entity_id},
1484
+ )
1485
+
1486
+ async def _related_scope(
1487
+ self, ctx: OperationContext, query: ListQuery, related: Mapping[str, Mapping[str, Any]]
1488
+ ) -> ListQuery | None:
1489
+ """``list`` filters on related records → ``<field> in [ids]``; ``None``
1490
+ when no related record matches."""
1491
+ from resource_engine.authz.conditions import conjunction
1492
+
1493
+ if not getattr(ctx.repository(), "supports_conditions", False):
1494
+ raise ConditionNotSupported(
1495
+ f"The repository of {ctx.resource.name!r} cannot filter by related records",
1496
+ hint="Use a repository with supports_conditions (in-memory, SQLAlchemy), or "
1497
+ "filter by the reference id.",
1498
+ doc="docs/relationships.md#filtering",
1499
+ )
1500
+ condition = query.condition
1501
+ for name, filters in related.items():
1502
+ ref = ctx.resource.references[name]
1503
+ target = self.registry.get(ref.target)
1504
+ tctx = await self._related_context(ctx, target)
1505
+ if tctx is None:
1506
+ return None
1507
+ await self._gate_query(tctx, ListQuery(filters=filters), await self._read_rules(tctx))
1508
+ own = dict(filters)
1509
+ if target.tenant_field and tctx.tenant is not None:
1510
+ own[target.tenant_field] = tctx.tenant
1511
+ page = await ctx.uow.repository(target.name).list( # type: ignore[union-attr]
1512
+ ListQuery(filters=own, limit=MAX_RELATED_MATCHES + 1)
1513
+ )
1514
+ if page.total > MAX_RELATED_MATCHES or len(page.items) > MAX_RELATED_MATCHES:
1515
+ raise InvalidQuery(
1516
+ f"The filter on {name} matches more than {MAX_RELATED_MATCHES} "
1517
+ f"{target.name} records",
1518
+ hint="Narrow the related filter, or filter by the reference id.",
1519
+ doc="docs/relationships.md#filtering",
1520
+ )
1521
+ ids = [getattr(e, target.id_field) for e in page.items if await self._visible(tctx, e)]
1522
+ if not ids:
1523
+ return None
1524
+ condition = conjunction(condition, {"in": [{"attr": f"resource.{ref.field}"}, ids]})
1525
+ return dataclasses.replace(query, condition=condition)
1526
+
1527
+ async def _release_dependents(
1528
+ self, ctx: OperationContext, dependents: Sequence[ReferenceDefinition]
1529
+ ) -> None:
1530
+ """Delete: refuse while restricting references exist (RE-E109); clear
1531
+ or delete the records of ``set_null`` / ``cascade`` references, through
1532
+ the manager as the same caller."""
1533
+ entity_id = ctx.entity_id
1534
+ for ref in dependents:
1535
+ if ref.on_delete != "restrict":
1536
+ continue
1537
+ page = await ctx.uow.repository(ref.owner).list( # type: ignore[union-attr]
1538
+ ListQuery(filters={ref.field: entity_id}, limit=1)
1539
+ )
1540
+ if page.items or page.total:
1541
+ raise ReferenceInUse(
1542
+ f"{ctx.resource.name} {entity_id!r} is referenced by {ref.owner}.{ref.field}",
1543
+ hint=f"Delete or change those {ref.owner} records first.",
1544
+ details={"resource": ref.owner, "field": ref.field, "id": entity_id},
1545
+ doc="docs/relationships.md#deleting",
1546
+ )
1547
+ tenant = ctx.extras.get("requested_tenant")
1548
+ for ref in dependents:
1549
+ if ref.on_delete == "restrict":
1550
+ continue
1551
+ owner = self.registry.get(ref.owner)
1552
+ done: set[Any] = set()
1553
+ while True:
1554
+ page = await ctx.uow.repository(ref.owner).list( # type: ignore[union-attr]
1555
+ ListQuery(filters={ref.field: entity_id}, limit=100)
1556
+ )
1557
+ pending = [i for e in page.items if (i := getattr(e, owner.id_field)) not in done]
1558
+ if not pending:
1559
+ break
1560
+ for child_id in pending:
1561
+ done.add(child_id)
1562
+ if ref.on_delete == "cascade":
1563
+ await self.delete(ref.owner, child_id, actor=ctx.actor, tenant=tenant)
1564
+ else:
1565
+ await self.update(
1566
+ ref.owner, child_id, {ref.field: None}, actor=ctx.actor, tenant=tenant
1567
+ )
1568
+
1569
+ # -------------------------------------------------------------------- write
1570
+
1571
+ @traced("create")
1572
+ @idempotent("create")
1573
+ async def create(
1574
+ self,
1575
+ resource: ResourceRef,
1576
+ data: Any,
1577
+ *,
1578
+ actor: Any = None,
1579
+ tenant: str | None = None,
1580
+ idempotency_key: str | None = None,
1581
+ ) -> Any:
1582
+ """Validate ``data``, run the create hooks and store a new record; returns its read
1583
+ model."""
1584
+ definition = self.registry.get(resource)
1585
+ self._require(definition, "create")
1586
+ ctx = self._context(definition, "create", actor=actor, raw_input=data, tenant=tenant)
1587
+ await self._gate(ctx, "create")
1588
+ await self._validate(ctx, definition.schemas["create"])
1589
+ hooks = definition.dispatcher
1590
+ async with self._transaction(ctx) as uow:
1591
+ entity = definition.resource_cls.build_entity(ctx.data, ctx)
1592
+ ctx.entity = entity
1593
+ if definition.parent is not None: # a subtype: its base's discriminator
1594
+ setattr(entity, definition.parent.discriminator or "", definition.identity)
1595
+ for runner in definition.record_machines.values():
1596
+ await runner.initialize(entity)
1597
+ _stamp_state(runner, entity)
1598
+ if definition.version_field and getattr(entity, definition.version_field, None) is None:
1599
+ setattr(entity, definition.version_field, 1)
1600
+ await self._stamp_tenant(ctx, entity)
1601
+ await self._gate(ctx, "create", resource=entity, input=ctx.data)
1602
+ await self._gate_fields(ctx, entity, ctx.data)
1603
+ await hooks.run(HookPoint.BEFORE_CREATE, ctx)
1604
+ await self._check_references(ctx, ctx.entity)
1605
+ entity = await ctx.repository().add(ctx.entity)
1606
+ ctx.entity = entity
1607
+ ctx.entity_id = self._id_of(ctx, entity)
1608
+ ctx.record_event(ResourceCreated(resource=definition.name, entity_id=ctx.entity_id))
1609
+ await hooks.run(HookPoint.AFTER_CREATE, ctx)
1610
+ ctx.result = self._to_read(ctx, ctx.entity, await self._read_rules(ctx))
1611
+ await self._before_commit(ctx, uow)
1612
+ await uow.commit()
1613
+ await self._after_commit(ctx)
1614
+ return ctx.result
1615
+
1616
+ @traced("update")
1617
+ @idempotent("update")
1618
+ async def update(
1619
+ self,
1620
+ resource: ResourceRef,
1621
+ entity_id: Any,
1622
+ data: Any,
1623
+ *,
1624
+ actor: Any = None,
1625
+ tenant: str | None = None,
1626
+ expected_version: int | None = None,
1627
+ idempotency_key: str | None = None,
1628
+ ) -> Any:
1629
+ """Apply ``data`` to the record ``entity_id`` (checking ``expected_version`` when given);
1630
+ returns its read model."""
1631
+ definition = self.registry.get(resource)
1632
+ self._require(definition, "update")
1633
+ ctx = self._context(
1634
+ definition,
1635
+ "update",
1636
+ actor=actor,
1637
+ raw_input=data,
1638
+ entity_id=entity_id,
1639
+ tenant=tenant,
1640
+ expected_version=expected_version,
1641
+ )
1642
+ await self._gate(ctx, "update")
1643
+ await self._validate(ctx, definition.schemas["update"])
1644
+ hooks = definition.dispatcher
1645
+ async with self._transaction(ctx) as uow:
1646
+ entity = await self._load(ctx)
1647
+ await self._gate_record(ctx, "update", entity, input=ctx.data)
1648
+ await self._gate_fields(ctx, entity, ctx.data)
1649
+ await self._check_version(ctx, entity)
1650
+ await hooks.run(HookPoint.BEFORE_UPDATE, ctx)
1651
+ sent = ctx.data.model_dump(exclude_unset=True)
1652
+ before = {k: getattr(entity, k, None) for k in sent}
1653
+ definition.resource_cls.apply_update(entity, ctx.data, ctx)
1654
+ changes = {
1655
+ k: (old, getattr(entity, k, None))
1656
+ for k, old in before.items()
1657
+ if getattr(entity, k, None) != old
1658
+ }
1659
+ await self._check_references(ctx, entity, changes)
1660
+ ctx.entity = await self._write(ctx, entity)
1661
+ ctx.record_event(
1662
+ ResourceUpdated(resource=definition.name, entity_id=entity_id, changes=changes)
1663
+ )
1664
+ await hooks.run(HookPoint.AFTER_UPDATE, ctx)
1665
+ ctx.result = self._to_read(ctx, ctx.entity, await self._read_rules(ctx))
1666
+ await self._before_commit(ctx, uow)
1667
+ await uow.commit()
1668
+ await self._after_commit(ctx)
1669
+ return ctx.result
1670
+
1671
+ @traced("delete")
1672
+ @idempotent("delete")
1673
+ async def delete(
1674
+ self,
1675
+ resource: ResourceRef,
1676
+ entity_id: Any,
1677
+ *,
1678
+ actor: Any = None,
1679
+ tenant: str | None = None,
1680
+ expected_version: int | None = None,
1681
+ idempotency_key: str | None = None,
1682
+ ) -> None:
1683
+ """Delete the record ``entity_id`` (checking ``expected_version`` when given)."""
1684
+ definition = self.registry.get(resource)
1685
+ self._require(definition, "delete")
1686
+ ctx = self._context(
1687
+ definition,
1688
+ "delete",
1689
+ actor=actor,
1690
+ entity_id=entity_id,
1691
+ tenant=tenant,
1692
+ expected_version=expected_version,
1693
+ )
1694
+ await self._gate(ctx, "delete")
1695
+ hooks = definition.dispatcher
1696
+ dependents = tuple(
1697
+ ref
1698
+ for ref in (
1699
+ *self.dependents.get(definition.name, ()),
1700
+ *(self.dependents.get(definition.parent.name, ()) if definition.parent else ()),
1701
+ )
1702
+ if self.registry.get(ref.owner).view is None # view rows follow their sources
1703
+ )
1704
+ # set_null / cascade change other records: one transaction for all of them
1705
+ grouped = any(r.on_delete != "restrict" for r in dependents)
1706
+ async with (
1707
+ self.transaction() if grouped else contextlib.nullcontext(),
1708
+ self._transaction(ctx) as uow,
1709
+ ):
1710
+ entity = await self._load(ctx)
1711
+ await self._gate_record(ctx, "delete", entity)
1712
+ await self._check_version(ctx, entity)
1713
+ await hooks.run(HookPoint.BEFORE_DELETE, ctx)
1714
+ await self._release_dependents(ctx, dependents)
1715
+ await self._remove(ctx, entity)
1716
+ if self.documents is not None and definition.document_slots:
1717
+ await self.documents.cascade(ctx)
1718
+ ctx.record_event(ResourceDeleted(resource=definition.name, entity_id=entity_id))
1719
+ await hooks.run(HookPoint.AFTER_DELETE, ctx)
1720
+ await self._before_commit(ctx, uow)
1721
+ await uow.commit()
1722
+ await self._after_commit(ctx)
1723
+
1724
+ @traced("transition")
1725
+ @idempotent("transition")
1726
+ async def transition(
1727
+ self,
1728
+ resource: ResourceRef,
1729
+ entity_id: Any,
1730
+ event: str,
1731
+ data: Any = None,
1732
+ *,
1733
+ actor: Any = None,
1734
+ tenant: str | None = None,
1735
+ expected_version: int | None = None,
1736
+ idempotency_key: str | None = None,
1737
+ ) -> Any:
1738
+ """Fire ``event`` on the record's state machine, with ``data`` as the payload; returns its
1739
+ read model."""
1740
+ definition = self.registry.get(resource)
1741
+ if definition.machine is None:
1742
+ raise UnknownTransition(
1743
+ f"Resource {definition.name!r} has no state machine",
1744
+ hint=(
1745
+ f"Transitions of {definition.name} records run on {definition.parent.name}."
1746
+ if definition.parent is not None
1747
+ else "Declare `state_machine = <StateMachine subclass>` on the resource."
1748
+ ),
1749
+ )
1750
+ machine = definition.machine_for(event)
1751
+ if machine is None:
1752
+ raise UnknownTransition(
1753
+ f"Resource {definition.name!r} has no transition {event!r}",
1754
+ hint=f"Available transitions: {', '.join(definition.transitions)}",
1755
+ )
1756
+ ctx = self._context(
1757
+ definition,
1758
+ "transition",
1759
+ transition=event,
1760
+ actor=actor,
1761
+ raw_input=data,
1762
+ entity_id=entity_id,
1763
+ tenant=tenant,
1764
+ expected_version=expected_version,
1765
+ )
1766
+ await self._gate(ctx, f"transition:{event}")
1767
+ await self._validate(ctx, definition.transition_schemas.get(event), event)
1768
+ hooks = definition.dispatcher
1769
+ async with self._transaction(ctx) as uow:
1770
+ entity = await self._load(ctx)
1771
+ await self._gate_record(ctx, f"transition:{event}", entity, input=ctx.data)
1772
+ await self._check_version(ctx, entity)
1773
+ ctx.previous_state = machine.current(entity)
1774
+ if (
1775
+ self.documents is not None
1776
+ and definition.document_slots
1777
+ and event in machine.allowed_events(entity)
1778
+ ):
1779
+ await self.documents.check_required(ctx, event)
1780
+ await hooks.run(HookPoint.BEFORE_TRANSITION, ctx, event)
1781
+ payload = (
1782
+ ctx.data.model_dump(exclude={definition.version_field} - {None})
1783
+ if ctx.data is not None
1784
+ else {}
1785
+ )
1786
+ previous, new = await machine.fire(entity, event, payload)
1787
+ _stamp_state(machine, entity)
1788
+ ctx.previous_state, ctx.new_state = previous, new
1789
+ ctx.entity = await self._write(ctx, entity)
1790
+ ctx.record_event(
1791
+ TransitionExecuted(
1792
+ resource=definition.name,
1793
+ entity_id=entity_id,
1794
+ transition=event,
1795
+ source=previous,
1796
+ target=new,
1797
+ machine=machine.name,
1798
+ )
1799
+ )
1800
+ await hooks.run(HookPoint.AFTER_TRANSITION, ctx, event)
1801
+ ctx.result = self._to_read(ctx, ctx.entity, await self._read_rules(ctx))
1802
+ await self._before_commit(ctx, uow)
1803
+ await uow.commit()
1804
+ await self._after_commit(ctx, event)
1805
+ return ctx.result
1806
+
1807
+ async def allowed_transitions(
1808
+ self, resource: ResourceRef, entity_id: Any, *, actor: Any = None, tenant: str | None = None
1809
+ ) -> builtins.list[str]:
1810
+ """The events of the record's state machine that ``actor`` may fire now."""
1811
+ definition = self.registry.get(resource)
1812
+ if definition.machine is None:
1813
+ return []
1814
+ ctx = self._context(definition, "get", actor=actor, entity_id=entity_id, tenant=tenant)
1815
+ async with self._reading(ctx):
1816
+ entity = await self._load(ctx)
1817
+ await self._gate_record(ctx, "get", entity)
1818
+ events = [
1819
+ e for m in definition.machines.values() for e in await m.enabled_events(entity)
1820
+ ]
1821
+ if self.authorizer is None:
1822
+ return events
1823
+ allowed = []
1824
+ for event in events:
1825
+ decision = await self.authorizer.check(
1826
+ actor, f"{definition.name}:transition:{event}", resource=entity
1827
+ )
1828
+ if decision.allowed is not False: # may still depend on the input
1829
+ allowed.append(event)
1830
+ return allowed
1831
+
1832
+ @traced("history")
1833
+ async def history(
1834
+ self,
1835
+ resource: ResourceRef,
1836
+ entity_id: Any,
1837
+ *,
1838
+ actor: Any = None,
1839
+ tenant: str | None = None,
1840
+ machine: str | None = None,
1841
+ ) -> builtins.list[StateChange]:
1842
+ """The record's state changes, oldest first: its creation and every
1843
+ committed transition, with the actor and time. Read from the audit trail;
1844
+ the caller needs to be able to ``get`` the record (RE-E009 without an
1845
+ audit trail or a state machine). With several machines each change names
1846
+ its ``machine``; ``machine=`` keeps one."""
1847
+ from resource_engine.audit.history import read_history, require_history_resource
1848
+
1849
+ definition = self.registry.get(resource)
1850
+ audit_resource = require_history_resource(self, definition)
1851
+ ctx = self._context(definition, "get", actor=actor, entity_id=entity_id, tenant=tenant)
1852
+ async with self._reading(ctx) as uow:
1853
+ entity = await self._load(ctx)
1854
+ await self._gate_record(ctx, "get", entity)
1855
+ tenant_value = (
1856
+ getattr(entity, definition.tenant_field, None) if definition.tenant_field else None
1857
+ )
1858
+ return await read_history(
1859
+ uow, audit_resource, definition, entity_id, tenant_value, machine
1860
+ )
1861
+
1862
+ @property
1863
+ def has_history(self) -> bool:
1864
+ """Whether ``history`` can read an audit trail."""
1865
+ from resource_engine.audit.history import history_resource
1866
+
1867
+ name = history_resource(self.audit)
1868
+ return name is not None and name in {d.name for d in self.registry}
1869
+
1870
+ @traced("action")
1871
+ @idempotent("action")
1872
+ async def run_action(
1873
+ self,
1874
+ resource: ResourceRef,
1875
+ entity_id: Any,
1876
+ action: str,
1877
+ data: Any = None,
1878
+ *,
1879
+ actor: Any = None,
1880
+ tenant: str | None = None,
1881
+ expected_version: int | None = None,
1882
+ idempotency_key: str | None = None,
1883
+ ) -> Any:
1884
+ """Run ``action`` on the record ``entity_id`` (``None`` for a collection action); returns
1885
+ the action's response. The arguments come in the order of ``transition``."""
1886
+ definition = self.registry.get(resource)
1887
+ action_def = definition.actions.get(action)
1888
+ if action_def is None:
1889
+ raise ActionNotFound(
1890
+ f"Resource {definition.name!r} has no action {action!r}",
1891
+ hint=f"Available actions: {', '.join(definition.actions) or '(none)'}",
1892
+ )
1893
+ if action_def.instance and entity_id is None:
1894
+ raise ValidationFailed(f"Action {action!r} requires an entity id")
1895
+ ctx = self._context(
1896
+ definition,
1897
+ "action",
1898
+ action=action,
1899
+ actor=actor,
1900
+ raw_input=data,
1901
+ entity_id=entity_id,
1902
+ tenant=tenant,
1903
+ expected_version=expected_version,
1904
+ )
1905
+ await self._gate(ctx, f"action:{action}")
1906
+ await self._validate(ctx, action_def.input_schema, action)
1907
+ hooks = definition.dispatcher
1908
+ async with self._transaction(ctx) as uow:
1909
+ if action_def.instance:
1910
+ entity = await self._load(ctx)
1911
+ await self._gate_record(ctx, f"action:{action}", entity, input=ctx.data)
1912
+ if definition.version_field: # claim the version before the action writes
1913
+ await self._check_version(ctx, entity)
1914
+ ctx.entity = await self._write(ctx, entity)
1915
+ else:
1916
+ await self._gate(ctx, f"action:{action}", resource=None, input=ctx.data)
1917
+ await hooks.run(HookPoint.BEFORE_ACTION, ctx, action)
1918
+ result = action_def.action_cls().execute(ctx)
1919
+ if inspect.isawaitable(result):
1920
+ result = await result
1921
+ ctx.record_event(
1922
+ ActionExecuted(resource=definition.name, entity_id=entity_id, action=action)
1923
+ )
1924
+ await hooks.run(HookPoint.AFTER_ACTION, ctx, action)
1925
+ if action_def.output_schema is not None:
1926
+ ctx.result = (
1927
+ result
1928
+ if isinstance(result, action_def.output_schema)
1929
+ else action_def.output_schema.model_validate(result, from_attributes=True)
1930
+ )
1931
+ elif result is None and action_def.instance and "read" in definition.schemas:
1932
+ ctx.result = self._to_read(ctx, ctx.entity, await self._read_rules(ctx))
1933
+ else:
1934
+ ctx.result = result
1935
+ await self._before_commit(ctx, uow)
1936
+ await uow.commit()
1937
+ await self._after_commit(ctx, action)
1938
+ return ctx.result
1939
+
1940
+
1941
+ def _stamp_state(machine: Any, entity: Any) -> None:
1942
+ """When the record entered the machine's current state (its ``since_field``)."""
1943
+ if machine.since_field:
1944
+ from datetime import UTC, datetime
1945
+
1946
+ setattr(entity, machine.since_field, datetime.now(UTC))
1947
+
1948
+
1949
+ async def _run_callbacks(callbacks: Any, kind: str, ctx: OperationContext) -> None:
1950
+ for callback in list(callbacks):
1951
+ try:
1952
+ result = callback()
1953
+ if inspect.isawaitable(result):
1954
+ await result
1955
+ except Exception as exc:
1956
+ await report_error(
1957
+ exc,
1958
+ where=f"{kind}_callback",
1959
+ force=True,
1960
+ callback=getattr(callback, "__qualname__", repr(callback)),
1961
+ resource=ctx.resource.name,
1962
+ correlation_id=ctx.correlation_id,
1963
+ )
1964
+
1965
+
1966
+ def _action_of(ctx: OperationContext) -> str:
1967
+ if ctx.operation == "transition":
1968
+ return f"transition:{ctx.transition}"
1969
+ if ctx.operation == "action":
1970
+ return f"action:{ctx.action}"
1971
+ return ctx.operation
1972
+
1973
+
1974
+ def _conflict(ctx: OperationContext, expected: Any, current: Any) -> VersionConflict:
1975
+ return VersionConflict(
1976
+ f"{ctx.resource.name} {ctx.entity_id!r} changed: version {current}, "
1977
+ f"the write was based on {expected}",
1978
+ hint="Reload the record and apply your change again.",
1979
+ details={
1980
+ "resource": ctx.resource.name,
1981
+ "id": ctx.entity_id,
1982
+ "expected": expected,
1983
+ "current": current,
1984
+ "reason": "version conflict",
1985
+ },
1986
+ doc="docs/concurrency.md",
1987
+ )