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,984 @@
1
+ """Declarative resource definitions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ import inspect
7
+ import re
8
+ from collections.abc import Mapping, Sequence
9
+ from dataclasses import dataclass, field
10
+ from typing import TYPE_CHECKING, Any, ClassVar
11
+
12
+ from pydantic import BaseModel
13
+ from statemachine import StateMachine
14
+
15
+ from resource_engine.application.actions import Action
16
+ from resource_engine.application.hooks import (
17
+ Hook,
18
+ HookDispatcher,
19
+ HookKey,
20
+ HookPoint,
21
+ normalize_hooks,
22
+ )
23
+ from resource_engine.application.relations import (
24
+ Link,
25
+ Reference,
26
+ ReferenceDefinition,
27
+ normalize_link,
28
+ normalize_references,
29
+ )
30
+ from resource_engine.application.settings import (
31
+ MOVED,
32
+ Access,
33
+ Audited,
34
+ Cached,
35
+ Internal,
36
+ Listing,
37
+ Subtype,
38
+ Translatable,
39
+ Versioned,
40
+ )
41
+ from resource_engine.application.slots import DocumentSlot
42
+ from resource_engine.application.state_machines import Machine, MachineRunner
43
+ from resource_engine.application.timers import Timer, TimerDefinition, normalize_timers
44
+ from resource_engine.application.views import Aggregate, check_view
45
+ from resource_engine.domain.events import DomainEvent
46
+ from resource_engine.errors import ConfigurationError, StateFieldExposed
47
+
48
+ if TYPE_CHECKING:
49
+ from resource_engine.application.context import OperationContext
50
+ from resource_engine.generation import Printout
51
+ from resource_engine.versions import ApiVersion, Deprecation
52
+
53
+ CRUD_OPERATIONS = ("list", "get", "create", "update", "delete")
54
+ #: Every CRUD operation: ``operations = CRUD``.
55
+ CRUD = CRUD_OPERATIONS
56
+
57
+ # Schemas each CRUD operation needs.
58
+ _REQUIRED_SCHEMAS = {
59
+ "list": ("read",),
60
+ "get": ("read",),
61
+ "create": ("create", "read"),
62
+ "update": ("update", "read"),
63
+ "delete": (),
64
+ }
65
+
66
+
67
+ def _default_name(cls_name: str) -> str:
68
+ base = cls_name.removesuffix("Resource") or cls_name
69
+ snake = re.sub(r"(?<!^)(?=[A-Z])", "_", base).lower()
70
+ return snake if snake.endswith("s") else f"{snake}s"
71
+
72
+
73
+ class Resource:
74
+ """Declarative description of a resource.
75
+
76
+ Subclass it and set class attributes; nothing is executed at import time.
77
+ The definition is validated when registered in a ``ResourceRegistry``.
78
+
79
+ Attributes:
80
+ name: Public name, used in URLs and registry lookups. Defaults to the
81
+ pluralised snake_case class name without ``Resource``
82
+ (``InvoiceResource`` → ``invoices``).
83
+ model: Domain entity class (a plain class or dataclass, not an ORM model).
84
+ id_field / id_type: Identifier attribute of the entity and its type.
85
+ schemas: Pydantic schemas per role: ``create``, ``update``, ``read``.
86
+ operations: Enabled CRUD operations, a subset of
87
+ ``list, get, create, update, delete`` (``CRUD`` for all of them).
88
+ operation_docs: Functional description of each CRUD operation.
89
+ hooks: Functions marked with ``@hook.before(...)`` / ``@hook.after(...)``
90
+ / ``@hook.after_commit``, or the modules holding them:
91
+ ``hooks = [hooks]``. The mapping
92
+ ``{"before_create": [fn, ...], "after_transition:approve": fn}`` works too.
93
+ state_machine: A ``python-statemachine`` class (its state in ``status``),
94
+ or ``Machine(cls, field=, since_field=)`` to name the field and the
95
+ datetime the engine stamps when the record enters a state.
96
+ machines: Several state machines, by name, each a ``Machine`` with its
97
+ own field (an invoice's ``approval`` and ``payment``). Instead of
98
+ ``state_machine``; transition names are unique across them.
99
+ transition_schemas: Optional input schema per transition event.
100
+ actions: ``Action`` subclasses exposed by this resource.
101
+ listing: ``Listing(filterable=, sortable=, max_page_size=)``.
102
+ documents: ``DocumentSlot`` declarations (files attached to entities).
103
+ access: ``Access(tenant_field=, restricted_fields=, wildcards=)``: tenancy,
104
+ fields that need an explicit grant, and whether wildcard grants match.
105
+ concurrency: ``Versioned(field, required=)`` for optimistic concurrency.
106
+ audit: ``False`` leaves the resource out of the audit trail;
107
+ ``Audited(reads=, exclude=)`` also audits reads or hides values.
108
+ events: Domain events (``DomainEvent`` dataclasses) that the resource's
109
+ actions and hooks record with ``ctx.record_event``. The engine's own
110
+ events (created, updated, transitions...) are implicit. Listed in the
111
+ generated docs and the AsyncAPI document; ``check`` flags undeclared
112
+ ones (RE-C006).
113
+ references: Fields holding ids of other resources' records:
114
+ ``{"customer_id": Reference("customers")}``. Integrity on writes,
115
+ ``on_delete`` behaviour, ``expand`` and related filters (see
116
+ docs/relationships.md).
117
+ internal: What only code runs (the manager, processes, jobs), not
118
+ offered by entry adapters (HTTP, GraphQL, MCP): a list of CRUD
119
+ operations, or ``Internal(operations=, transitions=True)`` to keep
120
+ the transitions internal too.
121
+ timers: ``Timer`` deadlines: transitions run by the worker once a record
122
+ has waited long enough in a state (see docs/timers.md).
123
+ link: On a join resource, the two reference fields it links
124
+ (``("invoice_id", "tag_id")``): invoices get a ``tags`` relation and
125
+ tags an ``invoices`` one (many-to-many). ``Link("invoice_id", "tag_id",
126
+ names={"invoice_id": "labels"})`` names those relations.
127
+ discriminator: On a base resource with subtypes (``requests``): the
128
+ field holding each record's subtype. The base lists and reads every
129
+ type and runs its state machines and actions on them; records are
130
+ created, updated and deleted through the subtypes (see
131
+ docs/polymorphism.md).
132
+ extends: On a subtype: the base resource class, or
133
+ ``Subtype(Base, identity="...")`` for its value in the discriminator
134
+ field (default: its name). The subtype's model subclasses the base
135
+ model, its read schema includes the base's fields, and it shares the
136
+ base's ids, tenancy, versioning, state machines and CRUD hooks.
137
+ caching: ``Cached(ttl=, control=)``: records kept by the manager's cache,
138
+ and the ``Cache-Control`` of HTTP ``GET`` answers.
139
+ view: A read-only resource computed by a query: an ``Aggregate`` over
140
+ another resource (computed by every storage adapter), or ``True``
141
+ for a custom view the storage adapter defines (see docs/views.md).
142
+ """
143
+
144
+ name: ClassVar[str | None] = None
145
+ model: ClassVar[type[Any]]
146
+ id_field: ClassVar[str] = "id"
147
+ id_type: ClassVar[type[Any]] = int
148
+ schemas: ClassVar[Mapping[str, type[BaseModel]]] = {}
149
+ operations: ClassVar[Sequence[str]] = ()
150
+ operation_docs: ClassVar[Mapping[str, str]] = {}
151
+ hooks: ClassVar[Mapping[str | HookPoint, Hook | Sequence[Hook]] | Sequence[Any]] = ()
152
+ state_machine: ClassVar[type[StateMachine] | Machine | None] = None
153
+ machines: ClassVar[Mapping[str, Machine]] = {}
154
+ transition_schemas: ClassVar[Mapping[str, type[BaseModel]]] = {}
155
+ actions: ClassVar[Sequence[type[Action]]] = ()
156
+ listing: ClassVar[Listing] = Listing()
157
+ documents: ClassVar[Sequence[DocumentSlot]] = ()
158
+ access: ClassVar[Access] = Access()
159
+ concurrency: ClassVar[Versioned | None] = None
160
+ audit: ClassVar[bool | Audited] = True
161
+ events: ClassVar[Sequence[type[DomainEvent]]] = ()
162
+ references: ClassVar[Mapping[str, Reference]] = {}
163
+ link: ClassVar[Sequence[str] | Link | None] = None
164
+ timers: ClassVar[Sequence[Timer]] = ()
165
+ internal: ClassVar[Internal | Sequence[str]] = Internal()
166
+ discriminator: ClassVar[str | None] = None
167
+ extends: ClassVar[type[Resource] | Subtype | None] = None
168
+ view: ClassVar[Aggregate | bool | None] = None
169
+ caching: ClassVar[Cached] = Cached()
170
+ #: Fields holding one text per language (``{locale: text}``), read and
171
+ #: written in the request's language (``resource_engine.translatable``);
172
+ #: ``Translatable("name", default_locale="ca")`` names their language.
173
+ translatable: ClassVar[Sequence[str] | Translatable] = ()
174
+ #: Older API versions still served, by name (``"v1"``), each with its
175
+ #: schemas and converters (``resource_engine.versions.ApiVersion``).
176
+ api_versions: ClassVar[Mapping[str, ApiVersion]] = {}
177
+ #: The whole resource is on its way out (``resource_engine.versions.Deprecation``).
178
+ deprecation: ClassVar[Deprecation | None] = None
179
+ #: Documents rendered from a record on request and downloaded without
180
+ #: being stored, by name (``resource_engine.generation.Printout``):
181
+ #: ``GET /invoices/7/printouts/invoice?format=pdf``.
182
+ printouts: ClassVar[Mapping[str, Printout]] = {}
183
+
184
+ # --- Mapping between schemas and entities. Override when needed. ---
185
+
186
+ @classmethod
187
+ def build_entity(cls, data: BaseModel, ctx: OperationContext) -> Any:
188
+ """Build a new entity from validated ``create`` input."""
189
+ values = data.model_dump()
190
+ definition = cls.definition()
191
+ if definition.translatable:
192
+ from resource_engine.translatable import merge, write_locale
193
+
194
+ locale = write_locale(definition.default_locale)
195
+ for name in definition.translatable:
196
+ text = values.pop(name, None)
197
+ translations = values.pop(f"{name}_translations", None)
198
+ values[name] = merge({}, text, translations, locale)
199
+ return cls.model(**values)
200
+
201
+ @classmethod
202
+ def apply_update(cls, entity: Any, data: BaseModel, ctx: OperationContext) -> None:
203
+ """Apply validated ``update`` input to an entity (only fields actually sent)."""
204
+ definition = cls.definition()
205
+ protected = {cls.id_field, definition.version_field, *definition.state_fields}
206
+ values = data.model_dump(exclude_unset=True)
207
+ if definition.translatable:
208
+ from resource_engine.translatable import merge, write_locale
209
+
210
+ locale = write_locale(definition.default_locale)
211
+ for name in definition.translatable:
212
+ if name in values or f"{name}_translations" in values:
213
+ text = values.pop(name, None)
214
+ translations = values.pop(f"{name}_translations", None)
215
+ setattr(entity, name, merge(getattr(entity, name), text, translations, locale))
216
+ for key, value in values.items():
217
+ if key not in protected:
218
+ setattr(entity, key, value)
219
+
220
+ @classmethod
221
+ def to_read(cls, entity: Any, ctx: OperationContext) -> Any:
222
+ """Convert an entity into the ``read`` schema."""
223
+ read = cls.schemas["read"]
224
+ definition = cls.definition()
225
+ if not definition.translatable:
226
+ return read.model_validate(entity, from_attributes=True)
227
+ from resource_engine.translatable import locale_chain, localise
228
+
229
+ chain = locale_chain(definition.default_locale)
230
+ values = {}
231
+ for name in read.model_fields:
232
+ base = name.removesuffix("_translations")
233
+ if name != base and base in definition.translatable:
234
+ values[name] = dict(getattr(entity, base, None) or {})
235
+ elif name in definition.translatable:
236
+ values[name] = localise(getattr(entity, name, None), chain)
237
+ elif hasattr(entity, name):
238
+ values[name] = getattr(entity, name)
239
+ return read.model_validate(values)
240
+
241
+ # --- Definition ---
242
+
243
+ @classmethod
244
+ def definition(cls) -> ResourceDefinition:
245
+ """The validated definition of this resource, built once."""
246
+ cached = cls.__dict__.get("_definition")
247
+ if cached is None:
248
+ cached = ResourceDefinition.from_resource(cls)
249
+ cls._definition = cached # type: ignore[attr-defined]
250
+ return cached
251
+
252
+
253
+ @dataclass(frozen=True)
254
+ class ActionDefinition:
255
+ """A validated action of a resource: its class, input and output schemas, and whether it runs on
256
+ a record."""
257
+
258
+ name: str
259
+ action_cls: type[Action]
260
+ input_schema: type[BaseModel] | None
261
+ output_schema: type[BaseModel] | None
262
+ instance: bool
263
+ description: str | None
264
+
265
+
266
+ @dataclass(frozen=True)
267
+ class ResourceDefinition:
268
+ """Validated, normalised form of a ``Resource`` subclass."""
269
+
270
+ name: str
271
+ resource_cls: type[Resource]
272
+ model: type[Any]
273
+ id_field: str
274
+ id_type: type[Any]
275
+ schemas: Mapping[str, type[BaseModel]]
276
+ operations: tuple[str, ...]
277
+ operation_docs: Mapping[str, str]
278
+ hooks: Mapping[HookKey, tuple[Hook, ...]]
279
+ state_machine: type[StateMachine] | None
280
+ state_field: str | None
281
+ transition_schemas: Mapping[str, type[BaseModel]]
282
+ actions: Mapping[str, ActionDefinition]
283
+ filterable: tuple[str, ...]
284
+ sortable: tuple[str, ...]
285
+ max_page_size: int
286
+ description: str | None
287
+ document_slots: Mapping[str, DocumentSlot]
288
+ expose_transitions: bool
289
+ restricted_fields: tuple[str, ...]
290
+ tenant_field: str | None
291
+ version_field: str | None
292
+ require_version: bool
293
+ events: tuple[type[DomainEvent], ...]
294
+ references: Mapping[str, ReferenceDefinition]
295
+ link: tuple[str, str] | None
296
+ link_names: Mapping[str, str]
297
+ state_since_field: str | None
298
+ timers: tuple[TimerDefinition, ...]
299
+ internal_operations: tuple[str, ...]
300
+ dispatcher: HookDispatcher = field(repr=False, compare=False)
301
+ #: The first (or only) machine; ``machines`` has them all, by name.
302
+ machine: MachineRunner | None = field(repr=False, compare=False)
303
+ machines: Mapping[str, MachineRunner] = field(default_factory=dict, repr=False, compare=False)
304
+ discriminator: str | None = None
305
+ identity: str | None = None
306
+ view: Aggregate | bool | None = None
307
+ cache_ttl: float | None = None
308
+ cache_control: str | None = None
309
+ #: Wildcard grants (``*:list``) match this resource's actions.
310
+ authz_wildcards: bool = True
311
+ #: The resource is in the audit trail; ``audit_reads`` also records reads.
312
+ audited: bool = True
313
+ audit_reads: bool = False
314
+ audit_exclude: tuple[str, ...] = ()
315
+ #: Text fields ``search`` looks in.
316
+ searchable: tuple[str, ...] = ()
317
+ #: Fields holding one text per language, and their default language.
318
+ translatable: tuple[str, ...] = ()
319
+ default_locale: str | None = None
320
+ #: The base resource's definition, on a subtype.
321
+ parent: ResourceDefinition | None = field(default=None, repr=False, compare=False)
322
+
323
+ def enabled(self, operation: str) -> bool:
324
+ """Whether ``operation`` is exposed."""
325
+ return operation in self.operations
326
+
327
+ def exposed(self, operation: str) -> bool:
328
+ """Enabled and offered by entry adapters (not an internal operation)."""
329
+ return operation in self.operations and operation not in self.internal_operations
330
+
331
+ @property
332
+ def transitions(self) -> tuple[str, ...]:
333
+ """Every machine's transition events, in declaration order."""
334
+ return tuple(e for m in self.machines.values() for e in m.info.events)
335
+
336
+ @property
337
+ def record_machines(self) -> Mapping[str, MachineRunner]:
338
+ """The machines a record of this resource has: a subtype's are its base's."""
339
+ return self.parent.machines if self.parent is not None else self.machines
340
+
341
+ @property
342
+ def state_fields(self) -> tuple[str, ...]:
343
+ """The fields holding the states of the record's machines."""
344
+ return tuple(m.state_field for m in self.record_machines.values())
345
+
346
+ @property
347
+ def family(self) -> str:
348
+ """The resource whose table holds the records: the base for a subtype."""
349
+ return self.parent.name if self.parent is not None else self.name
350
+
351
+ def machine_for(self, event: str) -> MachineRunner | None:
352
+ """The machine that has the transition ``event``."""
353
+ return next((m for m in self.machines.values() if event in m.info.events), None)
354
+
355
+ @classmethod
356
+ def from_resource(cls, resource_cls: type[Resource]) -> ResourceDefinition:
357
+ """Validate and normalise a ``Resource`` subclass. Raises ``ConfigurationError`` saying what
358
+ is wrong."""
359
+ owner = resource_cls.__qualname__
360
+ model = getattr(resource_cls, "model", None)
361
+ if model is None:
362
+ raise ConfigurationError(
363
+ f"{owner} does not declare 'model'",
364
+ hint="Set `model = <domain entity class>` on the resource.",
365
+ doc="docs/resources.md#declaring-a-resource",
366
+ )
367
+ name = resource_cls.name or _default_name(resource_cls.__name__)
368
+ listing, access, versioned, caching, audit = _settings(owner, resource_cls)
369
+ internal_spec, translatable = _shapes(owner, resource_cls)
370
+ base_cls, identity = _subtype(owner, resource_cls)
371
+ parent = _parent(owner, resource_cls, base_cls, model)
372
+
373
+ operations = tuple(resource_cls.operations)
374
+ unknown = [op for op in operations if op not in CRUD_OPERATIONS]
375
+ if unknown:
376
+ raise ConfigurationError(
377
+ f"{owner} enables unknown operations {unknown}",
378
+ hint=f"CRUD operations are {', '.join(CRUD_OPERATIONS)}. "
379
+ "Business operations must be Actions or state transitions.",
380
+ doc="docs/resources.md#operations",
381
+ )
382
+
383
+ schemas = dict(resource_cls.schemas)
384
+ for op in operations:
385
+ for role in _REQUIRED_SCHEMAS[op]:
386
+ schema = schemas.get(role)
387
+ if schema is None:
388
+ raise ConfigurationError(
389
+ f"{owner} enables '{op}' but has no '{role}' schema",
390
+ hint=f'Add `schemas = {{"{role}": <PydanticModel>, ...}}`.',
391
+ doc="docs/resources.md#schemas",
392
+ )
393
+ if not (inspect.isclass(schema) and issubclass(schema, BaseModel)):
394
+ raise ConfigurationError(f"{owner}: schema '{role}' must be a Pydantic model")
395
+
396
+ if parent is not None and (
397
+ resource_cls.state_machine
398
+ or resource_cls.machines
399
+ or resource_cls.timers
400
+ or resource_cls.transition_schemas
401
+ ):
402
+ raise ConfigurationError(
403
+ f"{owner}: state machines, timers and transitions of a subtype belong to "
404
+ f"its base {parent.name!r}",
405
+ hint="Declare them on the base resource; they run on every subtype's records.",
406
+ doc="docs/polymorphism.md",
407
+ )
408
+ runners = _machines(owner, name, resource_cls, schemas)
409
+ machine = next(iter(runners.values()), None)
410
+ sm = machine.machine_cls if machine else None
411
+ state_field = machine.state_field if machine else None
412
+ events_of = {e: r for r in runners.values() for e in r.info.events}
413
+
414
+ transition_schemas = dict(resource_cls.transition_schemas)
415
+ if transition_schemas and machine is None:
416
+ raise ConfigurationError(f"{owner} declares transition_schemas without a state_machine")
417
+ for event in transition_schemas:
418
+ if machine and event not in events_of:
419
+ raise ConfigurationError(
420
+ f"{owner}: transition_schemas references unknown transition {event!r}",
421
+ hint=f"Known transitions: {', '.join(events_of)}",
422
+ )
423
+
424
+ actions: dict[str, ActionDefinition] = {}
425
+ for action_cls in resource_cls.actions:
426
+ if not (inspect.isclass(action_cls) and issubclass(action_cls, Action)):
427
+ raise ConfigurationError(f"{owner}: {action_cls!r} is not an Action subclass")
428
+ action_name = action_cls.action_name()
429
+ if action_name in actions:
430
+ raise ConfigurationError(f"{owner}: duplicate action name {action_name!r}")
431
+ actions[action_name] = ActionDefinition(
432
+ name=action_name,
433
+ action_cls=action_cls,
434
+ input_schema=action_cls.input_schema,
435
+ output_schema=action_cls.output_schema,
436
+ instance=action_cls.instance,
437
+ description=inspect.getdoc(action_cls),
438
+ )
439
+
440
+ slots: dict[str, DocumentSlot] = {}
441
+ for slot in resource_cls.documents:
442
+ if not isinstance(slot, DocumentSlot):
443
+ raise ConfigurationError(f"{owner}: documents must contain DocumentSlot objects")
444
+ problems = slot.problems()
445
+ if slot.name in slots:
446
+ problems.append(f"duplicate slot {slot.name!r}")
447
+ for event in slot.required_for:
448
+ if machine is None or event not in machine.info.events:
449
+ problems.append(f"slot {slot.name!r} requires unknown transition {event!r}")
450
+ if problems:
451
+ raise ConfigurationError(
452
+ f"{owner}: invalid document slots: {'; '.join(problems)}",
453
+ doc="docs/documents.md#slots",
454
+ )
455
+ slots[slot.name] = slot
456
+
457
+ hooks = normalize_hooks(resource_cls.hooks, owner=owner)
458
+ for key in hooks:
459
+ if key.qualifier is None:
460
+ continue
461
+ if key.point in (HookPoint.BEFORE_TRANSITION, HookPoint.AFTER_TRANSITION):
462
+ known: tuple[str, ...] = machine.info.events if machine else ()
463
+ elif key.point in (
464
+ HookPoint.BEFORE_ATTACH,
465
+ HookPoint.AFTER_ATTACH,
466
+ HookPoint.BEFORE_DETACH,
467
+ HookPoint.AFTER_DETACH,
468
+ ):
469
+ known = tuple(slots)
470
+ else:
471
+ known = tuple(actions)
472
+ if key.qualifier not in known:
473
+ raise ConfigurationError(
474
+ f"{owner}: hook {str(key)!r} references unknown {key.qualifier!r}",
475
+ hint=f"Known names: {', '.join(known) or '(none)'}",
476
+ )
477
+
478
+ read_fields = schemas["read"].model_fields if "read" in schemas else {}
479
+ for fld in listing.searchable:
480
+ annotation = read_fields[fld].annotation if fld in read_fields else None
481
+ if annotation is None or not _is_text(annotation):
482
+ raise ConfigurationError(
483
+ f"{owner}: searchable field {fld!r} must be a text field of the read schema",
484
+ doc="docs/resources.md#settings",
485
+ )
486
+ if fld in translatable.fields:
487
+ raise ConfigurationError(
488
+ f"{owner}: searchable field {fld!r} is translatable; search looks in "
489
+ "plain text fields",
490
+ doc="docs/resources.md#settings",
491
+ )
492
+ for attr in ("filterable", "sortable"):
493
+ for fld in getattr(listing, attr):
494
+ if read_fields and fld not in read_fields:
495
+ raise ConfigurationError(
496
+ f"{owner}: {attr} field {fld!r} is not part of the read schema"
497
+ )
498
+
499
+ known_fields = set(read_fields)
500
+ for role in ("create", "update"):
501
+ if role in schemas:
502
+ known_fields |= set(schemas[role].model_fields)
503
+ tenant_field = _inherited(owner, "tenant_field", access.tenant_field, parent)
504
+ if tenant_field is not None:
505
+ if tenant_field == resource_cls.id_field:
506
+ raise ConfigurationError(f"{owner}: the id field cannot be the tenant field")
507
+ if read_fields and tenant_field not in read_fields:
508
+ raise ConfigurationError(
509
+ f"{owner}: tenant field {tenant_field!r} is not part of the read schema"
510
+ )
511
+ if "update" in schemas and tenant_field in schemas["update"].model_fields:
512
+ raise ConfigurationError(
513
+ f"{owner}: the update schema must not contain the tenant field "
514
+ f"{tenant_field!r}",
515
+ hint="Records never move between tenants.",
516
+ doc="docs/tenancy.md",
517
+ )
518
+ version_field = _inherited(
519
+ owner, "version_field", versioned.field if versioned else None, parent
520
+ )
521
+ if version_field is not None:
522
+ reserved = {
523
+ resource_cls.id_field: "id",
524
+ state_field: "state",
525
+ tenant_field: "tenant",
526
+ }
527
+ if version_field in reserved:
528
+ raise ConfigurationError(
529
+ f"{owner}: the {reserved[version_field]} field cannot be the version field"
530
+ )
531
+ if read_fields and version_field not in read_fields:
532
+ raise ConfigurationError(
533
+ f"{owner}: version field {version_field!r} is not part of the read schema",
534
+ hint="Expose it so clients can send it back (ETag / If-Match).",
535
+ doc="docs/concurrency.md",
536
+ )
537
+ if "create" in schemas and version_field in schemas["create"].model_fields:
538
+ raise ConfigurationError(
539
+ f"{owner}: the create schema must not contain the version field "
540
+ f"{version_field!r}",
541
+ hint="New records start at version 1.",
542
+ doc="docs/concurrency.md",
543
+ )
544
+ for fld in audit.exclude if audit else ():
545
+ if fld not in known_fields:
546
+ raise ConfigurationError(
547
+ f"{owner}: audit exclude field {fld!r} is not part of the read or write schemas"
548
+ )
549
+ for fld in access.restricted_fields:
550
+ if fld == resource_cls.id_field:
551
+ raise ConfigurationError(f"{owner}: the id field cannot be restricted")
552
+ if fld not in known_fields:
553
+ raise ConfigurationError(
554
+ f"{owner}: restricted field {fld!r} is not part of the read or write schemas"
555
+ )
556
+
557
+ events = tuple(resource_cls.events)
558
+ for declared in events:
559
+ if not (
560
+ isinstance(declared, type)
561
+ and issubclass(declared, DomainEvent)
562
+ and dataclasses.is_dataclass(declared)
563
+ ):
564
+ raise ConfigurationError(
565
+ f"{owner}: events must be DomainEvent dataclasses, not {declared!r}",
566
+ hint="Declare `@dataclass(frozen=True, kw_only=True) class X(DomainEvent)`.",
567
+ doc="docs/messaging.md#declaring-events",
568
+ )
569
+ if len({e.__name__ for e in events}) != len(events):
570
+ raise ConfigurationError(
571
+ f"{owner}: two declared events share a class name",
572
+ hint="The class name is the event type on the wire; rename one.",
573
+ doc="docs/messaging.md#declaring-events",
574
+ )
575
+
576
+ internal = tuple(internal_spec.operations)
577
+ if set(internal) - set(operations):
578
+ raise ConfigurationError(
579
+ f"{owner}: internal operations {sorted(set(internal) - set(operations))} "
580
+ "are not enabled operations",
581
+ hint="List them in operations too; internal ones are only hidden from adapters.",
582
+ )
583
+ for runner in runners.values():
584
+ _check_since_field(owner, runner.since_field, schemas, known_fields)
585
+ since_field = machine.since_field if machine else None
586
+ timers = normalize_timers(
587
+ owner,
588
+ name,
589
+ resource_cls.timers,
590
+ machines=runners,
591
+ transition_schemas=transition_schemas,
592
+ known_fields=known_fields,
593
+ )
594
+ references = normalize_references(name, owner, resource_cls.references, known_fields)
595
+ link, link_names = normalize_link(owner, resource_cls.link, references)
596
+ description = resource_cls.__doc__ and inspect.cleandoc(resource_cls.__doc__)
597
+ discriminator = _check_family(owner, resource_cls, parent, schemas, operations)
598
+ if resource_cls.view is not None:
599
+ _check_view_resource(
600
+ owner, resource_cls, operations, runners, actions, slots, version_field, base_cls
601
+ )
602
+ check_view(
603
+ owner,
604
+ set(read_fields),
605
+ resource_cls.id_field,
606
+ resource_cls.view,
607
+ )
608
+ if parent is not None:
609
+ hooks = _merge_hooks(parent.hooks, hooks)
610
+ return cls(
611
+ name=name,
612
+ resource_cls=resource_cls,
613
+ model=model,
614
+ id_field=parent.id_field if parent else resource_cls.id_field,
615
+ id_type=parent.id_type if parent else resource_cls.id_type,
616
+ schemas=schemas,
617
+ operations=operations,
618
+ operation_docs=dict(resource_cls.operation_docs),
619
+ hooks=hooks,
620
+ state_machine=sm,
621
+ state_field=state_field,
622
+ transition_schemas=transition_schemas,
623
+ actions=actions,
624
+ filterable=tuple(
625
+ dict.fromkeys([*listing.filterable, *([discriminator] if discriminator else [])])
626
+ ),
627
+ sortable=tuple(listing.sortable),
628
+ max_page_size=listing.max_page_size,
629
+ description=description or None,
630
+ document_slots=slots,
631
+ expose_transitions=not internal_spec.transitions,
632
+ restricted_fields=tuple(access.restricted_fields),
633
+ tenant_field=tenant_field,
634
+ version_field=version_field,
635
+ require_version=(
636
+ parent.require_version if parent else bool(versioned and versioned.required)
637
+ ),
638
+ events=events,
639
+ references=references,
640
+ link=link,
641
+ link_names=link_names,
642
+ state_since_field=since_field,
643
+ timers=timers,
644
+ internal_operations=internal,
645
+ dispatcher=HookDispatcher(hooks),
646
+ machine=machine,
647
+ machines=runners,
648
+ discriminator=discriminator,
649
+ identity=(identity or name) if parent else None,
650
+ parent=parent,
651
+ view=resource_cls.view,
652
+ cache_ttl=_cache_ttl(owner, caching.ttl),
653
+ cache_control=caching.control,
654
+ authz_wildcards=access.wildcards,
655
+ audited=audit is not None,
656
+ audit_reads=bool(audit and audit.reads),
657
+ audit_exclude=tuple(audit.exclude) if audit else (),
658
+ translatable=tuple(translatable.fields),
659
+ default_locale=translatable.default_locale,
660
+ searchable=tuple(listing.searchable),
661
+ )
662
+
663
+
664
+ def _is_text(annotation: Any) -> bool:
665
+ """``str``, or ``str | None``."""
666
+ import types
667
+ import typing
668
+
669
+ if annotation is str:
670
+ return True
671
+ args = typing.get_args(annotation)
672
+ is_union = typing.get_origin(annotation) in (typing.Union, types.UnionType)
673
+ return is_union and str in args and all(a in (str, type(None)) for a in args)
674
+
675
+
676
+ def _shapes(owner: str, resource_cls: type[Resource]) -> tuple[Internal, Translatable]:
677
+ """``internal`` and ``translatable`` in their full form (short forms are lists)."""
678
+ internal = resource_cls.internal
679
+ if not isinstance(internal, Internal):
680
+ if isinstance(internal, str) or not isinstance(internal, Sequence):
681
+ raise ConfigurationError(
682
+ f"{owner}: internal must be a list of operations or Internal(...), "
683
+ f"not {internal!r}",
684
+ doc="docs/resources.md#operations",
685
+ )
686
+ internal = Internal(operations=tuple(internal))
687
+ translatable = resource_cls.translatable
688
+ if not isinstance(translatable, Translatable):
689
+ if isinstance(translatable, str) or not isinstance(translatable, Sequence):
690
+ raise ConfigurationError(
691
+ f"{owner}: translatable must be a list of fields or Translatable(...), "
692
+ f"not {translatable!r}",
693
+ doc="docs/i18n.md",
694
+ )
695
+ translatable = Translatable(*translatable)
696
+ return internal, translatable
697
+
698
+
699
+ def _subtype(owner: str, resource_cls: type[Resource]) -> tuple[Any, str | None]:
700
+ """``extends`` as the base class and the subtype's identity."""
701
+ extends = resource_cls.extends
702
+ if isinstance(extends, Subtype):
703
+ return extends.base, extends.identity
704
+ return extends, None
705
+
706
+
707
+ def _settings(
708
+ owner: str, resource_cls: type[Resource]
709
+ ) -> tuple[Listing, Access, Versioned | None, Cached, Audited | None]:
710
+ """The grouped settings, checked; ``None`` audit: left out of the trail."""
711
+ moved = [attr for attr in MOVED if hasattr(resource_cls, attr)]
712
+ if moved:
713
+ raise ConfigurationError(
714
+ f"{owner} sets {', '.join(moved)}, which moved into grouped settings",
715
+ hint="Use " + "; ".join(MOVED[attr] for attr in moved) + ".",
716
+ doc="docs/resources.md#settings",
717
+ )
718
+ groups: tuple[tuple[str, Any, type | tuple[type, ...]], ...] = (
719
+ ("listing", resource_cls.listing, Listing),
720
+ ("access", resource_cls.access, Access),
721
+ ("concurrency", resource_cls.concurrency, (Versioned, type(None))),
722
+ ("caching", resource_cls.caching, Cached),
723
+ ("audit", resource_cls.audit, (bool, Audited)),
724
+ )
725
+ for attr, value, expected in groups:
726
+ if not isinstance(value, expected):
727
+ names = expected if isinstance(expected, tuple) else (expected,)
728
+ raise ConfigurationError(
729
+ f"{owner}: {attr} must be "
730
+ + " or ".join("None" if t is type(None) else t.__name__ for t in names)
731
+ + f", not {value!r}",
732
+ doc="docs/resources.md#settings",
733
+ )
734
+ if resource_cls.listing.max_page_size < 1:
735
+ raise ConfigurationError(f"{owner}: max_page_size must be at least 1")
736
+ audit = resource_cls.audit
737
+ audited = Audited() if audit is True else (audit or None)
738
+ return (
739
+ resource_cls.listing,
740
+ resource_cls.access,
741
+ resource_cls.concurrency,
742
+ resource_cls.caching,
743
+ audited,
744
+ )
745
+
746
+
747
+ def _machines(
748
+ owner: str, name: str, resource_cls: type[Resource], schemas: Mapping[str, type[BaseModel]]
749
+ ) -> dict[str, MachineRunner]:
750
+ """``machines`` (or the ``state_machine`` shorthand) as runners, validated."""
751
+ declared = dict(resource_cls.machines)
752
+ sm = resource_cls.state_machine
753
+ single = sm if isinstance(sm, Machine) else Machine(sm) if sm is not None else None
754
+ if declared and sm is not None:
755
+ raise ConfigurationError(
756
+ f"{owner} declares both state_machine and machines",
757
+ hint="Use machines for several; state_machine is the shorthand for one.",
758
+ doc="docs/state-machines.md#several-machines",
759
+ )
760
+ if single is not None:
761
+ declared = {single.field: single}
762
+ runners: dict[str, MachineRunner] = {}
763
+ seen_fields: dict[str, str] = {}
764
+ seen_events: dict[str, str] = {}
765
+ for machine_name, spec in declared.items():
766
+ where = f"{owner} machine {machine_name!r}"
767
+ if not isinstance(spec, Machine):
768
+ raise ConfigurationError(f"{where}: use Machine(<StateMachine class>, field=...)")
769
+ if not (inspect.isclass(spec.machine) and issubclass(spec.machine, StateMachine)):
770
+ raise ConfigurationError(
771
+ f"{where}: state_machine must be a python-statemachine StateMachine subclass"
772
+ )
773
+ for used, other in ((spec.field, seen_fields), (spec.since_field, seen_fields)):
774
+ if used is not None and used in other:
775
+ raise ConfigurationError(
776
+ f"{where}: field {used!r} is already used by machine {other[used]!r}",
777
+ doc="docs/state-machines.md#several-machines",
778
+ )
779
+ if used is not None:
780
+ other[used] = machine_name
781
+ for role in ("create", "update"):
782
+ schema = schemas.get(role)
783
+ if schema is not None and spec.field in schema.model_fields:
784
+ raise StateFieldExposed(
785
+ f"{owner}: the state field {spec.field!r} is part of the "
786
+ f"'{role}' schema {schema.__name__}",
787
+ hint="Remove it from the schema. State changes only through "
788
+ "transitions (POST /{id}/transitions/<event>).",
789
+ doc="docs/state-machines.md#protected-state",
790
+ )
791
+ runner = MachineRunner(
792
+ spec.machine, spec.field, name, name=machine_name, since_field=spec.since_field
793
+ )
794
+ for event in runner.info.events:
795
+ if event in seen_events:
796
+ raise ConfigurationError(
797
+ f"{owner}: transition {event!r} is in machines {seen_events[event]!r} "
798
+ f"and {machine_name!r}",
799
+ hint="Transition names are unique per resource (routes, permissions "
800
+ "and GraphQL use them alone); rename one.",
801
+ doc="docs/state-machines.md#several-machines",
802
+ )
803
+ seen_events[event] = machine_name
804
+ runners[machine_name] = runner
805
+ return runners
806
+
807
+
808
+ def _check_since_field(
809
+ owner: str,
810
+ since_field: str | None,
811
+ schemas: Mapping[str, type[BaseModel]],
812
+ known_fields: set[str],
813
+ ) -> None:
814
+ if since_field is None:
815
+ return
816
+ if since_field not in known_fields:
817
+ raise ConfigurationError(
818
+ f"{owner}: the since field {since_field!r} is not part of the read schema",
819
+ doc="docs/timers.md",
820
+ )
821
+ for role in ("create", "update"):
822
+ if role in schemas and since_field in schemas[role].model_fields:
823
+ raise ConfigurationError(
824
+ f"{owner}: the since field {since_field!r} is part of the {role!r} "
825
+ "schema; the engine sets it",
826
+ doc="docs/timers.md",
827
+ )
828
+
829
+
830
+ def _parent(
831
+ owner: str, resource_cls: type[Resource], base: Any, model: Any
832
+ ) -> ResourceDefinition | None:
833
+ """A subtype's base definition (``extends``), validated."""
834
+ if base is None:
835
+ return None
836
+ if not (inspect.isclass(base) and issubclass(base, Resource)):
837
+ raise ConfigurationError(f"{owner}: extends must be a Resource class, not {base!r}")
838
+ parent = base.definition()
839
+ if parent.discriminator is None:
840
+ raise ConfigurationError(
841
+ f"{owner} extends {parent.name!r}, which has no discriminator",
842
+ hint='Set `discriminator = "type"` on the base resource.',
843
+ doc="docs/polymorphism.md",
844
+ )
845
+ if parent.parent is not None:
846
+ raise ConfigurationError(
847
+ f"{owner}: {parent.name!r} is itself a subtype; one level of subtypes only",
848
+ doc="docs/polymorphism.md",
849
+ )
850
+ if resource_cls.discriminator is not None:
851
+ raise ConfigurationError(f"{owner}: a subtype has no discriminator of its own")
852
+ if not (inspect.isclass(model) and issubclass(model, parent.model)):
853
+ raise ConfigurationError(
854
+ f"{owner}: the model {getattr(model, '__name__', model)!r} must subclass the "
855
+ f"base model {parent.model.__name__!r}",
856
+ hint="Subtype records are base records with more fields.",
857
+ doc="docs/polymorphism.md",
858
+ )
859
+ return parent
860
+
861
+
862
+ def _inherited(owner: str, attr: str, own: Any, parent: ResourceDefinition | None) -> Any:
863
+ """Tenancy and versioning are the base's: a subtype may repeat them, not change them."""
864
+ if parent is None:
865
+ return own
866
+ theirs = getattr(parent, attr)
867
+ if own is not None and own != theirs:
868
+ raise ConfigurationError(
869
+ f"{owner}: {attr} {own!r} differs from the base's ({theirs!r})",
870
+ hint="Subtypes share the base's records: leave it unset.",
871
+ doc="docs/polymorphism.md",
872
+ )
873
+ return theirs
874
+
875
+
876
+ def _check_family(
877
+ owner: str,
878
+ resource_cls: type[Resource],
879
+ parent: ResourceDefinition | None,
880
+ schemas: Mapping[str, type[BaseModel]],
881
+ operations: tuple[str, ...],
882
+ ) -> str | None:
883
+ """Rules of bases and subtypes; returns the discriminator of a base."""
884
+ discriminator = resource_cls.discriminator
885
+ read = schemas.get("read")
886
+ if discriminator is not None:
887
+ writes = [op for op in operations if op not in ("list", "get")]
888
+ if writes:
889
+ raise ConfigurationError(
890
+ f"{owner}: a base resource only lists and reads; {', '.join(writes)} run on "
891
+ "its subtypes",
892
+ hint="Declare those operations on each subtype (extends = this resource).",
893
+ doc="docs/polymorphism.md",
894
+ )
895
+ if read is None or discriminator not in read.model_fields:
896
+ raise ConfigurationError(
897
+ f"{owner}: the discriminator {discriminator!r} is not part of the read schema",
898
+ doc="docs/polymorphism.md",
899
+ )
900
+ return discriminator
901
+ if parent is None:
902
+ return None
903
+ base_read = parent.schemas.get("read")
904
+ if read is not None and base_read is not None:
905
+ missing = [f for f in base_read.model_fields if f not in read.model_fields]
906
+ if missing:
907
+ raise ConfigurationError(
908
+ f"{owner}: the read schema lacks the base's fields {missing}",
909
+ hint=f"Subclass {base_read.__name__} for the subtype's read schema.",
910
+ doc="docs/polymorphism.md",
911
+ )
912
+ engine_owned: dict[str | None, str] = {
913
+ parent.id_field: "id",
914
+ parent.discriminator: "discriminator",
915
+ parent.version_field: "version",
916
+ **{f: "state" for f in parent.state_fields},
917
+ }
918
+ for role in ("create", "update"):
919
+ schema = schemas.get(role)
920
+ for fld, kind in engine_owned.items():
921
+ if fld is not None and schema is not None and fld in schema.model_fields:
922
+ raise ConfigurationError(
923
+ f"{owner}: the {kind} field {fld!r} is part of the {role!r} schema",
924
+ hint="The engine sets it.",
925
+ doc="docs/polymorphism.md",
926
+ )
927
+ return None
928
+
929
+
930
+ def _merge_hooks(
931
+ base: Mapping[HookKey, tuple[Hook, ...]], own: Mapping[HookKey, tuple[Hook, ...]]
932
+ ) -> dict[HookKey, tuple[Hook, ...]]:
933
+ """A subtype runs the base's unqualified CRUD and commit hooks first, then its own."""
934
+ shared = {
935
+ key: hooks
936
+ for key, hooks in base.items()
937
+ if key.qualifier is None
938
+ and key.point
939
+ not in (
940
+ HookPoint.BEFORE_TRANSITION,
941
+ HookPoint.AFTER_TRANSITION,
942
+ HookPoint.BEFORE_ACTION,
943
+ HookPoint.AFTER_ACTION,
944
+ )
945
+ }
946
+ merged = dict(shared)
947
+ for key, hooks in own.items():
948
+ merged[key] = (*merged.get(key, ()), *hooks)
949
+ return merged
950
+
951
+
952
+ def _check_view_resource(
953
+ owner: str,
954
+ resource_cls: type[Resource],
955
+ operations: tuple[str, ...],
956
+ runners: Mapping[str, Any],
957
+ actions: Mapping[str, Any],
958
+ slots: Mapping[str, Any],
959
+ version_field: str | None,
960
+ base: Any,
961
+ ) -> None:
962
+ """Views only list and read."""
963
+ problems = [op for op in operations if op not in ("list", "get")]
964
+ for what, present in (
965
+ ("state machines", runners),
966
+ ("actions", actions),
967
+ ("document slots", slots),
968
+ ("a version field", version_field),
969
+ ("subtypes or a base", resource_cls.discriminator or base),
970
+ ("a link", resource_cls.link),
971
+ ):
972
+ if present:
973
+ problems.append(what)
974
+ if problems:
975
+ raise ConfigurationError(
976
+ f"{owner}: a view only lists and reads; remove {', '.join(problems)}",
977
+ doc="docs/views.md",
978
+ )
979
+
980
+
981
+ def _cache_ttl(owner: str, ttl: float | None) -> float | None:
982
+ if ttl is not None and not ttl > 0:
983
+ raise ConfigurationError(f"{owner}: Cached(ttl=) must be positive seconds or None")
984
+ return ttl