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,277 @@
1
+ """Idempotency keys for writes: a retried request returns the first result
2
+ instead of running again. See docs/idempotency.md.
3
+
4
+ ``create``, ``update``, ``delete``, ``transition`` and ``run_action`` accept
5
+ ``idempotency_key=``. The first call with a key runs normally and stores its
6
+ result in the same transaction as the change. A later call by the same caller
7
+ with the same key and the same request returns that result without running;
8
+ with a different request it fails (RE-E107). Two calls racing with one key
9
+ both run, but only one commits: the other rolls back and replays the winner.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import functools
15
+ import hashlib
16
+ import inspect
17
+ import json
18
+ import logging
19
+ import re
20
+ from collections.abc import Callable, Mapping
21
+ from contextvars import ContextVar
22
+ from dataclasses import dataclass
23
+ from datetime import UTC, datetime, timedelta
24
+ from typing import TYPE_CHECKING, Any
25
+
26
+ from pydantic import BaseModel, TypeAdapter
27
+
28
+ from resource_engine.errors import (
29
+ ConfigurationError,
30
+ IdempotencyKeyReused,
31
+ IdempotencyNotSupported,
32
+ ValidationFailed,
33
+ )
34
+ from resource_engine.ports.idempotency import IdempotencyRecord, SupportsIdempotency
35
+
36
+ if TYPE_CHECKING:
37
+ from resource_engine.application.context import OperationContext
38
+
39
+ logger = logging.getLogger("resource_engine.idempotency")
40
+
41
+ KEY = re.compile(r"[\x21-\x7e]{1,255}") # printable ASCII, no spaces
42
+
43
+
44
+ @dataclass
45
+ class _Request:
46
+ scope: str
47
+ key: str
48
+ fingerprint: str
49
+ resource: str
50
+ operation: str
51
+ ctx: OperationContext | None = None # the operation's own context, once created
52
+
53
+
54
+ _pending: ContextVar[_Request | None] = ContextVar("resource_engine_idempotency", default=None)
55
+
56
+
57
+ def pending_for(ctx: OperationContext) -> _Request | None:
58
+ """The idempotent request ``ctx`` belongs to (only the top operation's
59
+ context, not those of operations its hooks start)."""
60
+ request = _pending.get()
61
+ if request is None:
62
+ return None
63
+ if request.ctx is None:
64
+ request.ctx = ctx
65
+ return request if request.ctx is ctx else None
66
+
67
+
68
+ def scope_of(actor: Any) -> str:
69
+ """The idempotency scope of a caller: its actor id, or ``anonymous``."""
70
+ from resource_engine.audit.recorder import actor_id
71
+
72
+ return actor_id(actor) or "anonymous"
73
+
74
+
75
+ def fingerprint(operation: str, resource: str, arguments: dict[str, Any]) -> str:
76
+ """SHA-256 of an operation's arguments, to tell a retry from a different request with the same
77
+ key."""
78
+ from resource_engine.audit.recorder import jsonable
79
+
80
+ payload = {"operation": operation, "resource": resource, "arguments": arguments}
81
+ text = json.dumps(jsonable(payload), sort_keys=True, separators=(",", ":"), default=str)
82
+ return hashlib.sha256(text.encode()).hexdigest()
83
+
84
+
85
+ def _input(value: Any) -> Any:
86
+ if isinstance(value, BaseModel):
87
+ return value.model_dump(mode="json", exclude_unset=True)
88
+ return value
89
+
90
+
91
+ # ------------------------------------------------------------------- results
92
+
93
+
94
+ def encode(ctx: OperationContext, result: Any) -> dict[str, Any]:
95
+ """The result as JSON, with what is needed to rebuild it."""
96
+ from resource_engine.audit.recorder import jsonable
97
+ from resource_engine.authz.fields import hidden_fields
98
+
99
+ if result is None:
100
+ return {"kind": "none"}
101
+ if isinstance(result, BaseModel):
102
+ hidden = sorted(hidden_fields(result))
103
+ schema = "read" if type(result) is ctx.resource.schemas.get("read") else "output"
104
+ return {
105
+ "kind": "model",
106
+ "schema": schema,
107
+ # secrets shown once (an API key) are never stored for replays
108
+ "data": result.model_dump(
109
+ mode="json", exclude=set(hidden) | set(ctx.extras.get("never_store", ()))
110
+ ),
111
+ "hidden": hidden,
112
+ }
113
+ return {"kind": "json", "data": jsonable(result)}
114
+
115
+
116
+ def decode(definition: Any, operation: str, action: str | None, stored: Mapping[str, Any]) -> Any:
117
+ """The stored result of an operation, as the caller would have received it the first time."""
118
+ from resource_engine.authz.fields import mask
119
+
120
+ kind = stored.get("kind")
121
+ if kind == "none":
122
+ return None
123
+ if kind == "json":
124
+ return stored.get("data")
125
+ if stored.get("schema") == "output":
126
+ schema = definition.actions[action].output_schema if action else None
127
+ else:
128
+ schema = definition.schemas.get("read")
129
+ if schema is None:
130
+ return stored.get("data")
131
+ data, hidden = stored.get("data", {}), stored.get("hidden", [])
132
+ if not hidden:
133
+ return schema.model_validate(data)
134
+ values = {
135
+ name: TypeAdapter(info.annotation).validate_python(data[name])
136
+ for name, info in schema.model_fields.items()
137
+ if name in data
138
+ }
139
+ return mask(schema.model_construct(**values), hidden)
140
+
141
+
142
+ # ---------------------------------------------------------------- decorator
143
+
144
+
145
+ def idempotent(operation: str) -> Callable[[Any], Any]:
146
+ """Make a manager write accept ``idempotency_key=``."""
147
+
148
+ def decorate(fn: Any) -> Any:
149
+ signature = inspect.signature(fn)
150
+
151
+ @functools.wraps(fn)
152
+ async def wrapper(manager: Any, *args: Any, **kwargs: Any) -> Any:
153
+ key = kwargs.get("idempotency_key")
154
+ if key is None:
155
+ return await fn(manager, *args, **kwargs)
156
+ if not isinstance(key, str) or not KEY.fullmatch(key):
157
+ raise ValidationFailed(
158
+ "Invalid idempotency key: use 1 to 255 printable ASCII characters",
159
+ details=[{"loc": ["idempotency_key"], "msg": "invalid idempotency key"}],
160
+ )
161
+ bound = signature.bind(manager, *args, **kwargs)
162
+ arguments = {
163
+ name: _input(value)
164
+ for name, value in bound.arguments.items()
165
+ if name not in ("self", "actor", "idempotency_key")
166
+ }
167
+ definition = manager.registry.get(arguments.pop("resource"))
168
+ request = _Request(
169
+ scope=scope_of(kwargs.get("actor")),
170
+ key=key,
171
+ fingerprint=fingerprint(operation, definition.name, arguments),
172
+ resource=definition.name,
173
+ operation=operation,
174
+ )
175
+ action = arguments.get("action") if operation == "action" else None
176
+ found = await _lookup(manager, request)
177
+ if found is not None:
178
+ return decode(definition, operation, action, found.result)
179
+ token = _pending.set(request)
180
+ try:
181
+ return await fn(manager, *args, **kwargs)
182
+ except Exception:
183
+ found = await _lookup(manager, request) # a racing duplicate committed first
184
+ if found is None:
185
+ raise
186
+ logger.info("Idempotency key %s replayed after a concurrent duplicate", key)
187
+ return decode(definition, operation, action, found.result)
188
+ finally:
189
+ _pending.reset(token)
190
+
191
+ return wrapper
192
+
193
+ return decorate
194
+
195
+
196
+ async def _lookup(manager: Any, request: _Request) -> IdempotencyRecord | None:
197
+ async with manager._reading() as uow:
198
+ record: IdempotencyRecord | None = await _store(uow).get(request.scope, request.key)
199
+ if record is None or (
200
+ record.expires_at is not None and _aware(record.expires_at) <= datetime.now(UTC)
201
+ ):
202
+ return None
203
+ if record.fingerprint != request.fingerprint:
204
+ raise IdempotencyKeyReused(
205
+ f"The idempotency key {request.key!r} was used for another request",
206
+ hint="Use a new key for every distinct request; reuse a key only to retry "
207
+ "exactly the same one.",
208
+ details={
209
+ "key": request.key,
210
+ "first": {"resource": record.resource, "operation": record.operation},
211
+ },
212
+ )
213
+ return record
214
+
215
+
216
+ async def store_result(manager: Any, ctx: OperationContext, uow: Any) -> None:
217
+ """Step 9, before commit: store the result of an idempotent write."""
218
+ request = pending_for(ctx)
219
+ if request is None:
220
+ return
221
+ now = datetime.now(UTC)
222
+ await _store(uow).put(
223
+ IdempotencyRecord(
224
+ scope=request.scope,
225
+ key=request.key,
226
+ fingerprint=request.fingerprint,
227
+ resource=request.resource,
228
+ operation=request.operation,
229
+ result=encode(ctx, ctx.result),
230
+ created_at=now,
231
+ expires_at=now + manager.idempotency_ttl,
232
+ )
233
+ )
234
+
235
+
236
+ def _store(uow: Any) -> Any:
237
+ if not isinstance(uow, SupportsIdempotency):
238
+ raise IdempotencyNotSupported(
239
+ f"{type(uow).__name__} has no idempotency store",
240
+ hint="Use the in-memory unit of work, or pass idempotency_table= to the "
241
+ "SQLAlchemy unit of work factory (engine_tables(metadata, idempotency=True)).",
242
+ doc="docs/idempotency.md",
243
+ )
244
+ return uow.idempotency()
245
+
246
+
247
+ def _aware(value: datetime) -> datetime:
248
+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value
249
+
250
+
251
+ # ------------------------------------------------------------------ janitor
252
+
253
+
254
+ class IdempotencyJanitor:
255
+ """Deletes expired idempotency records. Run ``run_once`` periodically (it is
256
+ a ``JobRunner`` job)."""
257
+
258
+ def __init__(self, uow_factory: Callable[[], Any], *, batch_size: int = 1000) -> None:
259
+ if batch_size < 1:
260
+ raise ConfigurationError("batch_size must be at least 1")
261
+ self.uow_factory = uow_factory
262
+ self.batch_size = batch_size
263
+
264
+ async def run_once(self, now: datetime | None = None) -> int:
265
+ """Delete the records that expired before ``now``, in batches; returns how many."""
266
+ now = now or datetime.now(UTC)
267
+ total = 0
268
+ while True:
269
+ async with self.uow_factory() as uow:
270
+ deleted: int = await _store(uow).purge(now, self.batch_size)
271
+ await uow.commit()
272
+ total += deleted
273
+ if deleted < self.batch_size:
274
+ return total
275
+
276
+
277
+ DEFAULT_TTL = timedelta(hours=24)