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.
- resource_engine/__init__.py +96 -0
- resource_engine/application/__init__.py +1 -0
- resource_engine/application/actions.py +48 -0
- resource_engine/application/context.py +111 -0
- resource_engine/application/events.py +54 -0
- resource_engine/application/hooks.py +272 -0
- resource_engine/application/idempotency.py +277 -0
- resource_engine/application/manager.py +1987 -0
- resource_engine/application/query.py +47 -0
- resource_engine/application/registry.py +137 -0
- resource_engine/application/relations.py +470 -0
- resource_engine/application/resource.py +984 -0
- resource_engine/application/searching.py +162 -0
- resource_engine/application/settings.py +169 -0
- resource_engine/application/slots.py +67 -0
- resource_engine/application/state_machines.py +177 -0
- resource_engine/application/timers.py +347 -0
- resource_engine/application/transaction.py +100 -0
- resource_engine/application/views.py +239 -0
- resource_engine/audit/__init__.py +40 -0
- resource_engine/audit/export.py +280 -0
- resource_engine/audit/history.py +165 -0
- resource_engine/audit/janitor.py +257 -0
- resource_engine/audit/model.py +98 -0
- resource_engine/audit/recorder.py +145 -0
- resource_engine/audit/resource.py +68 -0
- resource_engine/audit/seal.py +327 -0
- resource_engine/audit/sink.py +69 -0
- resource_engine/authz/__init__.py +72 -0
- resource_engine/authz/apikeys.py +300 -0
- resource_engine/authz/base.py +143 -0
- resource_engine/authz/catalog.py +291 -0
- resource_engine/authz/conditions.py +416 -0
- resource_engine/authz/config.py +77 -0
- resource_engine/authz/evaluator.py +382 -0
- resource_engine/authz/external.py +249 -0
- resource_engine/authz/fields.py +44 -0
- resource_engine/authz/model.py +145 -0
- resource_engine/authz/resources.py +289 -0
- resource_engine/authz/roles.py +101 -0
- resource_engine/cache.py +144 -0
- resource_engine/calls.py +100 -0
- resource_engine/capabilities.py +145 -0
- resource_engine/composite.py +295 -0
- resource_engine/documents/__init__.py +69 -0
- resource_engine/documents/content.py +57 -0
- resource_engine/documents/events.py +49 -0
- resource_engine/documents/janitor.py +93 -0
- resource_engine/documents/machine.py +38 -0
- resource_engine/documents/manager.py +704 -0
- resource_engine/documents/model.py +91 -0
- resource_engine/documents/pipeline.py +98 -0
- resource_engine/documents/processors.py +320 -0
- resource_engine/documents/resource.py +39 -0
- resource_engine/domain/__init__.py +10 -0
- resource_engine/domain/events.py +50 -0
- resource_engine/domain/exceptions.py +23 -0
- resource_engine/email.py +417 -0
- resource_engine/errors.py +562 -0
- resource_engine/explorer.py +133 -0
- resource_engine/exports.py +687 -0
- resource_engine/generation.py +233 -0
- resource_engine/i18n.py +251 -0
- resource_engine/identity.py +46 -0
- resource_engine/integration.py +80 -0
- resource_engine/jobs.py +390 -0
- resource_engine/locale/ca/LC_MESSAGES/resource_engine.mo +0 -0
- resource_engine/locale/ca/LC_MESSAGES/resource_engine.po +206 -0
- resource_engine/locale/es/LC_MESSAGES/resource_engine.mo +0 -0
- resource_engine/locale/es/LC_MESSAGES/resource_engine.po +206 -0
- resource_engine/logs.py +201 -0
- resource_engine/messaging/__init__.py +73 -0
- resource_engine/messaging/asyncapi.py +529 -0
- resource_engine/messaging/cloudevents.py +98 -0
- resource_engine/messaging/consumer.py +165 -0
- resource_engine/messaging/delivery.py +115 -0
- resource_engine/messaging/envelope.py +193 -0
- resource_engine/messaging/hub.py +148 -0
- resource_engine/messaging/inbound.py +76 -0
- resource_engine/messaging/inspection.py +113 -0
- resource_engine/messaging/janitor.py +136 -0
- resource_engine/messaging/live.py +179 -0
- resource_engine/messaging/processing.py +357 -0
- resource_engine/messaging/publishing.py +318 -0
- resource_engine/messaging/relay.py +84 -0
- resource_engine/messaging/worker.py +166 -0
- resource_engine/nosql.py +394 -0
- resource_engine/ports/__init__.py +13 -0
- resource_engine/ports/activity.py +171 -0
- resource_engine/ports/audit.py +42 -0
- resource_engine/ports/authz.py +132 -0
- resource_engine/ports/cache.py +41 -0
- resource_engine/ports/email.py +118 -0
- resource_engine/ports/event_publisher.py +34 -0
- resource_engine/ports/idempotency.py +69 -0
- resource_engine/ports/identity.py +112 -0
- resource_engine/ports/locks.py +28 -0
- resource_engine/ports/messaging.py +197 -0
- resource_engine/ports/observability.py +60 -0
- resource_engine/ports/ratelimit.py +59 -0
- resource_engine/ports/repository.py +56 -0
- resource_engine/ports/storage.py +93 -0
- resource_engine/ports/templates.py +54 -0
- resource_engine/ports/tracing.py +61 -0
- resource_engine/ports/unit_of_work.py +46 -0
- resource_engine/processes.py +408 -0
- resource_engine/py.typed +0 -0
- resource_engine/querying.py +319 -0
- resource_engine/ratelimit.py +217 -0
- resource_engine/reporting.py +230 -0
- resource_engine/schema_examples.py +51 -0
- resource_engine/templates.py +143 -0
- resource_engine/tenancy.py +68 -0
- resource_engine/testing/__init__.py +34 -0
- resource_engine/testing/activity.py +123 -0
- resource_engine/testing/contracts.py +1416 -0
- resource_engine/testing/email.py +36 -0
- resource_engine/testing/engine.py +40 -0
- resource_engine/testing/memory.py +603 -0
- resource_engine/testing/storage.py +110 -0
- resource_engine/testing/tracing.py +100 -0
- resource_engine/tracing.py +156 -0
- resource_engine/translatable.py +80 -0
- resource_engine/versions.py +189 -0
- resource_engine-0.1.0.dist-info/METADATA +36 -0
- resource_engine-0.1.0.dist-info/RECORD +128 -0
- resource_engine-0.1.0.dist-info/WHEEL +4 -0
- resource_engine-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""In-memory ``BlobStore`` with fake presigned URLs, for tests and prototypes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import secrets
|
|
6
|
+
from collections.abc import AsyncIterator, Sequence
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from datetime import UTC, datetime, timedelta
|
|
9
|
+
from typing import override
|
|
10
|
+
|
|
11
|
+
from resource_engine.documents.content import Measured, read_all
|
|
12
|
+
from resource_engine.errors import BlobNotFound
|
|
13
|
+
from resource_engine.ports.storage import (
|
|
14
|
+
BlobInfo,
|
|
15
|
+
BlobStore,
|
|
16
|
+
Content,
|
|
17
|
+
PresignedRequest,
|
|
18
|
+
SupportsPresignedUrls,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class _Blob:
|
|
24
|
+
data: bytes
|
|
25
|
+
info: BlobInfo
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class InMemoryBlobStore(BlobStore, SupportsPresignedUrls):
|
|
30
|
+
"""Blobs in a dict. Presigned URLs look like ``memory://put/<token>``; tests
|
|
31
|
+
complete them with ``upload(request, data)`` and ``download(request)``."""
|
|
32
|
+
|
|
33
|
+
blobs: dict[str, _Blob] = field(default_factory=dict)
|
|
34
|
+
_tokens: dict[str, tuple[str, str, datetime]] = field(default_factory=dict)
|
|
35
|
+
|
|
36
|
+
@override
|
|
37
|
+
async def put(
|
|
38
|
+
self, key: str, content: Content, *, content_type: str, max_bytes: int | None = None
|
|
39
|
+
) -> BlobInfo:
|
|
40
|
+
measured = Measured(content, max_bytes=max_bytes)
|
|
41
|
+
data = await read_all(measured)
|
|
42
|
+
info = BlobInfo(
|
|
43
|
+
key=key,
|
|
44
|
+
size=len(data),
|
|
45
|
+
content_type=content_type,
|
|
46
|
+
etag=measured.sha256[:32],
|
|
47
|
+
last_modified=datetime.now(UTC),
|
|
48
|
+
sha256=measured.sha256,
|
|
49
|
+
)
|
|
50
|
+
self.blobs[key] = _Blob(data, info)
|
|
51
|
+
return info
|
|
52
|
+
|
|
53
|
+
@override
|
|
54
|
+
async def open(self, key: str) -> AsyncIterator[bytes]:
|
|
55
|
+
blob = self.blobs.get(key)
|
|
56
|
+
if blob is None:
|
|
57
|
+
raise BlobNotFound(f"No blob {key!r}")
|
|
58
|
+
yield blob.data
|
|
59
|
+
|
|
60
|
+
@override
|
|
61
|
+
async def head(self, key: str) -> BlobInfo | None:
|
|
62
|
+
blob = self.blobs.get(key)
|
|
63
|
+
return blob.info if blob else None
|
|
64
|
+
|
|
65
|
+
@override
|
|
66
|
+
async def delete(self, keys: Sequence[str]) -> None:
|
|
67
|
+
for key in keys:
|
|
68
|
+
self.blobs.pop(key, None)
|
|
69
|
+
|
|
70
|
+
@override
|
|
71
|
+
async def list(self, prefix: str = "") -> AsyncIterator[BlobInfo]:
|
|
72
|
+
for key in sorted(self.blobs):
|
|
73
|
+
if key.startswith(prefix):
|
|
74
|
+
yield self.blobs[key].info
|
|
75
|
+
|
|
76
|
+
@override
|
|
77
|
+
async def presign_put(
|
|
78
|
+
self, key: str, *, content_type: str, expires: timedelta
|
|
79
|
+
) -> PresignedRequest:
|
|
80
|
+
token = secrets.token_hex(8)
|
|
81
|
+
expires_at = datetime.now(UTC) + expires
|
|
82
|
+
self._tokens[token] = ("PUT", key, expires_at)
|
|
83
|
+
return PresignedRequest(
|
|
84
|
+
f"memory://put/{token}", "PUT", expires_at, {"Content-Type": content_type}
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
@override
|
|
88
|
+
async def presign_get(
|
|
89
|
+
self, key: str, *, expires: timedelta, download_name: str | None = None
|
|
90
|
+
) -> PresignedRequest:
|
|
91
|
+
token = secrets.token_hex(8)
|
|
92
|
+
expires_at = datetime.now(UTC) + expires
|
|
93
|
+
self._tokens[token] = ("GET", key, expires_at)
|
|
94
|
+
return PresignedRequest(f"memory://get/{token}", "GET", expires_at)
|
|
95
|
+
|
|
96
|
+
def _resolve(self, request: PresignedRequest, method: str) -> str:
|
|
97
|
+
token = request.url.rsplit("/", 1)[-1]
|
|
98
|
+
kind, key, expires_at = self._tokens[token]
|
|
99
|
+
if kind != method or datetime.now(UTC) > expires_at:
|
|
100
|
+
raise PermissionError("Presigned URL is invalid or expired")
|
|
101
|
+
return key
|
|
102
|
+
|
|
103
|
+
async def upload(self, request: PresignedRequest, data: bytes) -> None:
|
|
104
|
+
"""Simulate the client's direct upload to a presigned PUT URL."""
|
|
105
|
+
key = self._resolve(request, "PUT")
|
|
106
|
+
await self.put(key, data, content_type=request.headers.get("Content-Type", ""))
|
|
107
|
+
|
|
108
|
+
async def download(self, request: PresignedRequest) -> bytes:
|
|
109
|
+
"""The content a presigned download request would fetch."""
|
|
110
|
+
return await read_all(self.open(self._resolve(request, "GET")))
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""``RecordingTracer``: an in-memory ``Tracer`` for tests (W3C-style ids)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import secrets
|
|
6
|
+
from collections.abc import AsyncIterator, Mapping
|
|
7
|
+
from contextlib import asynccontextmanager
|
|
8
|
+
from contextvars import ContextVar
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from typing import Any, override
|
|
11
|
+
|
|
12
|
+
from resource_engine.ports.tracing import Span, SpanKind, Tracer
|
|
13
|
+
from resource_engine.tracing import NOOP_SPAN
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class RecordedSpan(Span):
|
|
18
|
+
"""A span a recording tracer kept, to check in tests."""
|
|
19
|
+
|
|
20
|
+
name: str
|
|
21
|
+
kind: str
|
|
22
|
+
trace_id: str
|
|
23
|
+
span_id: str
|
|
24
|
+
parent_id: str | None
|
|
25
|
+
attributes: dict[str, Any] = field(default_factory=dict)
|
|
26
|
+
errors: list[BaseException | str] = field(default_factory=list)
|
|
27
|
+
ended: bool = False
|
|
28
|
+
|
|
29
|
+
@override
|
|
30
|
+
def set_attribute(self, key: str, value: Any) -> None:
|
|
31
|
+
self.attributes[key] = value
|
|
32
|
+
|
|
33
|
+
@override
|
|
34
|
+
def record_error(self, error: BaseException | str) -> None:
|
|
35
|
+
self.errors.append(error)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class RecordingTracer(Tracer):
|
|
39
|
+
"""Records every span. ``spans`` are in start order."""
|
|
40
|
+
|
|
41
|
+
def __init__(self) -> None:
|
|
42
|
+
self.spans: list[RecordedSpan] = []
|
|
43
|
+
self._current: ContextVar[RecordedSpan | None] = ContextVar("span", default=None)
|
|
44
|
+
|
|
45
|
+
@asynccontextmanager
|
|
46
|
+
@override
|
|
47
|
+
async def span(
|
|
48
|
+
self,
|
|
49
|
+
name: str,
|
|
50
|
+
*,
|
|
51
|
+
kind: SpanKind = "internal",
|
|
52
|
+
attributes: Mapping[str, Any] | None = None,
|
|
53
|
+
parent: Mapping[str, str] | None = None,
|
|
54
|
+
) -> AsyncIterator[RecordedSpan]:
|
|
55
|
+
trace_id, parent_id = None, None
|
|
56
|
+
remote = _parse(parent.get("traceparent")) if parent else None
|
|
57
|
+
if remote is not None:
|
|
58
|
+
trace_id, parent_id = remote
|
|
59
|
+
elif (current := self._current.get()) is not None:
|
|
60
|
+
trace_id, parent_id = current.trace_id, current.span_id
|
|
61
|
+
span = RecordedSpan(
|
|
62
|
+
name,
|
|
63
|
+
kind,
|
|
64
|
+
trace_id or secrets.token_hex(16),
|
|
65
|
+
secrets.token_hex(8),
|
|
66
|
+
parent_id,
|
|
67
|
+
dict(attributes or {}),
|
|
68
|
+
)
|
|
69
|
+
self.spans.append(span)
|
|
70
|
+
token = self._current.set(span)
|
|
71
|
+
try:
|
|
72
|
+
yield span
|
|
73
|
+
except BaseException as exc:
|
|
74
|
+
span.errors.append(exc)
|
|
75
|
+
raise
|
|
76
|
+
finally:
|
|
77
|
+
span.ended = True
|
|
78
|
+
self._current.reset(token)
|
|
79
|
+
|
|
80
|
+
@override
|
|
81
|
+
def current(self) -> Any:
|
|
82
|
+
return self._current.get() or NOOP_SPAN
|
|
83
|
+
|
|
84
|
+
@override
|
|
85
|
+
def inject(self) -> dict[str, str]:
|
|
86
|
+
span = self._current.get()
|
|
87
|
+
return {"traceparent": f"00-{span.trace_id}-{span.span_id}-01"} if span else {}
|
|
88
|
+
|
|
89
|
+
def named(self, name: str) -> RecordedSpan:
|
|
90
|
+
"""The one span called ``name``; fails when there is none or several."""
|
|
91
|
+
matches = [s for s in self.spans if s.name == name]
|
|
92
|
+
assert len(matches) == 1, (
|
|
93
|
+
f"{len(matches)} spans named {name!r}: {[s.name for s in self.spans]}"
|
|
94
|
+
)
|
|
95
|
+
return matches[0]
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _parse(traceparent: str | None) -> tuple[str, str] | None:
|
|
99
|
+
parts = (traceparent or "").split("-")
|
|
100
|
+
return (parts[1], parts[2]) if len(parts) == 4 else None
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""Configured tracer and the no-op default. See docs/observability.md.
|
|
2
|
+
|
|
3
|
+
```python
|
|
4
|
+
from resource_engine.tracing import set_tracer
|
|
5
|
+
from resource_engine_opentelemetry import OtelTracer
|
|
6
|
+
|
|
7
|
+
set_tracer(OtelTracer())
|
|
8
|
+
```
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import functools
|
|
14
|
+
import inspect
|
|
15
|
+
import logging
|
|
16
|
+
import time
|
|
17
|
+
from collections.abc import AsyncIterator, Callable, Mapping
|
|
18
|
+
from contextlib import asynccontextmanager
|
|
19
|
+
from typing import Any, TypeVar, cast, override
|
|
20
|
+
|
|
21
|
+
from resource_engine.logs import bind_log_context, error_type
|
|
22
|
+
from resource_engine.ports.observability import OperationRun
|
|
23
|
+
from resource_engine.ports.tracing import Span, SpanKind, Tracer
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger("resource_engine")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class NoopSpan(Span):
|
|
29
|
+
"""A span that records nothing, used when no tracer is installed."""
|
|
30
|
+
|
|
31
|
+
@override
|
|
32
|
+
def set_attribute(self, key: str, value: Any) -> None:
|
|
33
|
+
pass
|
|
34
|
+
|
|
35
|
+
@override
|
|
36
|
+
def record_error(self, error: BaseException | str) -> None:
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
NOOP_SPAN = NoopSpan()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class NoopTracer(Tracer):
|
|
44
|
+
"""The default: no spans, empty carriers, nothing to configure."""
|
|
45
|
+
|
|
46
|
+
@asynccontextmanager
|
|
47
|
+
@override
|
|
48
|
+
async def span(
|
|
49
|
+
self,
|
|
50
|
+
name: str,
|
|
51
|
+
*,
|
|
52
|
+
kind: SpanKind = "internal",
|
|
53
|
+
attributes: Mapping[str, Any] | None = None,
|
|
54
|
+
parent: Mapping[str, str] | None = None,
|
|
55
|
+
) -> AsyncIterator[Span]:
|
|
56
|
+
yield NOOP_SPAN
|
|
57
|
+
|
|
58
|
+
@override
|
|
59
|
+
def current(self) -> Span:
|
|
60
|
+
return NOOP_SPAN
|
|
61
|
+
|
|
62
|
+
@override
|
|
63
|
+
def inject(self) -> dict[str, str]:
|
|
64
|
+
return {}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
_tracer: Tracer = NoopTracer()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def set_tracer(tracer: Tracer | None) -> Tracer:
|
|
71
|
+
"""Use ``tracer`` everywhere (``None`` goes back to no tracing). Returns the
|
|
72
|
+
previous one."""
|
|
73
|
+
global _tracer
|
|
74
|
+
previous = _tracer
|
|
75
|
+
_tracer = tracer or NoopTracer()
|
|
76
|
+
return previous
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def get_tracer() -> Tracer:
|
|
80
|
+
"""The tracer installed with ``set_tracer`` (one that records nothing by default)."""
|
|
81
|
+
return _tracer
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _resource_name(manager: Any, resource: Any) -> str:
|
|
85
|
+
if isinstance(resource, str):
|
|
86
|
+
return resource
|
|
87
|
+
try:
|
|
88
|
+
name: str = manager.registry.get(resource).name
|
|
89
|
+
return name
|
|
90
|
+
except Exception:
|
|
91
|
+
return str(resource)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
_Method = TypeVar("_Method", bound=Callable[..., Any])
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def traced(operation: str, *, resource: str | None = None) -> Callable[[_Method], _Method]:
|
|
98
|
+
"""Wrap a manager method in a span named ``"<resource> <operation>"``, a log
|
|
99
|
+
context and a call to the manager's operation observers. The resource is
|
|
100
|
+
the method's first argument unless given."""
|
|
101
|
+
|
|
102
|
+
def decorate(fn: _Method) -> _Method:
|
|
103
|
+
@functools.wraps(fn)
|
|
104
|
+
async def wrapper(self: Any, *args: Any, **kwargs: Any) -> Any:
|
|
105
|
+
manager = getattr(self, "manager", self)
|
|
106
|
+
name = resource or (_resource_name(manager, args[0]) if args else "?")
|
|
107
|
+
attributes = {"resource_engine.resource": name, "resource_engine.operation": operation}
|
|
108
|
+
observers = getattr(manager, "observers", ())
|
|
109
|
+
started = time.perf_counter()
|
|
110
|
+
error: BaseException | None = None
|
|
111
|
+
with bind_log_context(resource=name, operation=operation) as context:
|
|
112
|
+
# a nested operation starts its own: drop the outer one's identity
|
|
113
|
+
for key in ("correlation_id", "entity_id", "action"):
|
|
114
|
+
context.pop(key, None)
|
|
115
|
+
try:
|
|
116
|
+
async with _tracer.span(f"{name} {operation}", attributes=attributes):
|
|
117
|
+
return await fn(self, *args, **kwargs)
|
|
118
|
+
except BaseException as exc:
|
|
119
|
+
error = exc
|
|
120
|
+
if isinstance(exc, Exception):
|
|
121
|
+
from resource_engine.reporting import report_error
|
|
122
|
+
|
|
123
|
+
await report_error(exc, where="operation", actor=kwargs.get("actor"))
|
|
124
|
+
raise
|
|
125
|
+
finally:
|
|
126
|
+
if observers:
|
|
127
|
+
await _observe(
|
|
128
|
+
observers,
|
|
129
|
+
OperationRun(
|
|
130
|
+
resource=name,
|
|
131
|
+
operation=operation,
|
|
132
|
+
outcome="ok" if error is None else "failed",
|
|
133
|
+
seconds=time.perf_counter() - started,
|
|
134
|
+
action=context.get("action"),
|
|
135
|
+
error_type=error_type(error),
|
|
136
|
+
correlation_id=context.get("correlation_id"),
|
|
137
|
+
error=error,
|
|
138
|
+
),
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
return cast("_Method", wrapper) # same signature: the method's own
|
|
142
|
+
|
|
143
|
+
return decorate
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
async def _observe(observers: Any, run: OperationRun) -> None:
|
|
147
|
+
for observer in observers:
|
|
148
|
+
try:
|
|
149
|
+
result = observer(run)
|
|
150
|
+
if inspect.isawaitable(result):
|
|
151
|
+
await result
|
|
152
|
+
except Exception:
|
|
153
|
+
logger.exception("Operation observer %r failed", observer)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
__all__ = ["NOOP_SPAN", "NoopSpan", "NoopTracer", "get_tracer", "set_tracer", "traced"]
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Translatable data: a field that holds one text per language (a product
|
|
2
|
+
name, a category description), stored as ``{locale: text}``.
|
|
3
|
+
|
|
4
|
+
```python
|
|
5
|
+
@dataclass
|
|
6
|
+
class Product:
|
|
7
|
+
sku: str
|
|
8
|
+
name: dict[str, str] = field(default_factory=dict) # {"ca": "Cadira", "en": "Chair"}
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ProductRead(BaseModel):
|
|
12
|
+
sku: str
|
|
13
|
+
name: str | None # in the request's language
|
|
14
|
+
name_translations: dict[str, str] = {} # optional: every language
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ProductResource(Resource):
|
|
18
|
+
translatable = Translatable("name", default_locale="ca")
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
- **Reading** gives the text in the request's language (``Accept-Language``,
|
|
22
|
+
the token's ``locale``), falling back to its base language (``ca-ES`` →
|
|
23
|
+
``ca``), then ``default_locale``, then any language there is.
|
|
24
|
+
- **Writing** ``name`` sets the request's language (or ``default_locale``)
|
|
25
|
+
and keeps the others; ``name_translations`` (when the create or update
|
|
26
|
+
schema declares it) sets several at once, and ``null`` for a language
|
|
27
|
+
removes it.
|
|
28
|
+
- **Filtering and sorting** by a translatable field use the same language
|
|
29
|
+
and fallbacks, in memory and in SQL (``JSON`` columns).
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
from collections.abc import Iterable, Mapping
|
|
35
|
+
from typing import Any
|
|
36
|
+
|
|
37
|
+
from resource_engine.i18n import get_locale
|
|
38
|
+
from resource_engine.templates import locale_candidates
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def locale_chain(default: str | None) -> list[str]:
|
|
42
|
+
"""The languages to try, most specific first, for the current request."""
|
|
43
|
+
return [c for c in locale_candidates(get_locale(), default) if c]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def localise(value: Any, chain: Iterable[str]) -> Any:
|
|
47
|
+
"""The text of ``value`` (``{locale: text}``) for the first language of
|
|
48
|
+
``chain`` that has one; any language as a last resort."""
|
|
49
|
+
if not isinstance(value, Mapping):
|
|
50
|
+
return value
|
|
51
|
+
for locale in chain:
|
|
52
|
+
text = value.get(locale)
|
|
53
|
+
if text not in (None, ""):
|
|
54
|
+
return text
|
|
55
|
+
return next((v for v in value.values() if v not in (None, "")), None)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def write_locale(default: str | None) -> str:
|
|
59
|
+
"""The locale a write stores translatable fields in: the request's, else the resource's default,
|
|
60
|
+
else ``en``."""
|
|
61
|
+
return get_locale() or default or "en"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def merge(
|
|
65
|
+
current: Any, text: Any, translations: Mapping[str, Any] | None, locale: str
|
|
66
|
+
) -> dict[str, str]:
|
|
67
|
+
"""``current`` with ``text`` in ``locale`` and the ``translations`` applied
|
|
68
|
+
(``None`` removes a language)."""
|
|
69
|
+
values = dict(current) if isinstance(current, Mapping) else {}
|
|
70
|
+
for key, value in (translations or {}).items():
|
|
71
|
+
if value is None:
|
|
72
|
+
values.pop(key, None)
|
|
73
|
+
else:
|
|
74
|
+
values[str(key)] = str(value)
|
|
75
|
+
if text is not None:
|
|
76
|
+
values[locale] = str(text)
|
|
77
|
+
return values
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
__all__ = ["locale_chain", "localise", "merge", "write_locale"]
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"""Versions of a resource's API and of its events, published side by side,
|
|
2
|
+
with deprecation notices.
|
|
3
|
+
|
|
4
|
+
**API versions.** A resource whose schemas change keeps serving the old ones
|
|
5
|
+
under the old version's prefix (``/v1/invoices`` next to ``/v2/invoices``).
|
|
6
|
+
Each older version converts its input to the current schemas and the current
|
|
7
|
+
output to its schemas; the operation itself (hooks, permissions, events) is
|
|
8
|
+
the same:
|
|
9
|
+
|
|
10
|
+
```python
|
|
11
|
+
class InvoiceResource(Resource):
|
|
12
|
+
schemas = {"create": InvoiceInV2, "read": InvoiceOutV2}
|
|
13
|
+
api_versions = {
|
|
14
|
+
"v1": ApiVersion(
|
|
15
|
+
read=InvoiceOutV1,
|
|
16
|
+
create=InvoiceInV1,
|
|
17
|
+
to_read=lambda out: {**out, "amount": str(out["total"])},
|
|
18
|
+
from_create=lambda data: {**data, "total": data.pop("amount")},
|
|
19
|
+
deprecation=Deprecation(since=date(2026, 12, 1), sunset=date(2027, 6, 30),
|
|
20
|
+
link="https://docs.example.com/invoices/v2"),
|
|
21
|
+
)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
mount_resources(app, registry, manager, versions=["v1", "v2"])
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
**Event versions.** An event whose payload changes declares
|
|
28
|
+
``schema_version = 2`` and keeps publishing the older shapes for consumers
|
|
29
|
+
not yet moved, each as its own message with ``schema_version`` set:
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
@dataclass(frozen=True, kw_only=True)
|
|
33
|
+
class InvoiceApproved(DomainEvent):
|
|
34
|
+
schema_version = 2
|
|
35
|
+
previous_versions = {
|
|
36
|
+
1: EventVersion(InvoiceApprovedV1, lambda p: {**p, "amount": str(p["total"])},
|
|
37
|
+
deprecation=Deprecation(sunset=date(2027, 6, 30))),
|
|
38
|
+
}
|
|
39
|
+
invoice_id: int
|
|
40
|
+
total: Decimal
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Consumers pick the version they are written for
|
|
44
|
+
(``router.on(InvoiceApproved, payload=..., schema_version=2)``); brokers can
|
|
45
|
+
also filter on the ``schema_version`` message attribute.
|
|
46
|
+
|
|
47
|
+
**Deprecation notices** go to the OpenAPI document (``deprecated``), the
|
|
48
|
+
responses (``Deprecation``, ``Sunset`` and ``Link`` headers, RFC 9745 and
|
|
49
|
+
8594), the AsyncAPI document and GraphQL (``@deprecated``). The contract
|
|
50
|
+
checks compare each version with the same version of the published document,
|
|
51
|
+
and let a version go only after its sunset.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
from __future__ import annotations
|
|
55
|
+
|
|
56
|
+
import calendar
|
|
57
|
+
from collections.abc import Callable, Mapping
|
|
58
|
+
from dataclasses import dataclass
|
|
59
|
+
from datetime import UTC, date, datetime
|
|
60
|
+
from email.utils import formatdate
|
|
61
|
+
from typing import Any
|
|
62
|
+
|
|
63
|
+
type Converter = Callable[[dict[str, Any]], dict[str, Any]]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True)
|
|
67
|
+
class Deprecation:
|
|
68
|
+
"""A version, resource or event on its way out.
|
|
69
|
+
|
|
70
|
+
Args:
|
|
71
|
+
since: When it was deprecated (``None``: deprecated, no date).
|
|
72
|
+
sunset: When it stops being served or published.
|
|
73
|
+
link: Where the migration is explained.
|
|
74
|
+
reason: One sentence for the documents (``"Use v2: totals are decimals."``).
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
since: date | None = None
|
|
78
|
+
sunset: date | None = None
|
|
79
|
+
link: str | None = None
|
|
80
|
+
reason: str | None = None
|
|
81
|
+
|
|
82
|
+
def headers(self) -> dict[str, str]:
|
|
83
|
+
"""``Deprecation``, ``Sunset`` and ``Link`` response headers."""
|
|
84
|
+
headers = {"Deprecation": f"@{_epoch(self.since)}" if self.since else "true"}
|
|
85
|
+
if self.sunset:
|
|
86
|
+
headers["Sunset"] = formatdate(_epoch(self.sunset), usegmt=True)
|
|
87
|
+
if self.link:
|
|
88
|
+
headers["Link"] = f'<{self.link}>; rel="deprecation"'
|
|
89
|
+
return headers
|
|
90
|
+
|
|
91
|
+
def notice(self) -> str:
|
|
92
|
+
"""The deprecation in one sentence, for descriptions."""
|
|
93
|
+
parts = ["Deprecated"]
|
|
94
|
+
if self.since:
|
|
95
|
+
parts.append(f"since {self.since.isoformat()}")
|
|
96
|
+
text = " ".join(parts)
|
|
97
|
+
if self.sunset:
|
|
98
|
+
text += f"; removed on {self.sunset.isoformat()}"
|
|
99
|
+
text += "."
|
|
100
|
+
if self.reason:
|
|
101
|
+
text += f" {self.reason}"
|
|
102
|
+
if self.link:
|
|
103
|
+
text += f" See {self.link}"
|
|
104
|
+
return text
|
|
105
|
+
|
|
106
|
+
def to_dict(self) -> dict[str, str]:
|
|
107
|
+
"""The deprecation as JSON-ready data."""
|
|
108
|
+
data = {
|
|
109
|
+
"since": self.since.isoformat() if self.since else None,
|
|
110
|
+
"sunset": self.sunset.isoformat() if self.sunset else None,
|
|
111
|
+
"link": self.link,
|
|
112
|
+
"reason": self.reason,
|
|
113
|
+
}
|
|
114
|
+
return {k: v for k, v in data.items() if v is not None}
|
|
115
|
+
|
|
116
|
+
def past_sunset(self, today: date | None = None) -> bool:
|
|
117
|
+
"""Whether ``today`` is on or after the sunset date."""
|
|
118
|
+
return self.sunset is not None and (today or datetime.now(UTC).date()) >= self.sunset
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _epoch(day: date) -> int:
|
|
122
|
+
return calendar.timegm(day.timetuple())
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def from_dict(data: Mapping[str, Any] | None) -> Deprecation | None:
|
|
126
|
+
"""A ``Deprecation`` from ``to_dict`` output (documents)."""
|
|
127
|
+
if not data:
|
|
128
|
+
return None
|
|
129
|
+
return Deprecation(
|
|
130
|
+
since=date.fromisoformat(data["since"]) if data.get("since") else None,
|
|
131
|
+
sunset=date.fromisoformat(data["sunset"]) if data.get("sunset") else None,
|
|
132
|
+
link=data.get("link"),
|
|
133
|
+
reason=data.get("reason"),
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@dataclass(frozen=True)
|
|
138
|
+
class ApiVersion:
|
|
139
|
+
"""An older version of a resource's API, served next to the current one.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
read / create / update: That version's schemas (``None``: the current one).
|
|
143
|
+
to_read: The current output (dumped to a dict) → that version's.
|
|
144
|
+
from_create / from_update: That version's input (a dict) → the current one's.
|
|
145
|
+
deprecation: Its deprecation notice.
|
|
146
|
+
"""
|
|
147
|
+
|
|
148
|
+
read: Any = None
|
|
149
|
+
create: Any = None
|
|
150
|
+
update: Any = None
|
|
151
|
+
to_read: Converter | None = None
|
|
152
|
+
from_create: Converter | None = None
|
|
153
|
+
from_update: Converter | None = None
|
|
154
|
+
deprecation: Deprecation | None = None
|
|
155
|
+
|
|
156
|
+
def schema(self, role: str, current: Mapping[str, Any]) -> Any:
|
|
157
|
+
"""The version's ``role`` model (input, read...), or the current one."""
|
|
158
|
+
return getattr(self, role, None) or current.get(role)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
@dataclass(frozen=True)
|
|
162
|
+
class EventVersion:
|
|
163
|
+
"""An older version of an event, still published next to the current one.
|
|
164
|
+
|
|
165
|
+
Args:
|
|
166
|
+
schema: Its payload type (the old event class or a model), for the
|
|
167
|
+
AsyncAPI document and typed consumers.
|
|
168
|
+
convert: The current payload (JSON-compatible dict) → this version's.
|
|
169
|
+
deprecation: Its deprecation notice.
|
|
170
|
+
"""
|
|
171
|
+
|
|
172
|
+
schema: Any
|
|
173
|
+
convert: Converter
|
|
174
|
+
deprecation: Deprecation | None = None
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def event_version(event_cls: type) -> int:
|
|
178
|
+
"""The schema version of an event class (``schema_version``, 1 by default)."""
|
|
179
|
+
return int(getattr(event_cls, "schema_version", 1))
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
__all__ = [
|
|
183
|
+
"ApiVersion",
|
|
184
|
+
"Converter",
|
|
185
|
+
"Deprecation",
|
|
186
|
+
"EventVersion",
|
|
187
|
+
"event_version",
|
|
188
|
+
"from_dict",
|
|
189
|
+
]
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: resource-engine
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Declarative resource engine for business backends: resources, lifecycle hooks, state machines, ports.
|
|
5
|
+
Project-URL: Homepage, https://github.com/EloiSans/python-resource-engine
|
|
6
|
+
Project-URL: Documentation, https://github.com/EloiSans/python-resource-engine/tree/main/docs
|
|
7
|
+
Project-URL: Source, https://github.com/EloiSans/python-resource-engine/tree/main/packages/resource-engine
|
|
8
|
+
Project-URL: Issues, https://github.com/EloiSans/python-resource-engine/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/EloiSans/python-resource-engine/blob/main/packages/resource-engine/CHANGELOG.md
|
|
10
|
+
License-Expression: Apache-2.0
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Framework :: AsyncIO
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.12
|
|
23
|
+
Requires-Dist: pydantic>=2.7
|
|
24
|
+
Requires-Dist: python-statemachine>=3.0
|
|
25
|
+
Provides-Extra: testing
|
|
26
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == 'testing'
|
|
27
|
+
Requires-Dist: pytest>=8; extra == 'testing'
|
|
28
|
+
Provides-Extra: xlsx
|
|
29
|
+
Requires-Dist: openpyxl>=3.1; extra == 'xlsx'
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
|
|
32
|
+
# resource-engine
|
|
33
|
+
|
|
34
|
+
Core of Resource Engine: declarative resources, lifecycle hooks, state machines, actions and ports. No web or database dependencies.
|
|
35
|
+
|
|
36
|
+
Part of [Resource Engine](../../README.md).
|