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,47 @@
1
+ """The queries ``list`` takes and the pages it returns."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Mapping, Sequence
6
+ from dataclasses import dataclass, field
7
+ from typing import Any
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class ListQuery:
12
+ """Paging, filters, search and ordering for ``list`` operations.
13
+
14
+ ``filters`` keys are field names (equality) or carry an operator,
15
+ ``amount[gte]`` (see ``resource_engine.application.searching``).
16
+ ``search`` keeps records holding every word in a searchable field.
17
+ ``order_by`` items are field names; prefix with ``-`` for descending order.
18
+ ``condition`` is a row filter in the policy condition language over
19
+ ``resource.*`` (set by the engine for row-level permissions). Repositories that
20
+ apply it declare ``supports_conditions = True``; the engine refuses to list
21
+ through others when a condition is needed (RE-E705).
22
+ """
23
+
24
+ offset: int = 0
25
+ limit: int = 50
26
+ filters: Mapping[str, Any] = field(default_factory=dict)
27
+ order_by: Sequence[str] = ()
28
+ condition: Any = None
29
+ search: str | None = None
30
+ #: Translatable fields of the resource, and the languages to compare and
31
+ #: sort them in (set by the engine; see ``resource_engine.translatable``).
32
+ translatable: frozenset[str] = frozenset()
33
+ locales: Sequence[str] = ()
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class Page[T]:
38
+ """One page of a list: its items, how many records match in total, and the paging used."""
39
+
40
+ items: list[T]
41
+ total: int
42
+ offset: int
43
+ limit: int
44
+
45
+ def map[U](self, fn: Callable[[T], U]) -> Page[U]:
46
+ """The same page with ``fn`` applied to each item."""
47
+ return Page([fn(item) for item in self.items], self.total, self.offset, self.limit)
@@ -0,0 +1,137 @@
1
+ """The registry of an application's resources."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator
6
+ from typing import Any
7
+
8
+ from resource_engine.application.resource import Resource, ResourceDefinition
9
+ from resource_engine.errors import ConfigurationError, ResourceNotRegistered
10
+
11
+
12
+ class ResourceRegistry:
13
+ """The set of resources an application exposes.
14
+
15
+ ``register`` validates the definition, so configuration errors surface at
16
+ bootstrap rather than on the first request. Usable as a decorator.
17
+ """
18
+
19
+ def __init__(self) -> None:
20
+ self._definitions: dict[str, ResourceDefinition] = {}
21
+ self._engine_actions: dict[str, Any] = {}
22
+
23
+ def register_actions(self, *actions: Any) -> None:
24
+ """Permission actions not tied to a resource (``ActionInfo``), such as
25
+ the explorer's ``jobs:run``: they appear in the authorization catalogue
26
+ and the policy editor like resource actions."""
27
+ for action in actions:
28
+ self._engine_actions[action.name] = action
29
+
30
+ def engine_actions(self) -> list[Any]:
31
+ """Engine actions not tied to a resource (``register_actions``)."""
32
+ return list(self._engine_actions.values())
33
+
34
+ def event_types(self) -> list[type[Any]]:
35
+ """The domain events the registered resources declare (``Resource.events``)."""
36
+ seen: dict[str, type[Any]] = {}
37
+ for definition in self._definitions.values():
38
+ for event in definition.resource_cls.events:
39
+ seen.setdefault(event.__name__, event)
40
+ return list(seen.values())
41
+
42
+ def register[R: type[Resource]](self, resource_cls: R) -> R:
43
+ """Validate and add a resource class; returns it, so it works as a decorator."""
44
+ definition = resource_cls.definition()
45
+ if definition.parent is not None:
46
+ base = definition.parent
47
+ if self._definitions.get(base.name) is not base:
48
+ self.register(base.resource_cls) # the base comes with its subtypes
49
+ taken = self.subtypes(base.name).get(definition.identity or "")
50
+ if taken is not None and taken.resource_cls is not resource_cls:
51
+ raise ConfigurationError(
52
+ f"{definition.name} and {taken.name} both have identity "
53
+ f"{definition.identity!r} in {base.name}",
54
+ hint="Set a distinct `identity` on one of them.",
55
+ doc="docs/polymorphism.md",
56
+ )
57
+ existing = self._definitions.get(definition.name)
58
+ if existing is not None and existing.resource_cls is not resource_cls:
59
+ raise ConfigurationError(
60
+ f"Resource name {definition.name!r} is already registered by "
61
+ f"{existing.resource_cls.__qualname__}",
62
+ hint="Set a distinct `name` on one of the resources.",
63
+ )
64
+ self._definitions[definition.name] = definition
65
+ return resource_cls
66
+
67
+ def register_documents(self, resource_cls: type[Resource] | None = None) -> type[Resource]:
68
+ """Register the built-in ``DocumentResource`` (or a subclass of it)."""
69
+ from resource_engine.documents.resource import DocumentResource
70
+
71
+ return self.register(resource_cls or DocumentResource)
72
+
73
+ def register_authz(self) -> None:
74
+ """Register the permission management resources (policies, custom roles,
75
+ role assignments)."""
76
+ from resource_engine.authz.resources import (
77
+ PolicyResource,
78
+ RoleAssignmentResource,
79
+ RoleResource,
80
+ )
81
+
82
+ for resource_cls in (PolicyResource, RoleResource, RoleAssignmentResource):
83
+ self.register(resource_cls)
84
+
85
+ def register_api_keys(self) -> None:
86
+ """Register ``authz_api_keys``: keys for machine clients (docs/api-keys.md).
87
+ Needs ``register_authz`` (keys carry its roles)."""
88
+ from resource_engine.authz.apikeys import ApiKeyResource
89
+
90
+ self.register(ApiKeyResource)
91
+
92
+ def register_audit(
93
+ self, resource_cls: type[Resource] | None = None, *, seals: bool = False
94
+ ) -> type[Resource]:
95
+ """Register the built-in, read-only ``audit_log`` resource (or a subclass),
96
+ and with ``seals=True`` the ``audit_seals`` resource used by ``AuditSealer``."""
97
+ from resource_engine.audit.resource import AuditLogResource, AuditSealResource
98
+
99
+ registered = self.register(resource_cls or AuditLogResource)
100
+ if seals:
101
+ self.register(AuditSealResource)
102
+ return registered
103
+
104
+ def get(self, resource: str | type[Resource]) -> ResourceDefinition:
105
+ """The definition of a resource, by name or class. Raises ``ResourceNotRegistered``."""
106
+ name = resource if isinstance(resource, str) else resource.definition().name
107
+ try:
108
+ return self._definitions[name]
109
+ except KeyError:
110
+ raise ResourceNotRegistered(
111
+ f"Resource {name!r} is not registered",
112
+ hint=f"Registered resources: {', '.join(self._definitions) or '(none)'}",
113
+ ) from None
114
+
115
+ def subtypes(self, base: str) -> dict[str, ResourceDefinition]:
116
+ """A base resource's registered subtypes, by identity."""
117
+ return {
118
+ d.identity: d
119
+ for d in self._definitions.values()
120
+ if d.parent is not None and d.parent.name == base and d.identity is not None
121
+ }
122
+
123
+ def subtype_of(self, base: ResourceDefinition, entity: Any) -> ResourceDefinition | None:
124
+ """The subtype of a base record, from its discriminator."""
125
+ if base.discriminator is None:
126
+ return None
127
+ value = getattr(entity, base.discriminator, None)
128
+ return self.subtypes(base.name).get(value) if isinstance(value, str) else None
129
+
130
+ def __contains__(self, name: object) -> bool:
131
+ return name in self._definitions
132
+
133
+ def __iter__(self) -> Iterator[ResourceDefinition]:
134
+ return iter(self._definitions.values())
135
+
136
+ def __len__(self) -> int:
137
+ return len(self._definitions)
@@ -0,0 +1,470 @@
1
+ """References between resources: declaration, validation and serialization.
2
+
3
+ ```python
4
+ class InvoiceResource(Resource):
5
+ references = {"customer_id": Reference("customers", name="customer")}
6
+ ```
7
+
8
+ - **Integrity:** create and update check that each referenced record exists
9
+ and that the caller can see it (RE-E108).
10
+ - **Deletes:** deleting a referenced record is refused while others point to
11
+ it (``on_delete="restrict"``, RE-E109). ``set_null`` and ``cascade`` update
12
+ or delete the dependents through the manager, in the same transaction and
13
+ as the same caller.
14
+ - **Reads:** ``get``/``list`` take ``expand=("customer",)`` and attach the
15
+ related records (``None`` when the caller may not read them). ``list``
16
+ accepts ``filters={"customer.country": "ES"}`` on the related resource's
17
+ filterable fields.
18
+
19
+ See docs/relationships.md.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import types
25
+ import typing
26
+ from collections.abc import Iterable, Mapping, Sequence
27
+ from dataclasses import dataclass
28
+ from typing import TYPE_CHECKING, Any, Literal
29
+
30
+ from pydantic import BaseModel
31
+
32
+ from resource_engine.errors import ConfigurationError
33
+
34
+ if TYPE_CHECKING:
35
+ from resource_engine.application.registry import ResourceRegistry
36
+ from resource_engine.application.resource import ResourceDefinition
37
+
38
+ type OnDelete = Literal["restrict", "set_null", "cascade"]
39
+
40
+ ON_DELETE = ("restrict", "set_null", "cascade")
41
+ DOC = "docs/relationships.md"
42
+ _EXPANDED = "_re_expanded"
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class Reference:
47
+ """A field holding the id of a record of another resource.
48
+
49
+ Args:
50
+ resource: The referenced resource's name.
51
+ name: Name of the relation, used by ``expand`` and related filters
52
+ (default: the field without ``_id``: ``customer_id`` → ``customer``).
53
+ on_delete: What deleting the referenced record does to records that
54
+ point to it: ``restrict`` (refused, RE-E109), ``set_null`` (the
55
+ field is set to ``None`` through ``update``) or ``cascade`` (they
56
+ are deleted through ``delete``).
57
+ description: What the relation means, for the generated docs.
58
+ related_name: Name of the reverse relation on the referenced resource
59
+ (default: this resource's name: ``customers`` gets ``invoices``):
60
+ ``GET /customers/{id}/invoices``, ``expand=["invoices"]``.
61
+ reverse: ``False`` exposes no reverse relation.
62
+ """
63
+
64
+ resource: str
65
+ name: str | None = None
66
+ on_delete: OnDelete = "restrict"
67
+ description: str | None = None
68
+ related_name: str | None = None
69
+ reverse: bool = True
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class ReferenceDefinition:
74
+ """A validated reference: ``field`` of ``owner`` points to ``target``."""
75
+
76
+ owner: str
77
+ field: str
78
+ target: str
79
+ name: str
80
+ on_delete: OnDelete
81
+ description: str | None
82
+ #: The reverse relation's name on ``target``; ``None`` when not exposed.
83
+ related_name: str | None = None
84
+
85
+
86
+ def normalize_references(
87
+ owner: str, qualname: str, declared: Mapping[str, Reference], known_fields: set[str]
88
+ ) -> dict[str, ReferenceDefinition]:
89
+ """Validate ``Resource.references`` on its own (targets are checked by
90
+ ``check_references`` once every resource is registered). By relation name."""
91
+ refs: dict[str, ReferenceDefinition] = {}
92
+ for field_name, ref in declared.items():
93
+ if not isinstance(ref, Reference):
94
+ raise ConfigurationError(
95
+ f"{qualname}: references[{field_name!r}] must be a Reference, not {ref!r}",
96
+ hint='references = {"customer_id": Reference("customers")}',
97
+ doc=DOC,
98
+ )
99
+ if field_name not in known_fields:
100
+ raise ConfigurationError(
101
+ f"{qualname}: reference field {field_name!r} is not part of the read or "
102
+ "write schemas",
103
+ doc=DOC,
104
+ )
105
+ if ref.on_delete not in ON_DELETE:
106
+ raise ConfigurationError(
107
+ f"{qualname}: on_delete of {field_name!r} must be one of {ON_DELETE}",
108
+ doc=DOC,
109
+ )
110
+ name = ref.name or field_name.removesuffix("_id")
111
+ if name == field_name or name in known_fields:
112
+ raise ConfigurationError(
113
+ f"{qualname}: the relation name {name!r} of {field_name!r} clashes with a field",
114
+ hint="Pass name=... to the Reference.",
115
+ doc=DOC,
116
+ )
117
+ if name in refs:
118
+ raise ConfigurationError(f"{qualname}: two references are named {name!r}", doc=DOC)
119
+ refs[name] = ReferenceDefinition(
120
+ owner=owner,
121
+ field=field_name,
122
+ target=ref.resource,
123
+ name=name,
124
+ on_delete=ref.on_delete,
125
+ description=ref.description,
126
+ related_name=(ref.related_name or owner) if ref.reverse else None,
127
+ )
128
+ return refs
129
+
130
+
131
+ def _nullable(annotation: Any) -> bool:
132
+ if annotation is None or annotation is type(None) or annotation is Any:
133
+ return True
134
+ origin = typing.get_origin(annotation)
135
+ if origin in (typing.Union, types.UnionType):
136
+ return any(_nullable(a) for a in typing.get_args(annotation))
137
+ if origin is typing.Annotated:
138
+ return _nullable(typing.get_args(annotation)[0])
139
+ return False
140
+
141
+
142
+ def check_references(registry: ResourceRegistry) -> dict[str, list[ReferenceDefinition]]:
143
+ """Validate every reference against the registry; returns the references
144
+ pointing to each resource (its dependents), by target name."""
145
+ names = {d.name for d in registry}
146
+ dependents: dict[str, list[ReferenceDefinition]] = {}
147
+ for d in registry:
148
+ for ref in d.references.values():
149
+ where = f"{d.name}.{ref.field}"
150
+ if ref.target not in names:
151
+ raise ConfigurationError(
152
+ f"{where} references {ref.target!r}, which is not registered",
153
+ hint="Register the referenced resource in the same registry.",
154
+ doc=DOC,
155
+ )
156
+ if ref.on_delete == "set_null":
157
+ update = d.schemas.get("update")
158
+ field = update.model_fields.get(ref.field) if update is not None else None
159
+ if not d.enabled("update") or field is None or not _nullable(field.annotation):
160
+ raise ConfigurationError(
161
+ f"{where}: on_delete='set_null' needs update enabled with "
162
+ f"{ref.field!r} in the update schema, accepting None",
163
+ hint="The field is cleared through manager.update as the caller.",
164
+ doc=DOC,
165
+ )
166
+ if ref.on_delete == "cascade" and not d.enabled("delete"):
167
+ raise ConfigurationError(
168
+ f"{where}: on_delete='cascade' needs delete enabled on {d.name!r}",
169
+ doc=DOC,
170
+ )
171
+ dependents.setdefault(ref.target, []).append(ref)
172
+ _check_cycles(dependents)
173
+ return dependents
174
+
175
+
176
+ @dataclass(frozen=True)
177
+ class LinkDefinition:
178
+ """A many-to-many relation through a join resource: from a ``source``
179
+ record, the ``target`` records linked to it by ``join`` rows
180
+ (``join.source_field`` → source, ``join.target_field`` → target)."""
181
+
182
+ join: str
183
+ source: str
184
+ source_field: str
185
+ target: str
186
+ target_field: str
187
+ name: str
188
+ description: str | None = None
189
+
190
+ @property
191
+ def owner(self) -> str:
192
+ """The resource whose records the relation lists."""
193
+ return self.target
194
+
195
+ @property
196
+ def field(self) -> None:
197
+ """Always ``None``: a link has no foreign key on the source."""
198
+ return None
199
+
200
+
201
+ @dataclass(frozen=True, init=False)
202
+ class Link:
203
+ """On a join resource, the two reference fields it links (many-to-many),
204
+ and the names of the relations it gives each side, by field:
205
+ ``Link("invoice_id", "tag_id", names={"invoice_id": "labels"})``.
206
+ ``link = ("invoice_id", "tag_id")`` is the short form.
207
+ """
208
+
209
+ fields: tuple[str, ...]
210
+ names: Mapping[str, str]
211
+
212
+ def __init__(self, *fields: str, names: Mapping[str, str] | None = None) -> None:
213
+ object.__setattr__(self, "fields", fields)
214
+ object.__setattr__(self, "names", dict(names or {}))
215
+
216
+
217
+ def normalize_link(
218
+ qualname: str,
219
+ link: Sequence[str] | Link | None,
220
+ references: Mapping[str, ReferenceDefinition],
221
+ ) -> tuple[tuple[str, str] | None, dict[str, str]]:
222
+ """Validate ``Resource.link``: two of the resource's reference fields, and
223
+ the relation names by field."""
224
+ if link is None:
225
+ return None, {}
226
+ link_names = dict(link.names) if isinstance(link, Link) else {}
227
+ link = link.fields if isinstance(link, Link) else link
228
+ fields = {ref.field for ref in references.values()}
229
+ pair = tuple(link)
230
+ if len(pair) != 2 or pair[0] == pair[1] or not set(pair) <= fields:
231
+ raise ConfigurationError(
232
+ f"{qualname}: link must name two different reference fields, not {link!r}",
233
+ hint='link = ("invoice_id", "tag_id"), both declared in references.',
234
+ doc=DOC + "#many-to-many",
235
+ )
236
+ unknown = set(link_names) - set(pair)
237
+ if unknown:
238
+ raise ConfigurationError(
239
+ f"{qualname}: Link names must be keyed by the link fields, not {sorted(unknown)}",
240
+ doc=DOC + "#many-to-many",
241
+ )
242
+ return pair, link_names
243
+
244
+
245
+ #: Path segments of a record's own routes; reverse relations cannot use them.
246
+ RESERVED_RELATIONS = frozenset({"transitions", "history", "actions", "documents"})
247
+
248
+
249
+ def _links(registry: ResourceRegistry) -> dict[str, list[LinkDefinition]]:
250
+ """Many-to-many relations by the resource that gets them."""
251
+ out: dict[str, list[LinkDefinition]] = {}
252
+ for d in registry:
253
+ if d.link is None:
254
+ continue
255
+ by_field = {r.field: r for r in d.references.values()}
256
+ a, b = (by_field[f] for f in d.link)
257
+ for source, target in ((a, b), (b, a)):
258
+ if not (d.enabled("list") and registry.get(target.target).enabled("list")):
259
+ continue
260
+ out.setdefault(source.target, []).append(
261
+ LinkDefinition(
262
+ join=d.name,
263
+ source=source.target,
264
+ source_field=source.field,
265
+ target=target.target,
266
+ target_field=target.field,
267
+ name=d.link_names.get(source.field, target.target),
268
+ description=d.description and d.description.splitlines()[0],
269
+ )
270
+ )
271
+ return out
272
+
273
+
274
+ def reverse_relations(
275
+ registry: ResourceRegistry, dependents: Mapping[str, list[ReferenceDefinition]]
276
+ ) -> dict[str, dict[str, ReferenceDefinition | LinkDefinition]]:
277
+ """The reverse relations (``customers`` → ``invoices``) and many-to-many
278
+ links (``invoices`` → ``tags``) of each resource, by resource and name."""
279
+ out: dict[str, dict[str, ReferenceDefinition | LinkDefinition]] = {}
280
+ links = _links(registry)
281
+ for target in sorted(set(dependents) | set(links)):
282
+ refs: list[Any] = list(dependents.get(target, ())) + list(links.get(target, ()))
283
+ definition = registry.get(target)
284
+ read = definition.schemas.get("read")
285
+ fields = set(read.model_fields) if read is not None else set()
286
+ named: dict[str, ReferenceDefinition | LinkDefinition] = {}
287
+ for ref in refs:
288
+ if isinstance(ref, LinkDefinition):
289
+ name = ref.name
290
+ where = f"{ref.join} link"
291
+ else:
292
+ name = ref.related_name
293
+ if name is None or not registry.get(ref.owner).enabled("list"):
294
+ continue # no reverse relation without list on the referencing resource
295
+ where = f"{ref.owner}.{ref.field}"
296
+ clash = (
297
+ "another reverse relation"
298
+ if name in named
299
+ else "a relation"
300
+ if name in definition.references
301
+ else "a field"
302
+ if name in fields
303
+ else "a route"
304
+ if name in RESERVED_RELATIONS
305
+ else None
306
+ )
307
+ if clash or not name.isidentifier():
308
+ raise ConfigurationError(
309
+ f"{where}: the relation {name!r} on {target} "
310
+ + (f"clashes with {clash}" if clash else "is not a valid name"),
311
+ hint="Pass related_name=... (or reverse=False) to the Reference, "
312
+ "or Link(..., names=...) on the join resource.",
313
+ doc=DOC + "#reverse-relations",
314
+ )
315
+ named[name] = ref
316
+ if named:
317
+ out[target] = named
318
+ return out
319
+
320
+
321
+ def parse_expand(item: str) -> tuple[str, int | None]:
322
+ """``"invoices:25"`` → ``("invoices", 25)``; ``"customer"`` → ``("customer", None)``."""
323
+ name, sep, size = item.partition(":")
324
+ if not sep:
325
+ return name.strip(), None
326
+ try:
327
+ return name.strip(), int(size)
328
+ except ValueError:
329
+ return name.strip(), -1
330
+
331
+
332
+ @dataclass(frozen=True)
333
+ class RelatedPage:
334
+ """An embedded page of a reverse relation (``expand=["invoices"]``)."""
335
+
336
+ items: list[Any]
337
+ total: int
338
+ limit: int
339
+
340
+ @property
341
+ def has_more(self) -> bool:
342
+ """Whether more related records exist than the page holds."""
343
+ return self.total > len(self.items)
344
+
345
+
346
+ def _check_cycles(dependents: Mapping[str, list[ReferenceDefinition]]) -> None:
347
+ edges = {
348
+ target: {r.owner for r in refs if r.on_delete == "cascade"}
349
+ for target, refs in dependents.items()
350
+ }
351
+ state: dict[str, int] = {}
352
+
353
+ def visit(node: str, path: list[str]) -> None:
354
+ if state.get(node) == 1:
355
+ cycle = " → ".join([*path[path.index(node) :], node])
356
+ raise ConfigurationError(
357
+ f"Cascading deletes form a cycle: {cycle}",
358
+ hint="Use on_delete='restrict' or 'set_null' on one of the references.",
359
+ doc=DOC,
360
+ )
361
+ if state.get(node) == 2:
362
+ return
363
+ state[node] = 1
364
+ for child in sorted(edges.get(node, ())):
365
+ visit(child, [*path, node])
366
+ state[node] = 2
367
+
368
+ for node in sorted(edges):
369
+ visit(node, [])
370
+
371
+
372
+ # ----------------------------------------------------------------- results
373
+
374
+
375
+ def attach(model: Any, expanded: Mapping[str, Any]) -> Any:
376
+ """Attach expanded related records to a read model (in place)."""
377
+ if not isinstance(model, BaseModel) or not expanded:
378
+ return model
379
+ private = dict(model.__pydantic_private__ or {})
380
+ private[_EXPANDED] = {**private.get(_EXPANDED, {}), **expanded}
381
+ object.__setattr__(model, "__pydantic_private__", private)
382
+ return model
383
+
384
+
385
+ def expansions(model: Any) -> dict[str, Any]:
386
+ """The related records attached by ``expand``, by relation name."""
387
+ private = getattr(model, "__pydantic_private__", None)
388
+ if not isinstance(private, dict):
389
+ return {}
390
+ return dict(private.get(_EXPANDED, {}))
391
+
392
+
393
+ def dump_read(value: Any) -> Any:
394
+ """JSON-compatible form of a read result for entry adapters: hidden fields
395
+ left out, expanded related records nested under their relation name."""
396
+ from resource_engine.authz.fields import hidden_fields
397
+
398
+ if isinstance(value, RelatedPage):
399
+ return {
400
+ "items": [dump_read(i) for i in value.items],
401
+ "total": value.total,
402
+ "limit": value.limit,
403
+ "has_more": value.has_more,
404
+ }
405
+ if isinstance(value, BaseModel):
406
+ data = value.model_dump(mode="json", by_alias=True, exclude=set(hidden_fields(value)))
407
+ for name, related in expansions(value).items():
408
+ data[name] = dump_read(related)
409
+ return data
410
+ if isinstance(value, list | tuple):
411
+ return [dump_read(v) for v in value]
412
+ if isinstance(value, Mapping):
413
+ return {k: dump_read(v) for k, v in value.items()}
414
+ return value
415
+
416
+
417
+ def needs_dump(value: Any) -> bool:
418
+ """Whether ``value`` must be serialized with ``dump_read`` (hidden fields
419
+ or expansions), not by validating it against its response model."""
420
+ from resource_engine.authz.fields import hidden_fields
421
+
422
+ return bool(hidden_fields(value)) or bool(expansions(value))
423
+
424
+
425
+ def split_filters(filters: Mapping[str, Any]) -> tuple[dict[str, Any], dict[str, dict[str, Any]]]:
426
+ """Own filters, and related filters by relation name (``customer.country``)."""
427
+ own: dict[str, Any] = {}
428
+ related: dict[str, dict[str, Any]] = {}
429
+ for key, value in filters.items():
430
+ if "." in key:
431
+ name, _, field = key.partition(".")
432
+ related.setdefault(name, {})[field] = value
433
+ else:
434
+ own[key] = value
435
+ return own, related
436
+
437
+
438
+ def related_filter_names(definition: ResourceDefinition, registry: ResourceRegistry) -> list[str]:
439
+ """Every ``<relation>.<field>`` filter ``list`` accepts."""
440
+ names = []
441
+ for ref in definition.references.values():
442
+ target = registry.get(ref.target)
443
+ names += [f"{ref.name}.{f}" for f in target.filterable]
444
+ return names
445
+
446
+
447
+ def unique(values: Iterable[Any]) -> list[Any]:
448
+ seen: list[Any] = []
449
+ for v in values:
450
+ if v is not None and v not in seen:
451
+ seen.append(v)
452
+ return seen
453
+
454
+
455
+ __all__ = [
456
+ "LinkDefinition",
457
+ "Reference",
458
+ "ReferenceDefinition",
459
+ "RelatedPage",
460
+ "attach",
461
+ "check_references",
462
+ "dump_read",
463
+ "expansions",
464
+ "needs_dump",
465
+ "normalize_references",
466
+ "parse_expand",
467
+ "related_filter_names",
468
+ "reverse_relations",
469
+ "split_filters",
470
+ ]