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,96 @@
1
+ """Resource Engine: declarative resources for business backends.
2
+
3
+ Import from here, or from the public modules docs/stability.md lists (the
4
+ first-level ones, such as ``resource_engine.messaging``). Deeper modules, and
5
+ ``resource_engine.application``, are internal and can change in any release.
6
+ """
7
+
8
+ from resource_engine.application.actions import Action
9
+ from resource_engine.application.context import OperationContext
10
+ from resource_engine.application.events import (
11
+ ActionExecuted,
12
+ ResourceCreated,
13
+ ResourceDeleted,
14
+ ResourceEvent,
15
+ ResourceUpdated,
16
+ TransitionExecuted,
17
+ )
18
+ from resource_engine.application.hooks import HookPoint, external_effect, hook
19
+ from resource_engine.application.idempotency import IdempotencyJanitor
20
+ from resource_engine.application.manager import ResourceManager
21
+ from resource_engine.application.query import ListQuery, Page
22
+ from resource_engine.application.registry import ResourceRegistry
23
+ from resource_engine.application.relations import Link, Reference
24
+ from resource_engine.application.resource import (
25
+ CRUD,
26
+ CRUD_OPERATIONS,
27
+ ActionDefinition,
28
+ Resource,
29
+ ResourceDefinition,
30
+ )
31
+ from resource_engine.application.settings import (
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, describe_machine
43
+ from resource_engine.application.timers import Timer, TimerJob
44
+ from resource_engine.application.views import Aggregate, Avg, Count, Max, Min, Sum
45
+ from resource_engine.domain import DomainError, DomainEvent
46
+ from resource_engine.errors import ResourceEngineError
47
+
48
+ __version__ = "0.1.0"
49
+
50
+ __all__ = [
51
+ "CRUD",
52
+ "CRUD_OPERATIONS",
53
+ "Access",
54
+ "Action",
55
+ "ActionDefinition",
56
+ "ActionExecuted",
57
+ "Aggregate",
58
+ "Audited",
59
+ "Avg",
60
+ "Cached",
61
+ "Count",
62
+ "DocumentSlot",
63
+ "DomainError",
64
+ "DomainEvent",
65
+ "HookPoint",
66
+ "IdempotencyJanitor",
67
+ "Internal",
68
+ "Link",
69
+ "ListQuery",
70
+ "Listing",
71
+ "Machine",
72
+ "Max",
73
+ "Min",
74
+ "OperationContext",
75
+ "Page",
76
+ "Reference",
77
+ "Resource",
78
+ "ResourceCreated",
79
+ "ResourceDefinition",
80
+ "ResourceDeleted",
81
+ "ResourceEngineError",
82
+ "ResourceEvent",
83
+ "ResourceManager",
84
+ "ResourceRegistry",
85
+ "ResourceUpdated",
86
+ "Subtype",
87
+ "Sum",
88
+ "Timer",
89
+ "TimerJob",
90
+ "TransitionExecuted",
91
+ "Translatable",
92
+ "Versioned",
93
+ "describe_machine",
94
+ "external_effect",
95
+ "hook",
96
+ ]
@@ -0,0 +1 @@
1
+ """Application layer: resource definitions, lifecycle and orchestration."""
@@ -0,0 +1,48 @@
1
+ """Business actions (use cases) attached to a resource."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import TYPE_CHECKING, Any, ClassVar
7
+
8
+ from pydantic import BaseModel
9
+
10
+ if TYPE_CHECKING:
11
+ from resource_engine.application.context import OperationContext
12
+
13
+
14
+ def _snake(name: str) -> str:
15
+ return re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower()
16
+
17
+
18
+ class Action:
19
+ """A business operation that is neither CRUD nor a plain state transition.
20
+
21
+ Subclass it, document it with a docstring and implement ``execute``. The engine
22
+ validates the input, opens the unit of work, loads the entity (for instance
23
+ actions), runs ``before_action`` / ``after_action`` hooks, commits and publishes
24
+ events. ``execute`` may be sync or async.
25
+
26
+ Class attributes:
27
+ name: Public name (defaults to the snake_case class name).
28
+ input_schema: Pydantic model for the input, or ``None``.
29
+ output_schema: Pydantic model for the result. If ``None`` the resource's
30
+ ``read`` schema is used for instance actions returning the entity.
31
+ instance: ``True`` if the action targets one entity (``/{id}/actions/x``),
32
+ ``False`` for collection-level actions (``/actions/x``).
33
+ """
34
+
35
+ name: ClassVar[str | None] = None
36
+ input_schema: ClassVar[type[BaseModel] | None] = None
37
+ output_schema: ClassVar[type[BaseModel] | None] = None
38
+ instance: ClassVar[bool] = True
39
+
40
+ @classmethod
41
+ def action_name(cls) -> str:
42
+ """The action's name: ``name``, or the class name in snake case."""
43
+ return cls.name or _snake(cls.__name__)
44
+
45
+ def execute(self, ctx: OperationContext) -> Any: # pragma: no cover - abstract
46
+ """Run the action. ``ctx.entity`` is the record (``None`` for collection actions); the
47
+ return value is the response."""
48
+ raise NotImplementedError
@@ -0,0 +1,111 @@
1
+ """The context every operation carries through its hooks: the resource, the actor, the data, the
2
+ entity and what the operation produced."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import uuid
7
+ from collections.abc import Awaitable, Callable, Mapping
8
+ from dataclasses import dataclass, field
9
+ from typing import TYPE_CHECKING, Any
10
+
11
+ from resource_engine.domain.events import DomainEvent
12
+
13
+ if TYPE_CHECKING:
14
+ from resource_engine.application.resource import ResourceDefinition
15
+ from resource_engine.ports.repository import Repository
16
+ from resource_engine.ports.unit_of_work import UnitOfWork
17
+
18
+
19
+ type Callback = Callable[[], Awaitable[Any] | Any] # results are ignored
20
+
21
+
22
+ @dataclass(kw_only=True)
23
+ class OperationContext:
24
+ """Everything a hook, state-machine bridge or action can see about an operation.
25
+
26
+ Attributes:
27
+ resource: Definition of the resource being operated on.
28
+ operation: ``list``, ``get``, ``create``, ``update``, ``delete``,
29
+ ``transition`` or ``action``.
30
+ transition: Event name when ``operation == "transition"``.
31
+ action: Action name when ``operation == "action"``.
32
+ slot: Document slot for ``attach`` / ``detach`` operations.
33
+ actor: The caller (a ``Principal``, ``system_principal(...)`` for engine
34
+ jobs, or ``None``), provided by the entry adapter.
35
+ raw_input: Input as received, before validation (mutable in ``before_validate``).
36
+ data: Validated input (a Pydantic model instance), or ``None``.
37
+ entity_id: Identifier of the target entity, when there is one.
38
+ entity: The loaded or newly built entity.
39
+ previous_state / new_state: State values around a transition.
40
+ uow: Active unit of work (``None`` outside the transaction).
41
+ events: Events recorded so far; published after commit.
42
+ result: Value returned to the caller (set before commit).
43
+ correlation_id: Identifier shared by logs and events of this operation.
44
+ extras: Free-form storage for hooks to share data.
45
+ documents: Attach/detach documents inside this transaction (``None`` when
46
+ the manager has no blob store).
47
+ decision: The last authorization ``Decision`` for this operation.
48
+ tenant: Tenant the operation is confined to (tenant-scoped resources);
49
+ ``None`` for cross-tenant callers acting on all tenants.
50
+ """
51
+
52
+ resource: ResourceDefinition
53
+ operation: str
54
+ transition: str | None = None
55
+ action: str | None = None
56
+ slot: str | None = None
57
+ actor: Any = None
58
+ raw_input: Any = None
59
+ data: Any = None
60
+ entity_id: Any = None
61
+ entity: Any = None
62
+ previous_state: Any = None
63
+ new_state: Any = None
64
+ uow: UnitOfWork | None = None
65
+ events: list[DomainEvent] = field(default_factory=list)
66
+ result: Any = None
67
+ correlation_id: str = field(default_factory=lambda: uuid.uuid4().hex)
68
+ services: Mapping[str, Any] = field(default_factory=dict)
69
+ extras: dict[str, Any] = field(default_factory=dict)
70
+ documents: Any = None
71
+ decision: Any = None
72
+ tenant: str | None = None
73
+ _tenant_scope: Any = field(default=None, repr=False)
74
+ _on_rollback: list[Callback] = field(default_factory=list, repr=False)
75
+ _on_commit: list[Callback] = field(default_factory=list, repr=False)
76
+
77
+ def on_rollback(self, callback: Callback) -> None:
78
+ """Register a compensation for a *staged effect*.
79
+
80
+ Use it for writes outside the database that nothing references until the
81
+ commit (a stored blob, a remote record with a delete call). If the
82
+ operation fails, callbacks run in reverse order, best effort: errors are
83
+ logged. A crash can skip them, so pair them with a cleanup job.
84
+ """
85
+ self._on_rollback.append(callback)
86
+
87
+ def on_commit(self, callback: Callback) -> None:
88
+ """Run ``callback`` after a successful commit, before ``after_commit`` hooks.
89
+
90
+ For deferred clean-ups (e.g. deleting a detached blob). Errors are logged.
91
+ """
92
+ self._on_commit.append(callback)
93
+
94
+ def record_event(self, event: DomainEvent) -> None:
95
+ """Queue an event; it is published only if the transaction commits."""
96
+ self.events.append(event)
97
+
98
+ def repository(self, resource_name: str | None = None) -> Repository[Any]:
99
+ """Repository of this (or another) resource inside the current transaction."""
100
+ if self.uow is None:
101
+ raise RuntimeError("No unit of work is active at this point of the lifecycle")
102
+ return self.uow.repository(resource_name or self.resource.name)
103
+
104
+ def service(self, name: str) -> Any:
105
+ """Look up a service registered on the ResourceManager (e.g. a mail gateway port)."""
106
+ try:
107
+ return self.services[name]
108
+ except KeyError:
109
+ raise KeyError(
110
+ f"Service {name!r} is not registered; pass it to ResourceManager(services=...)"
111
+ ) from None
@@ -0,0 +1,54 @@
1
+ """Lifecycle events emitted by the engine itself."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any
7
+
8
+ from resource_engine.domain.events import DomainEvent
9
+
10
+
11
+ @dataclass(frozen=True, kw_only=True)
12
+ class ResourceEvent(DomainEvent):
13
+ """Base of the events the manager publishes about a record of a resource."""
14
+
15
+ resource: str
16
+ entity_id: Any
17
+
18
+
19
+ @dataclass(frozen=True, kw_only=True)
20
+ class ResourceCreated(ResourceEvent):
21
+ """A record was created."""
22
+
23
+ pass
24
+
25
+
26
+ @dataclass(frozen=True, kw_only=True)
27
+ class ResourceUpdated(ResourceEvent):
28
+ """A record was updated; ``changes`` maps each changed field to ``(before, after)``."""
29
+
30
+ changes: dict[str, tuple[Any, Any]] = field(default_factory=dict)
31
+
32
+
33
+ @dataclass(frozen=True, kw_only=True)
34
+ class ResourceDeleted(ResourceEvent):
35
+ """A record was deleted."""
36
+
37
+ pass
38
+
39
+
40
+ @dataclass(frozen=True, kw_only=True)
41
+ class TransitionExecuted(ResourceEvent):
42
+ """A state machine moved a record from ``source`` to ``target`` with ``transition``."""
43
+
44
+ transition: str
45
+ source: Any
46
+ target: Any
47
+ machine: str | None = None # which of the resource's machines (its name)
48
+
49
+
50
+ @dataclass(frozen=True, kw_only=True)
51
+ class ActionExecuted(ResourceEvent):
52
+ """An action ran on a record (instance actions) or on the resource."""
53
+
54
+ action: str
@@ -0,0 +1,272 @@
1
+ """Typed lifecycle hooks and their dispatcher."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ import types
7
+ from collections.abc import Awaitable, Callable, Iterable, Mapping, Sequence
8
+ from dataclasses import dataclass
9
+ from enum import StrEnum
10
+ from typing import TYPE_CHECKING, Any
11
+
12
+ from resource_engine.errors import ConfigurationError, ExternalEffectInTransaction
13
+
14
+ if TYPE_CHECKING:
15
+ from resource_engine.application.context import OperationContext
16
+
17
+ type Hook = Callable[[OperationContext], Awaitable[None] | None]
18
+
19
+ _EXTERNAL_EFFECT_ATTR = "__resource_engine_external_effect__"
20
+ _POINTS_ATTR = "__resource_engine_hook_points__"
21
+
22
+
23
+ class HookPoint(StrEnum):
24
+ """Points of the lifecycle where hooks can run. See docs/lifecycle.md for the order."""
25
+
26
+ BEFORE_VALIDATE = "before_validate"
27
+ AFTER_VALIDATE = "after_validate"
28
+ BEFORE_CREATE = "before_create"
29
+ AFTER_CREATE = "after_create"
30
+ BEFORE_UPDATE = "before_update"
31
+ AFTER_UPDATE = "after_update"
32
+ BEFORE_DELETE = "before_delete"
33
+ AFTER_DELETE = "after_delete"
34
+ BEFORE_TRANSITION = "before_transition"
35
+ AFTER_TRANSITION = "after_transition"
36
+ BEFORE_ACTION = "before_action"
37
+ AFTER_ACTION = "after_action"
38
+ BEFORE_ATTACH = "before_attach"
39
+ AFTER_ATTACH = "after_attach"
40
+ BEFORE_DETACH = "before_detach"
41
+ AFTER_DETACH = "after_detach"
42
+ AFTER_COMMIT = "after_commit"
43
+
44
+ @property
45
+ def transactional(self) -> bool:
46
+ """Whether hooks at this point run inside the unit of work."""
47
+ return self not in (
48
+ HookPoint.BEFORE_VALIDATE,
49
+ HookPoint.AFTER_VALIDATE,
50
+ HookPoint.AFTER_COMMIT,
51
+ )
52
+
53
+
54
+ # Points that accept a ``:qualifier`` (transition event or action name).
55
+ QUALIFIABLE = {
56
+ HookPoint.BEFORE_TRANSITION,
57
+ HookPoint.AFTER_TRANSITION,
58
+ HookPoint.BEFORE_ACTION,
59
+ HookPoint.AFTER_ACTION,
60
+ HookPoint.BEFORE_ATTACH,
61
+ HookPoint.AFTER_ATTACH,
62
+ HookPoint.BEFORE_DETACH,
63
+ HookPoint.AFTER_DETACH,
64
+ }
65
+
66
+
67
+ def external_effect[F: Callable[..., Any]](fn: F) -> F:
68
+ """Mark a hook as producing external effects (emails, HTTP calls, messages).
69
+
70
+ Such hooks may only be registered at ``after_commit``; the engine refuses any
71
+ other point at bootstrap with RE-E104.
72
+ """
73
+ setattr(fn, _EXTERNAL_EFFECT_ATTR, True)
74
+ return fn
75
+
76
+
77
+ def has_external_effect(fn: Callable[..., Any]) -> bool:
78
+ """Whether ``fn`` was marked as having an effect outside the transaction
79
+ (``external_effect``)."""
80
+ return bool(getattr(fn, _EXTERNAL_EFFECT_ATTR, False))
81
+
82
+
83
+ @dataclass(frozen=True)
84
+ class HookKey:
85
+ """Where a hook runs: a hook point and, for transitions and actions, which one."""
86
+
87
+ point: HookPoint
88
+ qualifier: str | None = None
89
+
90
+ def __str__(self) -> str:
91
+ return f"{self.point.value}:{self.qualifier}" if self.qualifier else self.point.value
92
+
93
+ @classmethod
94
+ def parse(cls, raw: str | HookPoint) -> HookKey:
95
+ """The key for ``"point"`` or ``"point:qualifier"``."""
96
+ if isinstance(raw, HookPoint):
97
+ return cls(raw)
98
+ name, _, qualifier = raw.partition(":")
99
+ try:
100
+ point = HookPoint(name)
101
+ except ValueError:
102
+ valid = ", ".join(p.value for p in HookPoint)
103
+ raise ConfigurationError(
104
+ f"Unknown hook point {raw!r}",
105
+ hint=f"Use one of: {valid}",
106
+ doc="docs/lifecycle.md#hook-points",
107
+ ) from None
108
+ if qualifier and point not in QUALIFIABLE:
109
+ raise ConfigurationError(
110
+ f"Hook point {name!r} does not accept a qualifier ({raw!r})",
111
+ hint="Only the transition, action, attach and detach points accept ':<name>'.",
112
+ doc="docs/lifecycle.md#hook-points",
113
+ )
114
+ return cls(point, qualifier or None)
115
+
116
+
117
+ def _callable_name(fn: Callable[..., Any]) -> str:
118
+ return getattr(fn, "__qualname__", None) or repr(fn)
119
+
120
+
121
+ class HookMarks:
122
+ """Where a hook runs, said next to its code: ``@hook.before("create")``.
123
+
124
+ The decorators only mark the function (it stays a plain function, callable
125
+ in tests); the resource lists the marked functions, or the modules holding
126
+ them, in ``hooks = [...]``. Targets are the hook points without their
127
+ ``before_`` / ``after_`` prefix, with the usual qualifier:
128
+ ``"create"``, ``"update"``, ``"transition:approve"``, ``"action:recalculate"``,
129
+ ``"attach:signed_pdf"``. Stack them to run a function at several points.
130
+ """
131
+
132
+ def before[F: Callable[..., Any]](self, *targets: str) -> Callable[[F], F]:
133
+ """Run the hook before each target (inside the transaction, except validate)."""
134
+ return self._mark("before", targets)
135
+
136
+ def after[F: Callable[..., Any]](self, *targets: str) -> Callable[[F], F]:
137
+ """Run the hook after each target (inside the transaction, except validate)."""
138
+ return self._mark("after", targets)
139
+
140
+ def after_commit[F: Callable[..., Any]](self, fn: F) -> F:
141
+ """Run the hook once the transaction has committed (external effects go here)."""
142
+ return _add_points(fn, (HookKey(HookPoint.AFTER_COMMIT),))
143
+
144
+ def _mark[F: Callable[..., Any]](
145
+ self, prefix: str, targets: tuple[str, ...]
146
+ ) -> Callable[[F], F]:
147
+ if not targets:
148
+ raise ConfigurationError(
149
+ f"@hook.{prefix}() needs at least one target",
150
+ hint=f'For example @hook.{prefix}("create", "update").',
151
+ doc="docs/lifecycle.md#hook-points",
152
+ )
153
+ keys = tuple(HookKey.parse(f"{prefix}_{target}") for target in targets)
154
+ return lambda fn: _add_points(fn, keys)
155
+
156
+
157
+ def _add_points[F: Callable[..., Any]](fn: F, keys: tuple[HookKey, ...]) -> F:
158
+ if not callable(fn):
159
+ raise ConfigurationError(f"@hook marks functions, not {fn!r}")
160
+ setattr(fn, _POINTS_ATTR, (*keys, *hook_points(fn)))
161
+ return fn
162
+
163
+
164
+ def hook_points(fn: Any) -> tuple[HookKey, ...]:
165
+ """The points ``@hook`` decorators marked ``fn`` for, in the order written."""
166
+ return tuple(getattr(fn, _POINTS_ATTR, ()))
167
+
168
+
169
+ #: The decorators: ``@hook.before(...)``, ``@hook.after(...)``, ``@hook.after_commit``.
170
+ hook = HookMarks()
171
+
172
+
173
+ def _marked(raw: Sequence[Any], owner: str) -> dict[HookKey, list[Hook]]:
174
+ """``hooks = [fn, module, ...]``: marked functions, and those defined in modules."""
175
+ found: dict[HookKey, list[Hook]] = {}
176
+ for item in raw:
177
+ if isinstance(item, types.ModuleType):
178
+ fns = [
179
+ value
180
+ for value in vars(item).values()
181
+ if inspect.isfunction(value)
182
+ and value.__module__ == item.__name__
183
+ and hook_points(value)
184
+ ]
185
+ if not fns:
186
+ raise ConfigurationError(
187
+ f"{owner}: the module {item.__name__} has no functions marked with @hook",
188
+ hint='Mark each hook with @hook.before("create") or similar.',
189
+ doc="docs/lifecycle.md#declaring-hooks",
190
+ )
191
+ elif callable(item):
192
+ if not hook_points(item):
193
+ raise ConfigurationError(
194
+ f"{owner}: the hook {_callable_name(item)!r} says nowhere where it runs",
195
+ hint='Mark it with @hook.before("create"), @hook.after(...) or '
196
+ "@hook.after_commit, or use hooks = {point: [fn]}.",
197
+ doc="docs/lifecycle.md#declaring-hooks",
198
+ )
199
+ fns = [item]
200
+ else:
201
+ raise ConfigurationError(
202
+ f"{owner}: hooks lists functions or modules, not {item!r}",
203
+ doc="docs/lifecycle.md#declaring-hooks",
204
+ )
205
+ for fn in fns:
206
+ for key in hook_points(fn):
207
+ listed = found.setdefault(key, [])
208
+ if fn not in listed: # listed on its own and through its module: once
209
+ listed.append(fn)
210
+ return found
211
+
212
+
213
+ def normalize_hooks(
214
+ raw: Mapping[str | HookPoint, Hook | Sequence[Hook]] | Sequence[Any], *, owner: str
215
+ ) -> dict[HookKey, tuple[Hook, ...]]:
216
+ """Validate a ``hooks`` declaration and return it keyed by HookKey.
217
+
218
+ Either a list of functions marked with ``@hook`` (or modules holding them),
219
+ or the mapping ``{"before_create": [fn], ...}``.
220
+ """
221
+ if not isinstance(raw, Mapping):
222
+ raw = _marked(raw, owner) # type: ignore[assignment]
223
+ result: dict[HookKey, tuple[Hook, ...]] = {}
224
+ for raw_key, value in raw.items(): # type: ignore[union-attr]
225
+ key = raw_key if isinstance(raw_key, HookKey) else HookKey.parse(raw_key)
226
+ fns: Iterable[Hook] = (value,) if callable(value) else value
227
+ fns = tuple(fns)
228
+ for fn in fns:
229
+ if not callable(fn):
230
+ raise ConfigurationError(
231
+ f"Hook {fn!r} registered at {key} of {owner} is not callable"
232
+ )
233
+ if has_external_effect(fn) and key.point is not HookPoint.AFTER_COMMIT:
234
+ raise ExternalEffectInTransaction(
235
+ f"The hook {_callable_name(fn)!r} registered at {str(key)!r} of {owner} "
236
+ "produces external effects.",
237
+ hint="Move it to 'after_commit' or record a domain event instead.",
238
+ doc="docs/lifecycle.md#external-effects",
239
+ )
240
+ result[key] = result.get(key, ()) + fns
241
+ return result
242
+
243
+
244
+ class HookDispatcher:
245
+ """Runs hooks for a lifecycle point: generic ones first, then qualified ones."""
246
+
247
+ def __init__(self, hooks: Mapping[HookKey, Sequence[Hook]]) -> None:
248
+ self._hooks = hooks
249
+
250
+ def for_point(self, point: HookPoint, qualifier: str | None = None) -> list[Hook]:
251
+ """The hooks for ``point``: generic ones, then those for ``qualifier``."""
252
+ hooks = list(self._hooks.get(HookKey(point), ()))
253
+ if qualifier:
254
+ hooks.extend(self._hooks.get(HookKey(point, qualifier), ()))
255
+ return hooks
256
+
257
+ async def run(
258
+ self, point: HookPoint, ctx: OperationContext, qualifier: str | None = None
259
+ ) -> None:
260
+ """Run the hooks for ``point`` in order, awaiting async ones."""
261
+ for fn in self.for_point(point, qualifier):
262
+ try:
263
+ result = fn(ctx)
264
+ if inspect.isawaitable(result):
265
+ await result
266
+ except Exception as exc:
267
+ exc.add_note(
268
+ f"[resource-engine] raised by hook {_callable_name(fn)!r} at "
269
+ f"{point.value}{':' + qualifier if qualifier else ''} "
270
+ f"of resource {ctx.resource.name!r}"
271
+ )
272
+ raise