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,112 @@
1
+ """Identity port: who is calling (authentication). See ``ports.authz`` for what they may do.
2
+
3
+ Entry adapters turn credentials (a bearer token) into a ``Principal`` with an
4
+ ``Authenticator`` and pass it to the engine as ``actor``; hooks and actions read
5
+ it from ``ctx.actor``.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Mapping
11
+ from dataclasses import dataclass, field
12
+ from typing import Any, Protocol
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class Principal:
17
+ """An authenticated caller, normalised across identity providers.
18
+
19
+ Attributes:
20
+ subject: Stable id of the user or service at the provider (``sub``/``oid``).
21
+ issuer: Who vouched for it (token ``iss``).
22
+ provider: Adapter preset name (``keycloak``, ``cognito``, ``entra_id``...).
23
+ name / email: Display data when the token carries it.
24
+ roles: Roles or groups the provider assigned (realm/client roles,
25
+ Cognito groups, Entra app roles, custom claims).
26
+ groups: Group memberships, when the provider separates them from roles.
27
+ scopes: OAuth scopes granted to the token.
28
+ tenant: Tenant / organisation id for multi-tenant providers.
29
+ client_id: The OAuth client the token was issued to.
30
+ service: True for machine identities (client credentials).
31
+ claims: All verified claims, for anything not normalised above.
32
+ """
33
+
34
+ subject: str
35
+ issuer: str
36
+ provider: str = "oidc"
37
+ name: str | None = None
38
+ email: str | None = None
39
+ roles: frozenset[str] = field(default_factory=frozenset)
40
+ groups: frozenset[str] = field(default_factory=frozenset)
41
+ scopes: frozenset[str] = field(default_factory=frozenset)
42
+ tenant: str | None = None
43
+ client_id: str | None = None
44
+ service: bool = False
45
+ claims: Mapping[str, Any] = field(default_factory=dict, repr=False, compare=False)
46
+
47
+ @property
48
+ def id(self) -> str:
49
+ """Label used by the engine (e.g. ``Document.created_by``)."""
50
+ return f"{self.provider}:{self.subject}"
51
+
52
+ def has_role(self, role: str) -> bool:
53
+ """Whether the caller has ``role``."""
54
+ return role in self.roles
55
+
56
+ def has_scope(self, scope: str) -> bool:
57
+ """Whether the caller's token grants ``scope``."""
58
+ return scope in self.scopes
59
+
60
+
61
+ class Authenticator(Protocol):
62
+ """Verifies credentials and returns the caller.
63
+
64
+ Raises ``AuthenticationFailed`` (RE-E701) when the credentials are not valid.
65
+ """
66
+
67
+ async def authenticate(self, token: str) -> Principal:
68
+ """The caller ``token`` belongs to. Raises ``AuthenticationFailed`` when it is not valid."""
69
+ ...
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class Credentials:
74
+ """A token with what the request proves about its sender, for
75
+ sender-constrained tokens (DPoP, RFC 9449; mTLS, RFC 8705).
76
+
77
+ Attributes:
78
+ token: The access token.
79
+ scheme: ``bearer`` or ``dpop`` (the ``Authorization`` scheme, lower case).
80
+ method / url: The request's method and URL without query or fragment,
81
+ as the client sent them (what a DPoP proof's ``htm``/``htu`` name).
82
+ proof: The ``DPoP`` header (a signed proof JWT), if any.
83
+ client_certificate: The TLS client certificate (DER), if any.
84
+ """
85
+
86
+ token: str
87
+ scheme: str = "bearer"
88
+ method: str | None = None
89
+ url: str | None = None
90
+ proof: str | None = None
91
+ client_certificate: bytes | None = field(default=None, repr=False)
92
+
93
+
94
+ class RequestAuthenticator(Authenticator, Protocol):
95
+ """An ``Authenticator`` that also checks the request's proof of possession.
96
+
97
+ Entry adapters call ``authenticate_request`` when it exists, and refuse
98
+ the ``DPoP`` scheme otherwise (see ``resource_engine.identity``).
99
+ """
100
+
101
+ async def authenticate_request(self, credentials: Credentials) -> Principal:
102
+ """The caller, once the token and the request's proof of possession (DPoP, mTLS) are
103
+ verified."""
104
+ ...
105
+
106
+
107
+ __all__ = [
108
+ "Authenticator",
109
+ "Credentials",
110
+ "Principal",
111
+ "RequestAuthenticator",
112
+ ]
@@ -0,0 +1,28 @@
1
+ """Lock port: named leases so a job runs on one worker at a time."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import timedelta
6
+ from typing import Protocol
7
+
8
+
9
+ class LockProvider(Protocol):
10
+ """Named leases with an expiry.
11
+
12
+ A lease is held by ``owner`` until it is released or ``ttl`` passes, so a
13
+ worker that dies frees it after ``ttl``. Acquiring a lease the same owner
14
+ already holds renews it.
15
+ """
16
+
17
+ async def acquire(self, name: str, owner: str, ttl: timedelta) -> bool:
18
+ """Take or renew the lease. ``False`` when another owner holds it."""
19
+ ...
20
+
21
+ async def release(self, name: str, owner: str) -> None:
22
+ """Give the lease up. Does nothing when ``owner`` does not hold it."""
23
+ ...
24
+
25
+
26
+ __all__ = [
27
+ "LockProvider",
28
+ ]
@@ -0,0 +1,197 @@
1
+ """Messaging ports: outbound transport, transactional outbox and inbound handlers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Awaitable, Callable, Sequence
6
+ from dataclasses import dataclass
7
+ from datetime import datetime
8
+ from typing import Any, Protocol, runtime_checkable
9
+
10
+ from resource_engine.messaging.envelope import EventEnvelope
11
+
12
+
13
+ class MessagePublisher(Protocol):
14
+ """Hands envelopes to a broker (SQS, SNS, Service Bus, Pub/Sub...).
15
+
16
+ Must either accept every envelope or raise ``PublishFailed`` listing the ids
17
+ that were not accepted. Delivery is at-least-once: consumers must tolerate
18
+ duplicates (use ``EventEnvelope.id``).
19
+ """
20
+
21
+ async def publish(self, messages: Sequence[EventEnvelope]) -> None:
22
+ """Hand ``messages`` to the broker, or raise ``PublishFailed`` with the ids it did not
23
+ accept."""
24
+ ...
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class OutboxRecord:
29
+ """An event waiting in the outbox, with its delivery attempts."""
30
+
31
+ envelope: EventEnvelope
32
+ attempts: int = 0
33
+ last_error: str | None = None
34
+ created_at: datetime | None = None
35
+ published: bool = False
36
+ published_at: datetime | None = None
37
+
38
+
39
+ class OutboxStore(Protocol):
40
+ """Outbox table reached through the active unit of work."""
41
+
42
+ async def add(self, envelopes: Sequence[EventEnvelope]) -> None:
43
+ """Store ``envelopes`` as unpublished, in the current transaction."""
44
+ ...
45
+
46
+ async def pending(self, limit: int) -> list[OutboxRecord]:
47
+ """Oldest unpublished records. SQL implementations lock them (SKIP LOCKED)."""
48
+ ...
49
+
50
+ async def mark_published(self, ids: Sequence[str]) -> None:
51
+ """Mark these records as sent."""
52
+ ...
53
+
54
+ async def mark_failed(self, ids: Sequence[str], error: str) -> None:
55
+ """Count a failed attempt for these records and keep ``error``."""
56
+ ...
57
+
58
+ async def purge_published(self, before: datetime, limit: int) -> int:
59
+ """Delete up to ``limit`` records published before ``before``; returns how
60
+ many. Unpublished records are never deleted."""
61
+ ...
62
+
63
+
64
+ @runtime_checkable
65
+ class InspectableOutbox(Protocol):
66
+ """An outbox operators can look into and requeue from (the explorer).
67
+ Optional: the relay needs only ``OutboxStore``."""
68
+
69
+ async def unpublished(self, limit: int) -> list[OutboxRecord]:
70
+ """Oldest records not sent yet, without locking them (unlike ``pending``)."""
71
+ ...
72
+
73
+ async def get(self, message_id: str) -> OutboxRecord | None:
74
+ """One record, sent or not (until retention deletes it)."""
75
+ ...
76
+
77
+ async def requeue(self, ids: Sequence[str]) -> int:
78
+ """Send these records again: unpublished, attempts and error reset.
79
+ Returns how many were found."""
80
+ ...
81
+
82
+
83
+ @runtime_checkable
84
+ class SupportsOutbox(Protocol):
85
+ """A unit of work that can write to an outbox in the same transaction."""
86
+
87
+ def outbox(self) -> OutboxStore:
88
+ """The outbox, in this unit of work's transaction."""
89
+ ...
90
+
91
+
92
+ type MessageHandler = Callable[[EventEnvelope], Awaitable[None] | None]
93
+
94
+
95
+ # --- Inbound ---
96
+
97
+
98
+ @dataclass(frozen=True)
99
+ class ReceivedMessage:
100
+ """A message taken from a broker (pull) or an HTTP push request.
101
+
102
+ Attributes:
103
+ envelope: The decoded envelope, or ``None`` when the body could not be decoded.
104
+ handle: Broker token needed to ack/retry it (receipt handle, ack id, lock...).
105
+ delivery_count: 1 on the first delivery; ``None`` if the broker does not say.
106
+ error: Why decoding failed, when ``envelope`` is ``None``.
107
+ message_id: Broker-side message id, for logs.
108
+ """
109
+
110
+ envelope: EventEnvelope | None
111
+ handle: Any = None
112
+ delivery_count: int | None = None
113
+ error: str | None = None
114
+ message_id: str | None = None
115
+
116
+
117
+ class MessageSource(Protocol):
118
+ """Pull side of a broker queue or subscription."""
119
+
120
+ async def receive(self, max_messages: int, wait_seconds: float) -> list[ReceivedMessage]:
121
+ """Up to ``max_messages``, waiting at most ``wait_seconds`` when none are ready."""
122
+ ...
123
+
124
+ async def ack(self, messages: Sequence[ReceivedMessage]) -> None:
125
+ """Remove the messages for good."""
126
+ ...
127
+
128
+ async def retry(self, messages: Sequence[ReceivedMessage], delay_seconds: float) -> None:
129
+ """Make the messages available again, after ``delay_seconds`` if the broker can."""
130
+ ...
131
+
132
+
133
+ @runtime_checkable
134
+ class SupportsDeadLetter(Protocol):
135
+ """A source that can move messages to a dead-letter destination explicitly.
136
+
137
+ Sources without it rely on the broker's own redrive policy (e.g. SQS
138
+ ``maxReceiveCount``, Pub/Sub dead-letter topics).
139
+ """
140
+
141
+ async def dead_letter(self, messages: Sequence[ReceivedMessage], reason: str) -> None:
142
+ """Move ``messages`` to the dead-letter destination, with ``reason``."""
143
+ ...
144
+
145
+
146
+ class InboxStore(Protocol):
147
+ """Ids of messages a consumer has already processed (idempotent consumer)."""
148
+
149
+ async def processed(self, consumer: str, message_ids: Sequence[str]) -> set[str]:
150
+ """Which of ``message_ids`` ``consumer`` has already processed."""
151
+ ...
152
+
153
+ async def mark_processed(self, consumer: str, message_ids: Sequence[str]) -> None:
154
+ """Record that ``consumer`` processed ``message_ids``, in the current transaction."""
155
+ ...
156
+
157
+ async def purge(self, before: datetime, limit: int) -> int:
158
+ """Delete up to ``limit`` marks (any consumer) written before ``before``;
159
+ returns how many."""
160
+ ...
161
+
162
+
163
+ @runtime_checkable
164
+ class SupportsInbox(Protocol):
165
+ """A unit of work that exposes the inbox table."""
166
+
167
+ def inbox(self) -> InboxStore:
168
+ """The inbox, in this unit of work's transaction."""
169
+ ...
170
+
171
+
172
+ class MessageObserver(Protocol):
173
+ """Metrics hook: called after every message a consumer processes, with the
174
+ consumer name, the message, its ``ProcessResult`` and the duration in
175
+ seconds. May be sync or async; failures never change the outcome."""
176
+
177
+ def __call__(
178
+ self, consumer: str, message: ReceivedMessage, result: Any, seconds: float
179
+ ) -> Awaitable[None] | None:
180
+ """Observe one processed message."""
181
+ ...
182
+
183
+
184
+ __all__ = [
185
+ "InboxStore",
186
+ "InspectableOutbox",
187
+ "MessageHandler",
188
+ "MessageObserver",
189
+ "MessagePublisher",
190
+ "MessageSource",
191
+ "OutboxRecord",
192
+ "OutboxStore",
193
+ "ReceivedMessage",
194
+ "SupportsDeadLetter",
195
+ "SupportsInbox",
196
+ "SupportsOutbox",
197
+ ]
@@ -0,0 +1,60 @@
1
+ """Operation metrics port: an observer called after every manager operation.
2
+
3
+ ``ResourceManager(observers=[...])`` calls each observer once per operation
4
+ (``list``, ``get``, ``create``... and the document operations), whether it
5
+ succeeded or failed. The OpenTelemetry implementation is
6
+ ``resource_engine_opentelemetry.OperationMetrics``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Awaitable
12
+ from dataclasses import dataclass
13
+ from typing import Literal, Protocol
14
+
15
+ type OperationOutcome = Literal["ok", "failed"]
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class OperationRun:
20
+ """One finished operation.
21
+
22
+ Attributes:
23
+ resource: The resource's name.
24
+ operation: ``list``, ``get``, ``create``, ``update``, ``delete``,
25
+ ``transition``, ``action``, ``attach``, ``detach``,
26
+ ``request_upload``, ``confirm_upload`` or ``list_documents``.
27
+ outcome: ``ok`` or ``failed``.
28
+ seconds: Wall time, from the call to its return (after commit and
29
+ post-commit work).
30
+ action: ``transition:<event>`` or ``action:<name>`` (else ``None``).
31
+ error_type: The error code (``RE-E702``, a ``DomainError`` code) or the
32
+ exception's class name, when failed.
33
+ correlation_id: The operation's correlation id (``None`` when it failed
34
+ before its context existed, e.g. an unknown resource).
35
+ error: The exception, when failed.
36
+ """
37
+
38
+ resource: str
39
+ operation: str
40
+ outcome: OperationOutcome
41
+ seconds: float
42
+ action: str | None = None
43
+ error_type: str | None = None
44
+ correlation_id: str | None = None
45
+ error: BaseException | None = None
46
+
47
+
48
+ class OperationObserver(Protocol):
49
+ """Port: called after each manager operation with what happened and how long it took."""
50
+
51
+ def __call__(self, run: OperationRun) -> Awaitable[None] | None:
52
+ """Observe one finished operation."""
53
+ ...
54
+
55
+
56
+ __all__ = [
57
+ "OperationObserver",
58
+ "OperationOutcome",
59
+ "OperationRun",
60
+ ]
@@ -0,0 +1,59 @@
1
+ """Rate limit port: decides whether a caller may make one more request.
2
+
3
+ Entry adapters and the manager call it at fixed points; what it counts and
4
+ where is the implementation's business. ``resource_engine.ratelimit`` ships
5
+ ``SlidingWindowLimiter`` (counters in a ``RateLimitStore``: memory or Redis).
6
+ Implement the port to delegate to something else: a gateway's rate-limit
7
+ service (Envoy RLS), a SaaS limiter, quotas billed per customer.
8
+
9
+ Each method returns ``None`` or a ``Decision`` when the request may go on (the
10
+ decision feeds the ``RateLimit-*`` headers) and raises ``RateLimited``
11
+ (RE-E710) when it may not.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from dataclasses import dataclass
17
+ from typing import Any, Protocol
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class Decision:
22
+ """The outcome of one check, with what the RateLimit headers report."""
23
+
24
+ allowed: bool
25
+ limit: int
26
+ remaining: int
27
+ reset: int # seconds until the window frees up
28
+ retry_after: int # seconds to wait when refused (0 when allowed)
29
+ key: str = ""
30
+
31
+
32
+ class RateLimiter(Protocol):
33
+ """Port: decides whether a caller may make one more request."""
34
+
35
+ async def caller(self, actor: Any) -> Decision | None:
36
+ """One request of an authenticated caller (HTTP, each MCP tool call)."""
37
+ ...
38
+
39
+ async def client(self, address: str | None) -> Decision | None:
40
+ """One request without credentials, from ``address``."""
41
+ ...
42
+
43
+ async def before_auth(self, address: str | None) -> None:
44
+ """Before checking credentials from ``address`` (refuse brute force)."""
45
+ ...
46
+
47
+ async def failed(self, address: str | None) -> None:
48
+ """Credentials from ``address`` were wrong."""
49
+ ...
50
+
51
+ async def action(self, actor: Any, action: str) -> None:
52
+ """The manager is about to run ``action`` (``invoices:create``) for ``actor``."""
53
+ ...
54
+
55
+
56
+ __all__ = [
57
+ "Decision",
58
+ "RateLimiter",
59
+ ]
@@ -0,0 +1,56 @@
1
+ """Port: persistence of one resource's entities."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Protocol
6
+
7
+ from resource_engine.application.query import ListQuery, Page
8
+
9
+
10
+ class Repository[E](Protocol):
11
+ """Persistence port for the entities of one resource.
12
+
13
+ Implementations must make ``add``/``update``/``delete`` visible inside the
14
+ current unit of work (e.g. flush), and assign the identifier on ``add``.
15
+
16
+ Optional capabilities, declared as class attributes:
17
+
18
+ - ``supports_conditions``: ``list`` applies ``ListQuery.condition``
19
+ (row-level permissions).
20
+ - ``supports_versions``: ``update`` and ``delete`` accept
21
+ ``expected_version`` and raise ``VersionConflict`` when the stored version
22
+ differs at write time (atomically: compare and set). Needed by resources
23
+ with a ``version_field``.
24
+ - ``filterable`` / ``sortable``: the fields ``list`` can filter and sort
25
+ by (``None``: any), and ``max_offset``: the deepest offset it pages to.
26
+ The engine refuses other queries with ``QueryNotSupported`` (RE-E103).
27
+
28
+ Units of work declare ``transaction_scope`` (``"unit_of_work"``,
29
+ ``"partition"`` or ``"none"``) and ``max_writes``. See
30
+ ``resource_engine.capabilities``.
31
+ """
32
+
33
+ async def get(self, entity_id: Any) -> E | None:
34
+ """The entity with ``entity_id``, or ``None``."""
35
+ ...
36
+
37
+ async def list(self, query: ListQuery) -> Page[E]:
38
+ """One page of the entities matching ``query``, with the total."""
39
+ ...
40
+
41
+ async def add(self, entity: E) -> E:
42
+ """Store a new entity and return it with its assigned id."""
43
+ ...
44
+
45
+ async def update(self, entity: E) -> E:
46
+ """Store the changes of an existing entity and return it."""
47
+ ...
48
+
49
+ async def delete(self, entity: E) -> None:
50
+ """Remove the entity."""
51
+ ...
52
+
53
+
54
+ __all__ = [
55
+ "Repository",
56
+ ]
@@ -0,0 +1,93 @@
1
+ """Blob storage port: binary content of documents (S3, Garage, MinIO, Azure Blob, GCS...)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import AsyncIterable, AsyncIterator, Sequence
6
+ from dataclasses import dataclass, field
7
+ from datetime import datetime, timedelta
8
+ from typing import Protocol, runtime_checkable
9
+
10
+ type Content = bytes | AsyncIterable[bytes]
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class BlobInfo:
15
+ """What a blob store knows about a stored object."""
16
+
17
+ key: str
18
+ size: int
19
+ content_type: str | None = None
20
+ etag: str | None = None
21
+ last_modified: datetime | None = None
22
+ sha256: str | None = None
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class PresignedRequest:
27
+ """An HTTP request a client can make directly against the store."""
28
+
29
+ url: str
30
+ method: str
31
+ expires_at: datetime
32
+ headers: dict[str, str] = field(default_factory=dict)
33
+
34
+
35
+ class BlobStore(Protocol):
36
+ """Stores opaque binary content under string keys.
37
+
38
+ Keys are relative; adapters may add their own prefix. ``put`` must not leave a
39
+ partial object behind when it fails or when ``max_bytes`` is exceeded.
40
+ """
41
+
42
+ async def put(
43
+ self, key: str, content: Content, *, content_type: str, max_bytes: int | None = None
44
+ ) -> BlobInfo:
45
+ """Store ``content`` (streamed), returning size and sha256.
46
+
47
+ Raises ``DocumentTooLarge`` (RE-E603) past ``max_bytes`` and
48
+ ``StorageFailed`` (RE-E607) on store errors.
49
+ """
50
+ ...
51
+
52
+ def open(self, key: str) -> AsyncIterator[bytes]:
53
+ """Stream the content. Raises ``BlobNotFound`` (RE-E608)."""
54
+ ...
55
+
56
+ async def head(self, key: str) -> BlobInfo | None:
57
+ """Size, type and sha256 of ``key``, or ``None`` when it is missing."""
58
+ ...
59
+
60
+ async def delete(self, keys: Sequence[str]) -> None:
61
+ """Delete keys; missing keys are ignored."""
62
+ ...
63
+
64
+ def list(self, prefix: str = "") -> AsyncIterator[BlobInfo]:
65
+ """The blobs whose keys start with ``prefix``."""
66
+ ...
67
+
68
+
69
+ @runtime_checkable
70
+ class SupportsPresignedUrls(Protocol):
71
+ """A store that can hand out time-limited URLs for direct upload and download."""
72
+
73
+ async def presign_put(
74
+ self, key: str, *, content_type: str, expires: timedelta
75
+ ) -> PresignedRequest:
76
+ """A request that uploads ``key`` directly, valid for ``expires``."""
77
+ ...
78
+
79
+ async def presign_get(
80
+ self, key: str, *, expires: timedelta, download_name: str | None = None
81
+ ) -> PresignedRequest:
82
+ """A URL that downloads ``key`` directly, valid for ``expires``, saved as ``download_name``
83
+ when given."""
84
+ ...
85
+
86
+
87
+ __all__ = [
88
+ "BlobInfo",
89
+ "BlobStore",
90
+ "Content",
91
+ "PresignedRequest",
92
+ "SupportsPresignedUrls",
93
+ ]
@@ -0,0 +1,54 @@
1
+ """Template port: render named templates per locale (emails, documents).
2
+
3
+ ``resource_engine.templates`` ships ``StringTemplates`` for tests and small
4
+ apps; ``resource-engine-jinja`` the Jinja2 renderer (autoescaping, sandbox).
5
+ Names are paths with an extension (``email/invoice_approved.html``); the
6
+ extension says how values are escaped.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Mapping
12
+ from typing import Any, Protocol
13
+
14
+
15
+ class TemplateRenderer(Protocol):
16
+ """Port: renders named templates per locale (emails, documents)."""
17
+
18
+ def render(self, name: str, context: Mapping[str, Any], *, locale: str | None = None) -> str:
19
+ """The template for the most specific locale that has it (``ca-ES``,
20
+ then ``ca``, then the default). Raises ``TemplateNotFound`` (RE-E120)
21
+ when none does, ``TemplateFailed`` (RE-E121) when rendering fails."""
22
+ ...
23
+
24
+ def exists(self, name: str, *, locale: str | None = None) -> bool:
25
+ """Whether ``render`` would find a template."""
26
+ ...
27
+
28
+ def names(self) -> list[str]:
29
+ """Every template name, without the locale (for ``check``)."""
30
+ ...
31
+
32
+
33
+ class PreviewableTemplates(TemplateRenderer, Protocol):
34
+ """A renderer the documentation can show templates from (both renderers
35
+ shipped implement it)."""
36
+
37
+ def variants(self, name: str) -> list[str | None]:
38
+ """The locales that have ``name`` itself (``None``: the unlocalised one)."""
39
+ ...
40
+
41
+ def preview(self, name: str, *, locale: str | None = None) -> str:
42
+ """The template rendered with every variable shown as a placeholder
43
+ (``{{ customer }}``), for the generated docs: no data is invented.
44
+
45
+ ``locale`` falls back like ``render`` (``ca-ES``, ``ca``, the default
46
+ locale); ``None`` is the unlocalised template only. Raises
47
+ ``TemplateNotFound`` when there is none."""
48
+ ...
49
+
50
+
51
+ __all__ = [
52
+ "PreviewableTemplates",
53
+ "TemplateRenderer",
54
+ ]