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,162 @@
1
+ """Search and filter operators for ``list``.
2
+
3
+ - **Filter operators:** a filter key may carry an operator, ``amount[gte]``:
4
+ ``ne``, ``lt``, ``lte``, ``gt``, ``gte``, ``in`` and ``nin`` (``in`` and
5
+ ``nin`` take a list, or a comma-separated text). The comparisons are for
6
+ ordered types (numbers, dates, times); text and other fields take ``ne``,
7
+ ``in`` and ``nin``, and booleans only ``ne``. A key without one is
8
+ equality, as before. Only the resource's own ``filterable`` fields take
9
+ operators; related filters (``customer.country``) stay equalities.
10
+ - **Search:** ``ListQuery(search="ana sants")`` keeps the records where every
11
+ word appears, ignoring case, in at least one of the resource's
12
+ ``Listing(searchable=[...])`` fields that the caller may read.
13
+
14
+ Both become a condition in the condition language (``icontains`` for the
15
+ words), so every store that applies row filters runs them through its own
16
+ compiler: SQL, in memory, the query engines, the document stores that can.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import re
22
+ import types
23
+ import typing
24
+ from collections.abc import Mapping
25
+ from datetime import date, datetime, time
26
+ from decimal import Decimal
27
+ from typing import Any
28
+
29
+ from pydantic import TypeAdapter, ValidationError
30
+
31
+ from resource_engine.errors import InvalidQuery
32
+
33
+ #: Operators clients write, and the condition operator each one becomes.
34
+ FILTER_OPERATORS = {
35
+ "ne": "ne",
36
+ "lt": "lt",
37
+ "lte": "le",
38
+ "gt": "gt",
39
+ "gte": "ge",
40
+ "in": "in",
41
+ "nin": "nin",
42
+ }
43
+ #: Types the comparisons (``lt``, ``lte``, ``gt``, ``gte``) apply to.
44
+ ORDERED = (int, float, Decimal, date, datetime, time)
45
+ #: The operators of every other field, and of booleans.
46
+ UNORDERED_OPERATORS = ("ne", "in", "nin")
47
+ BOOLEAN_OPERATORS = ("ne",)
48
+
49
+ #: The most words a search takes, and the longest word.
50
+ MAX_WORDS = 8
51
+ MAX_WORD = 100
52
+
53
+ _KEY = re.compile(r"^(?P<field>[^\[\]]+)\[(?P<op>[a-z]+)\]$")
54
+
55
+
56
+ def split_operator(key: str) -> tuple[str, str | None]:
57
+ """``"amount[gte]"`` → ``("amount", "gte")``; ``"amount"`` → ``("amount", None)``."""
58
+ match = _KEY.match(key)
59
+ return (match["field"], match["op"]) if match else (key, None)
60
+
61
+
62
+ def operators_for(annotation: Any) -> tuple[str, ...]:
63
+ """The filter operators a field of this type takes."""
64
+ args = typing.get_args(annotation)
65
+ if typing.get_origin(annotation) in (typing.Union, types.UnionType):
66
+ inner = [a for a in args if a is not type(None)]
67
+ annotation = inner[0] if len(inner) == 1 else Any
68
+ if annotation is bool:
69
+ return BOOLEAN_OPERATORS
70
+ if isinstance(annotation, type) and issubclass(annotation, ORDERED):
71
+ return tuple(FILTER_OPERATORS)
72
+ return UNORDERED_OPERATORS
73
+
74
+
75
+ def operator_filters(
76
+ resource: str, filters: Mapping[str, Any], read: Any
77
+ ) -> tuple[dict[str, Any], Any]:
78
+ """Equality filters, and a condition for the ones with operators (``None``
79
+ when there are none). Values are converted to the field's type, as the read
80
+ schema declares it; one that doesn't convert is refused (RE-E103)."""
81
+ from resource_engine.authz.conditions import conjunction
82
+
83
+ plain: dict[str, Any] = {}
84
+ parts: list[Any] = []
85
+ for key, value in filters.items():
86
+ name, op = split_operator(key)
87
+ if op is None:
88
+ plain[key] = value
89
+ continue
90
+ if op not in FILTER_OPERATORS:
91
+ raise InvalidQuery(
92
+ f"Unknown filter operator {op!r} in {key!r}",
93
+ hint=f"Use one of: {', '.join(FILTER_OPERATORS)}.",
94
+ doc="docs/frontend.md#lists",
95
+ )
96
+ field = read.model_fields.get(name) if read is not None else None
97
+ if field is not None and op not in operators_for(field.annotation):
98
+ raise InvalidQuery(
99
+ f"{name} doesn't take {op!r}",
100
+ hint=f"{name} takes: {', '.join(operators_for(field.annotation))}; "
101
+ "comparisons are for numbers, dates and times.",
102
+ doc="docs/frontend.md#lists",
103
+ )
104
+ converted = _convert(resource, key, name, op, value, read)
105
+ parts.append({FILTER_OPERATORS[op]: [{"attr": f"resource.{name}"}, converted]})
106
+ return plain, (conjunction(*parts) if parts else None)
107
+
108
+
109
+ def _convert(resource: str, key: str, name: str, op: str, value: Any, read: Any) -> Any:
110
+ field = read.model_fields.get(name) if read is not None else None
111
+ adapter = TypeAdapter(field.annotation if field is not None else Any)
112
+ if op in ("in", "nin"):
113
+ items = value.split(",") if isinstance(value, str) else list(value or [])
114
+ if not items:
115
+ raise InvalidQuery(f"{key} needs at least one value")
116
+ return [_validate(adapter, item, resource, key) for item in items]
117
+ return _validate(adapter, value, resource, key)
118
+
119
+
120
+ def _validate(adapter: TypeAdapter[Any], value: Any, resource: str, key: str) -> Any:
121
+ try:
122
+ return adapter.validate_python(value)
123
+ except ValidationError:
124
+ raise InvalidQuery(
125
+ f"{key}={value!r} is not a valid value for {resource}", doc="docs/frontend.md#lists"
126
+ ) from None
127
+
128
+
129
+ def search_words(text: str | None) -> list[str]:
130
+ """The words of a search (at most ``MAX_WORDS``, each at most ``MAX_WORD``
131
+ characters); empty when there is nothing to search."""
132
+ if not text:
133
+ return []
134
+ words = text.split()
135
+ if len(words) > MAX_WORDS or any(len(w) > MAX_WORD for w in words):
136
+ raise InvalidQuery(
137
+ f"A search takes at most {MAX_WORDS} words of {MAX_WORD} characters",
138
+ doc="docs/frontend.md#search",
139
+ )
140
+ return words
141
+
142
+
143
+ def search_condition(fields: list[str], words: list[str]) -> Any:
144
+ """Every word in at least one of ``fields`` (``False`` when no field can be
145
+ searched: nothing matches)."""
146
+ from resource_engine.authz.conditions import conjunction, disjunction
147
+
148
+ if not fields:
149
+ return False
150
+ return conjunction(
151
+ *(
152
+ disjunction(*({"icontains": [{"attr": f"resource.{f}"}, word]} for f in fields))
153
+ for word in words
154
+ )
155
+ )
156
+
157
+
158
+ def like_pattern(text: str, escape: str = "\\") -> str:
159
+ """``%text%`` for SQL ``LIKE``, with ``%``, ``_`` and the escape character
160
+ escaped: a search for ``50%`` finds "50%", not everything."""
161
+ escaped = text.replace(escape, escape * 2).replace("%", escape + "%").replace("_", escape + "_")
162
+ return f"%{escaped}%"
@@ -0,0 +1,169 @@
1
+ """Grouped settings of a ``Resource``: one value per concern instead of a flat
2
+ list of class attributes.
3
+
4
+ ```python
5
+ class InvoiceResource(Resource):
6
+ listing = Listing(filterable=["status"], sortable=["id", "amount"])
7
+ access = Access(tenant_field="org_id", restricted_fields=["notes"])
8
+ concurrency = Versioned("version")
9
+ caching = Cached(ttl=30)
10
+ audit = Audited(reads=True)
11
+ ```
12
+
13
+ Each group is optional; leaving it out keeps the defaults.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from collections.abc import Sequence
19
+ from dataclasses import dataclass
20
+ from typing import Any
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class Listing:
25
+ """How ``list`` may be filtered, sorted and paged.
26
+
27
+ Attributes:
28
+ filterable: Fields accepted as filters (``?status=draft``).
29
+ sortable: Fields accepted in ``sort`` (``-amount``).
30
+ max_page_size: Upper bound for a page.
31
+ searchable: Text fields ``search`` looks in (``?q=ana``): a record
32
+ matches when every word appears, ignoring case, in one of them.
33
+ """
34
+
35
+ filterable: Sequence[str] = ()
36
+ sortable: Sequence[str] = ()
37
+ max_page_size: int = 100
38
+ searchable: Sequence[str] = ()
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class Access:
43
+ """Who may see what, beyond the policies (see docs/permissions.md).
44
+
45
+ Attributes:
46
+ tenant_field: Entity attribute holding the tenant: every operation is
47
+ confined to the caller's tenant (docs/tenancy.md).
48
+ restricted_fields: Fields read or written only with an explicit grant
49
+ (``<resource>:read:<field>`` / ``<resource>:write:<field>``).
50
+ wildcards: ``False`` for sensitive resources: wildcard grants
51
+ (``*:list``) don't match their actions, only explicit ones.
52
+ """
53
+
54
+ tenant_field: str | None = None
55
+ restricted_fields: Sequence[str] = ()
56
+ wildcards: bool = True
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class Versioned:
61
+ """Optimistic concurrency (docs/concurrency.md): writes check the version
62
+ the client saw and bump it.
63
+
64
+ Attributes:
65
+ field: Integer attribute holding the version.
66
+ required: Refuse writes that send no version (RE-E106).
67
+ """
68
+
69
+ field: str = "version"
70
+ required: bool = False
71
+
72
+
73
+ @dataclass(frozen=True)
74
+ class Cached:
75
+ """Caching of records and answers (docs/caching.md).
76
+
77
+ Attributes:
78
+ ttl: Seconds the manager's cache keeps records read by id; ``None``
79
+ doesn't cache them.
80
+ control: ``Cache-Control`` of the HTTP ``GET`` answers; the default
81
+ lets clients store answers but revalidate them.
82
+ """
83
+
84
+ ttl: float | None = None
85
+ control: str | None = None
86
+
87
+
88
+ @dataclass(frozen=True)
89
+ class Audited:
90
+ """What the audit trail records beyond writes (docs/audit.md).
91
+ ``audit = False`` leaves the resource out of it.
92
+
93
+ Attributes:
94
+ reads: Also audit ``get`` and ``list``.
95
+ exclude: Fields recorded as changed without their values (restricted
96
+ fields always are).
97
+ """
98
+
99
+ reads: bool = False
100
+ exclude: Sequence[str] = ()
101
+
102
+
103
+ @dataclass(frozen=True, init=False)
104
+ class Translatable:
105
+ """Fields holding one text per language (``{locale: text}``), read and
106
+ written in the request's language (docs/i18n.md). ``translatable = ["name"]``
107
+ is the short form when the default language is the application's.
108
+
109
+ Attributes:
110
+ fields: The translatable fields.
111
+ default_locale: Their language when the request names none.
112
+ """
113
+
114
+ fields: tuple[str, ...]
115
+ default_locale: str | None
116
+
117
+ def __init__(self, *fields: str, default_locale: str | None = None) -> None:
118
+ object.__setattr__(self, "fields", fields)
119
+ object.__setattr__(self, "default_locale", default_locale)
120
+
121
+
122
+ @dataclass(frozen=True)
123
+ class Internal:
124
+ """What only code runs (the manager, processes, jobs): entry adapters (HTTP,
125
+ GraphQL, MCP) don't offer it. ``internal = ["create"]`` is the short form
126
+ for operations only.
127
+
128
+ Attributes:
129
+ operations: Enabled CRUD operations kept internal.
130
+ transitions: Keep every transition internal too.
131
+ """
132
+
133
+ operations: Sequence[str] = ()
134
+ transitions: bool = False
135
+
136
+
137
+ @dataclass(frozen=True)
138
+ class Subtype:
139
+ """On a subtype of a polymorphic resource (docs/polymorphism.md): its base,
140
+ and its value in the base's discriminator (default: the subtype's name).
141
+ ``extends = RequestResource`` is the short form.
142
+ """
143
+
144
+ base: Any
145
+ identity: str | None = None
146
+
147
+
148
+ #: Flat settings that moved into a group, with where they went.
149
+ MOVED = {
150
+ "filterable": "listing = Listing(filterable=[...])",
151
+ "sortable": "listing = Listing(sortable=[...])",
152
+ "max_page_size": "listing = Listing(max_page_size=...)",
153
+ "tenant_field": 'access = Access(tenant_field="...")',
154
+ "restricted_fields": "access = Access(restricted_fields=[...])",
155
+ "authz_wildcards": "access = Access(wildcards=False)",
156
+ "version_field": 'concurrency = Versioned("...")',
157
+ "require_version": 'concurrency = Versioned("...", required=True)',
158
+ "cache_ttl": "caching = Cached(ttl=...)",
159
+ "cache_control": 'caching = Cached(control="...")',
160
+ "audit_reads": "audit = Audited(reads=True)",
161
+ "audit_exclude": "audit = Audited(exclude=[...])",
162
+ "state_field": 'state_machine = Machine(<StateMachine>, field="...")',
163
+ "state_since_field": 'state_machine = Machine(<StateMachine>, since_field="...")',
164
+ "link_names": 'link = Link("...", "...", names={...})',
165
+ "default_locale": 'translatable = Translatable("...", default_locale="...")',
166
+ "internal_operations": "internal = [...] (or Internal(operations=[...]))",
167
+ "expose_transitions": "internal = Internal(transitions=True)",
168
+ "identity": 'extends = Subtype(<BaseResource>, identity="...")',
169
+ }
@@ -0,0 +1,67 @@
1
+ """Document slots: which files a resource accepts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import fnmatch
6
+ import re
7
+ from collections.abc import Sequence
8
+ from dataclasses import dataclass
9
+ from typing import Literal
10
+
11
+ type UploadMode = Literal["api", "presigned", "any"]
12
+
13
+ _NAME = re.compile(r"^[a-z][a-z0-9_]*$")
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class DocumentSlot:
18
+ """A named place for documents on a resource (``Resource.documents``).
19
+
20
+ Args:
21
+ name: Slot identifier (``signed_pdf``), used in URLs and hook qualifiers.
22
+ content_types: Accepted MIME types; ``*`` patterns allowed (``image/*``).
23
+ max_bytes: Size limit, enforced while streaming and on upload confirmation.
24
+ multiple: Several documents at once; otherwise attaching replaces the
25
+ previous one.
26
+ upload: ``api`` (bytes go through the API), ``presigned`` (direct to the
27
+ store) or ``any``.
28
+ required_for: Transitions that need an available document in this slot.
29
+ processing: Documents go through the processing pipeline before they
30
+ become available.
31
+ description: Functional description (shown in generated docs).
32
+ """
33
+
34
+ name: str
35
+ content_types: Sequence[str] = ("*/*",)
36
+ max_bytes: int = 25 * 1024 * 1024
37
+ multiple: bool = False
38
+ upload: UploadMode = "any"
39
+ required_for: Sequence[str] = ()
40
+ processing: bool = False
41
+ description: str | None = None
42
+
43
+ def __post_init__(self) -> None:
44
+ object.__setattr__(self, "content_types", tuple(t.lower() for t in self.content_types))
45
+ object.__setattr__(self, "required_for", tuple(self.required_for))
46
+
47
+ def accepts(self, content_type: str) -> bool:
48
+ """Whether the slot takes ``content_type`` (patterns such as ``image/*``)."""
49
+ base = content_type.split(";", 1)[0].strip().lower()
50
+ return any(fnmatch.fnmatchcase(base, pattern) for pattern in self.content_types)
51
+
52
+ def allows(self, mode: Literal["api", "presigned"]) -> bool:
53
+ """Whether the slot takes uploads through the API or presigned URLs."""
54
+ return self.upload in (mode, "any")
55
+
56
+ def problems(self) -> list[str]:
57
+ """What is wrong with the slot's declaration (empty when valid)."""
58
+ out = []
59
+ if not _NAME.match(self.name):
60
+ out.append(f"slot name {self.name!r} must be snake_case")
61
+ if self.max_bytes <= 0:
62
+ out.append(f"slot {self.name!r}: max_bytes must be positive")
63
+ if self.upload not in ("api", "presigned", "any"):
64
+ out.append(f"slot {self.name!r}: upload must be 'api', 'presigned' or 'any'")
65
+ if not self.content_types:
66
+ out.append(f"slot {self.name!r}: content_types is empty")
67
+ return out
@@ -0,0 +1,177 @@
1
+ """Bridge between resources and ``python-statemachine``.
2
+
3
+ The state machine class lives in the module's domain layer and knows nothing about
4
+ sessions or transactions. The engine binds a fresh machine to the entity for each
5
+ operation, fires the event and then persists the entity through the repository.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import inspect
11
+ from dataclasses import dataclass
12
+ from typing import Any
13
+
14
+ from statemachine import StateMachine
15
+ from statemachine.exceptions import TransitionNotAllowed as _SMTransitionNotAllowed
16
+
17
+ from resource_engine.errors import TransitionNotAllowed, UnknownTransition
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class Machine:
22
+ """One of a resource's state machines (``Resource.machines``).
23
+
24
+ ```python
25
+ machines = {
26
+ "approval": Machine(InvoiceStateMachine, field="status", since_field="status_since"),
27
+ "payment": Machine(PaymentStateMachine, field="payment_status"),
28
+ }
29
+ ```
30
+
31
+ Args:
32
+ machine: A ``python-statemachine`` class.
33
+ field: Entity attribute that stores this machine's state.
34
+ since_field: Datetime attribute the engine sets whenever this machine
35
+ changes state (on create and on each of its transitions); timers of
36
+ its transitions count from it by default.
37
+ """
38
+
39
+ machine: type[StateMachine]
40
+ field: str = "status"
41
+ since_field: str | None = None
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class StateInfo:
46
+ """A state of a resource's state machine."""
47
+
48
+ id: str
49
+ name: str
50
+ value: Any
51
+ initial: bool
52
+ final: bool
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class TransitionInfo:
57
+ """A transition of a resource's state machine: the event and the states it moves between."""
58
+
59
+ event: str
60
+ source: str
61
+ target: str
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class MachineInfo:
66
+ """A state machine's states and transitions, read once from the machine class."""
67
+
68
+ states: tuple[StateInfo, ...]
69
+ transitions: tuple[TransitionInfo, ...]
70
+
71
+ @property
72
+ def events(self) -> tuple[str, ...]:
73
+ """The machine's events, in declaration order, once each."""
74
+ seen: dict[str, None] = {}
75
+ for t in self.transitions:
76
+ seen.setdefault(t.event, None)
77
+ return tuple(seen)
78
+
79
+ @property
80
+ def initial(self) -> StateInfo | None:
81
+ """The initial state, if the machine declares one."""
82
+ return next((s for s in self.states if s.initial), None)
83
+
84
+
85
+ def describe_machine(machine_cls: type[StateMachine]) -> MachineInfo:
86
+ """Static description of a machine: states and transitions, in declaration order."""
87
+ states = tuple(
88
+ StateInfo(id=s.id, name=s.name, value=s.value, initial=s.initial, final=s.final)
89
+ for s in machine_cls.states
90
+ )
91
+ transitions: list[TransitionInfo] = []
92
+ for state in machine_cls.states:
93
+ for t in state.transitions:
94
+ for event in str(t.event).split():
95
+ transitions.append(
96
+ TransitionInfo(event=event, source=t.source.id, target=t.target.id)
97
+ )
98
+ return MachineInfo(states=states, transitions=tuple(transitions))
99
+
100
+
101
+ async def _maybe_await(value: Any) -> Any:
102
+ if inspect.isawaitable(value):
103
+ return await value
104
+ return value
105
+
106
+
107
+ class MachineRunner:
108
+ """Executes a resource's state machine against one entity."""
109
+
110
+ def __init__(
111
+ self,
112
+ machine_cls: type[StateMachine],
113
+ state_field: str,
114
+ resource: str,
115
+ *,
116
+ name: str | None = None,
117
+ since_field: str | None = None,
118
+ ) -> None:
119
+ self.machine_cls = machine_cls
120
+ self.state_field = state_field
121
+ self.resource = resource
122
+ self.name = name or state_field
123
+ self.since_field = since_field
124
+ self.info = describe_machine(machine_cls)
125
+
126
+ def _bind(self, entity: Any) -> StateMachine:
127
+ return self.machine_cls(model=entity, state_field=self.state_field)
128
+
129
+ def current(self, entity: Any) -> Any:
130
+ """The entity's current state."""
131
+ return getattr(entity, self.state_field, None)
132
+
133
+ async def initialize(self, entity: Any) -> None:
134
+ """Set the initial state on a new entity if it has none."""
135
+ if self.current(entity) is not None:
136
+ return
137
+ sm = self._bind(entity)
138
+ if self.current(entity) is None: # async engines activate lazily
139
+ await _maybe_await(sm.activate_initial_state())
140
+
141
+ def allowed_events(self, entity: Any) -> list[str]:
142
+ """Events the current state has transitions for (guards not run)."""
143
+ return [e.id for e in self._bind(entity).allowed_events]
144
+
145
+ async def enabled_events(self, entity: Any) -> list[str]:
146
+ """Events whose guards also pass now. Guards that need the transition's
147
+ input cannot run without it: those events are kept."""
148
+ sm = self._bind(entity)
149
+ allowed = [e.id for e in sm.allowed_events]
150
+ try:
151
+ enabled = {e.id for e in await _maybe_await(sm.enabled_events())}
152
+ except Exception: # a guard needs the transition's input
153
+ return allowed
154
+ return [e for e in allowed if e in enabled]
155
+
156
+ async def fire(self, entity: Any, event: str, payload: dict[str, Any]) -> tuple[Any, Any]:
157
+ """Fire ``event`` on ``entity``. Returns ``(previous_state, new_state)``."""
158
+ if event not in self.info.events:
159
+ raise UnknownTransition(
160
+ f"Resource {self.resource!r} has no transition {event!r}",
161
+ hint=f"Available transitions: {', '.join(self.info.events) or '(none)'}",
162
+ )
163
+ previous = self.current(entity)
164
+ sm = self._bind(entity)
165
+ try:
166
+ await _maybe_await(sm.send(event, **payload))
167
+ except _SMTransitionNotAllowed as exc:
168
+ allowed = [e.id for e in sm.allowed_events]
169
+ raise TransitionNotAllowed(
170
+ f"Transition {event!r} is not allowed for {self.resource!r} in state {previous!r}",
171
+ hint=(
172
+ f"Allowed transitions from {previous!r}: {', '.join(allowed) or '(none)'}. "
173
+ "If the transition has guard conditions, they returned False."
174
+ ),
175
+ details={"state": previous, "allowed": allowed},
176
+ ) from exc
177
+ return previous, self.current(entity)