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,171 @@
|
|
|
1
|
+
"""Activity log port: what the worker did, for the explorer and operators.
|
|
2
|
+
|
|
3
|
+
The worker and the API are separate processes, so what one does and the
|
|
4
|
+
other shows goes through a store both reach:
|
|
5
|
+
|
|
6
|
+
- which consumers handled each event and how (``record_delivery``, fed by
|
|
7
|
+
``ActivityMessageObserver``);
|
|
8
|
+
- the worker's jobs and their schedules (``register_jobs``), their runs
|
|
9
|
+
(``record_job_run``, fed by ``JobRunner(activity=...)``), and "run now"
|
|
10
|
+
requests the API records and the worker claims (``request_run``).
|
|
11
|
+
|
|
12
|
+
Adapters: ``InMemoryActivityLog`` (tests, one process) and
|
|
13
|
+
``SqlAlchemyActivityLog``. ``MessagingJanitor(activity_retention=)`` purges it.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import uuid
|
|
19
|
+
from collections.abc import Collection, Sequence
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
from datetime import UTC, datetime
|
|
22
|
+
from typing import Literal, Protocol
|
|
23
|
+
|
|
24
|
+
type RequestStatus = Literal["pending", "running", "ok", "failed", "skipped"]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _now() -> datetime:
|
|
28
|
+
return datetime.now(UTC)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _id() -> str:
|
|
32
|
+
return uuid.uuid4().hex
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class DeliveryRecord:
|
|
37
|
+
"""One consumer's handling of one message.
|
|
38
|
+
|
|
39
|
+
Attributes:
|
|
40
|
+
outcome: ``ack``, ``duplicate``, ``retry``, ``dead_letter``... (the
|
|
41
|
+
``MessageProcessor`` outcome).
|
|
42
|
+
error: Code and message of the failure, if any.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
consumer: str
|
|
46
|
+
message_id: str
|
|
47
|
+
event_type: str
|
|
48
|
+
outcome: str
|
|
49
|
+
seconds: float
|
|
50
|
+
error: str | None = None
|
|
51
|
+
at: datetime = field(default_factory=_now)
|
|
52
|
+
id: str = field(default_factory=_id)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class JobInfo:
|
|
57
|
+
"""A job as a worker runs it (``JobRunner.describe``)."""
|
|
58
|
+
|
|
59
|
+
name: str
|
|
60
|
+
every: float
|
|
61
|
+
single: bool = False
|
|
62
|
+
ttl: float = 600.0
|
|
63
|
+
run_at_start: bool = True
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True)
|
|
67
|
+
class WorkerJobs:
|
|
68
|
+
"""The jobs one worker runs, as it last said (``seen_at``)."""
|
|
69
|
+
|
|
70
|
+
owner: str
|
|
71
|
+
jobs: tuple[JobInfo, ...]
|
|
72
|
+
seen_at: datetime = field(default_factory=_now)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass(frozen=True)
|
|
76
|
+
class JobRunRecord:
|
|
77
|
+
"""One run of a job: ``ok``, ``failed`` or ``skipped`` (another worker
|
|
78
|
+
held the lease of a ``single`` job)."""
|
|
79
|
+
|
|
80
|
+
job: str
|
|
81
|
+
outcome: str
|
|
82
|
+
seconds: float
|
|
83
|
+
owner: str
|
|
84
|
+
error: str | None = None
|
|
85
|
+
at: datetime = field(default_factory=_now)
|
|
86
|
+
id: str = field(default_factory=_id)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@dataclass(frozen=True)
|
|
90
|
+
class RunRequest:
|
|
91
|
+
"""Someone asked for a job to run now. The worker claims it (``running``)
|
|
92
|
+
and runs it through its runner, so leases hold; then ``ok``, ``failed``,
|
|
93
|
+
or ``skipped`` when another worker held the lease."""
|
|
94
|
+
|
|
95
|
+
id: str
|
|
96
|
+
job: str
|
|
97
|
+
requested_by: str | None
|
|
98
|
+
status: RequestStatus = "pending"
|
|
99
|
+
requested_at: datetime = field(default_factory=_now)
|
|
100
|
+
claimed_by: str | None = None
|
|
101
|
+
finished_at: datetime | None = None
|
|
102
|
+
error: str | None = None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class ActivityLog(Protocol):
|
|
106
|
+
"""Port: where the worker's job runs, run requests and consumer deliveries are recorded."""
|
|
107
|
+
|
|
108
|
+
async def register_jobs(self, owner: str, jobs: Sequence[JobInfo]) -> None:
|
|
109
|
+
"""Replace what ``owner`` runs (called at start, then as a heartbeat)."""
|
|
110
|
+
...
|
|
111
|
+
|
|
112
|
+
async def workers(self) -> list[WorkerJobs]:
|
|
113
|
+
"""Every worker that registered, most recently seen first."""
|
|
114
|
+
...
|
|
115
|
+
|
|
116
|
+
async def record_job_run(self, run: JobRunRecord) -> None:
|
|
117
|
+
"""Store one run of a job."""
|
|
118
|
+
...
|
|
119
|
+
|
|
120
|
+
async def job_runs(self, job: str | None = None, limit: int = 50) -> list[JobRunRecord]:
|
|
121
|
+
"""Runs (of ``job``), newest first."""
|
|
122
|
+
...
|
|
123
|
+
|
|
124
|
+
async def request_run(self, job: str, requested_by: str | None) -> RunRequest:
|
|
125
|
+
"""Ask for ``job`` to run now; the request stays ``pending`` until a worker claims it."""
|
|
126
|
+
...
|
|
127
|
+
|
|
128
|
+
async def run_request(self, request_id: str) -> RunRequest | None:
|
|
129
|
+
"""One request by id, with its current status (``None``: unknown id)."""
|
|
130
|
+
...
|
|
131
|
+
|
|
132
|
+
async def claim_requests(
|
|
133
|
+
self, owner: str, jobs: Collection[str], limit: int = 10
|
|
134
|
+
) -> list[RunRequest]:
|
|
135
|
+
"""Mark up to ``limit`` pending requests for ``jobs`` as ``running`` by
|
|
136
|
+
``owner`` and return them; a request is claimed by one worker only."""
|
|
137
|
+
...
|
|
138
|
+
|
|
139
|
+
async def finish_request(
|
|
140
|
+
self, request_id: str, status: RequestStatus, error: str | None = None
|
|
141
|
+
) -> None:
|
|
142
|
+
"""Close a claimed request with ``ok``, ``failed`` or ``skipped``."""
|
|
143
|
+
...
|
|
144
|
+
|
|
145
|
+
async def record_delivery(self, record: DeliveryRecord) -> None:
|
|
146
|
+
"""Store how one consumer handled one message."""
|
|
147
|
+
...
|
|
148
|
+
|
|
149
|
+
async def deliveries(self, message_id: str) -> list[DeliveryRecord]:
|
|
150
|
+
"""Every consumer's handling of ``message_id``, oldest first."""
|
|
151
|
+
...
|
|
152
|
+
|
|
153
|
+
async def dead_letters(self, limit: int = 50) -> list[DeliveryRecord]:
|
|
154
|
+
"""Messages consumers gave up on (``dead_letter``), newest first."""
|
|
155
|
+
...
|
|
156
|
+
|
|
157
|
+
async def purge(self, before: datetime, limit: int) -> int:
|
|
158
|
+
"""Delete up to ``limit`` records (deliveries, runs, finished requests,
|
|
159
|
+
workers not seen since) older than ``before``; returns how many."""
|
|
160
|
+
...
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
__all__ = [
|
|
164
|
+
"ActivityLog",
|
|
165
|
+
"DeliveryRecord",
|
|
166
|
+
"JobInfo",
|
|
167
|
+
"JobRunRecord",
|
|
168
|
+
"RequestStatus",
|
|
169
|
+
"RunRequest",
|
|
170
|
+
"WorkerJobs",
|
|
171
|
+
]
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Audit port: where audit entries go."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from typing import TYPE_CHECKING, Protocol
|
|
7
|
+
|
|
8
|
+
if TYPE_CHECKING:
|
|
9
|
+
from resource_engine.audit.model import AuditEntry
|
|
10
|
+
from resource_engine.ports.unit_of_work import UnitOfWork
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class AuditSink(Protocol):
|
|
14
|
+
"""Port: where audit entries are stored."""
|
|
15
|
+
|
|
16
|
+
async def record(self, entries: Sequence[AuditEntry], *, uow: UnitOfWork | None = None) -> None:
|
|
17
|
+
"""Store ``entries``.
|
|
18
|
+
|
|
19
|
+
With ``uow`` (committed changes) the entries belong to that transaction:
|
|
20
|
+
they are committed or rolled back with the change. Without it (refused
|
|
21
|
+
attempts, audited reads) the sink writes on its own.
|
|
22
|
+
"""
|
|
23
|
+
...
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class AuditExporter(Protocol):
|
|
27
|
+
"""Ships committed audit entries to another system (``AuditForwarder``).
|
|
28
|
+
|
|
29
|
+
Raise ``RemoteCallFailed`` (RE-E501) to have the entries retried later,
|
|
30
|
+
``MessageRejected`` (RE-E406) for entries the other system will never take.
|
|
31
|
+
Entries may arrive more than once: dedupe by ``entry.id``.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
async def export(self, entries: Sequence[AuditEntry]) -> None:
|
|
35
|
+
"""Send ``entries`` to the other system; raise to have them retried."""
|
|
36
|
+
...
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
__all__ = [
|
|
40
|
+
"AuditExporter",
|
|
41
|
+
"AuditSink",
|
|
42
|
+
]
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Authorization port: may this principal perform this action (on this record)?"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any, Protocol
|
|
7
|
+
|
|
8
|
+
from resource_engine.ports.identity import Principal
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class Decision:
|
|
13
|
+
"""Outcome of an authorization check.
|
|
14
|
+
|
|
15
|
+
``allowed`` is ``None`` when it cannot be decided yet (the record is not
|
|
16
|
+
loaded and some policy depends on it).
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
allowed: bool | None
|
|
20
|
+
reason: str
|
|
21
|
+
policies: tuple[str, ...] = field(default_factory=tuple)
|
|
22
|
+
system_role: str | None = None
|
|
23
|
+
|
|
24
|
+
def to_dict(self) -> dict[str, Any]:
|
|
25
|
+
"""The decision as JSON-ready data."""
|
|
26
|
+
return {
|
|
27
|
+
"allowed": self.allowed,
|
|
28
|
+
"reason": self.reason,
|
|
29
|
+
"policies": list(self.policies),
|
|
30
|
+
"system_role": self.system_role,
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True)
|
|
35
|
+
class FieldAccess:
|
|
36
|
+
"""Field-level outcome for one record: ``denied`` fields are hidden (read) or
|
|
37
|
+
protected (write); ``conditional`` ones depend on data not known yet (the
|
|
38
|
+
record or the input). Callers treat conditional as denied once both are known.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
denied: frozenset[str] = frozenset()
|
|
42
|
+
conditional: frozenset[str] = frozenset()
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def blocked(self) -> frozenset[str]:
|
|
46
|
+
"""Fields the caller may not write: denied and conditional ones."""
|
|
47
|
+
return self.denied | self.conditional
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class FieldRules(Protocol):
|
|
51
|
+
"""Field decisions for one principal, resource and mode, prepared once and
|
|
52
|
+
evaluated per record (cheap, synchronous)."""
|
|
53
|
+
|
|
54
|
+
def decide(self, *, resource: Any = ..., input: Any = ...) -> FieldAccess:
|
|
55
|
+
"""The field decisions for one record (``resource``) or one write (``input``)."""
|
|
56
|
+
...
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class Authorizer(Protocol):
|
|
60
|
+
"""Port: decides whether a principal may do an action, and the row filter for lists."""
|
|
61
|
+
|
|
62
|
+
async def check(
|
|
63
|
+
self,
|
|
64
|
+
principal: Principal | None,
|
|
65
|
+
action: str,
|
|
66
|
+
*,
|
|
67
|
+
resource: Any = ...,
|
|
68
|
+
input: Any = ...,
|
|
69
|
+
context: dict[str, Any] | None = None,
|
|
70
|
+
) -> Decision:
|
|
71
|
+
"""``resource``/``input`` left as ``...`` are unknown (partial check)."""
|
|
72
|
+
...
|
|
73
|
+
|
|
74
|
+
async def scope(self, principal: Principal | None, action: str) -> Any:
|
|
75
|
+
"""Row filter for ``action`` (a ``list``): ``True`` (all rows), ``False``
|
|
76
|
+
(none) or a condition over ``resource.*``."""
|
|
77
|
+
...
|
|
78
|
+
|
|
79
|
+
# Optional: authorizers without field rules leave every field open.
|
|
80
|
+
# async def field_rules(self, principal, resource: str, mode: str) -> FieldRules
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass(frozen=True)
|
|
84
|
+
class AuthzRequest:
|
|
85
|
+
"""One question to an external policy engine.
|
|
86
|
+
|
|
87
|
+
``resource`` and ``input`` are plain dicts (Python values: ``Decimal``,
|
|
88
|
+
``date``... kept; adapters encode them for their engine), or ``...`` when
|
|
89
|
+
not known yet. ``resource_type`` is the resource name (``"invoices"``);
|
|
90
|
+
``id_field`` names its identifier.
|
|
91
|
+
|
|
92
|
+
``filter`` is true when a residual will be applied to records (a ``list``
|
|
93
|
+
row filter, field rules); otherwise a residual only has to say "depends on
|
|
94
|
+
the record" (step 2), so engines may answer without enumerating records.
|
|
95
|
+
"""
|
|
96
|
+
|
|
97
|
+
subject: dict[str, Any] | None
|
|
98
|
+
action: str
|
|
99
|
+
resource_type: str | None
|
|
100
|
+
resource: Any = ...
|
|
101
|
+
input: Any = ...
|
|
102
|
+
context: dict[str, Any] = field(default_factory=dict)
|
|
103
|
+
entity_id: Any = None
|
|
104
|
+
id_field: str = "id"
|
|
105
|
+
filter: bool = False
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def unknowns(self) -> tuple[str, ...]:
|
|
109
|
+
"""Namespaces not known yet (``resource``, ``input``)."""
|
|
110
|
+
return tuple(n for n in ("resource", "input") if getattr(self, n) is ...)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class PolicyEngine(Protocol):
|
|
114
|
+
"""An external policy engine (OPA, Cedar, OpenFGA...) behind
|
|
115
|
+
``EngineAuthorizer``."""
|
|
116
|
+
|
|
117
|
+
async def evaluate(self, request: AuthzRequest) -> Any:
|
|
118
|
+
"""``True``/``False`` when decided; otherwise a residual condition (the
|
|
119
|
+
engine-neutral condition language of ``resource_engine.authz.conditions``)
|
|
120
|
+
over the unknown namespaces. Raise ``ConditionNotSupported`` when the
|
|
121
|
+
engine's residual cannot be expressed."""
|
|
122
|
+
...
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
__all__ = [
|
|
126
|
+
"Authorizer",
|
|
127
|
+
"AuthzRequest",
|
|
128
|
+
"Decision",
|
|
129
|
+
"FieldAccess",
|
|
130
|
+
"FieldRules",
|
|
131
|
+
"PolicyEngine",
|
|
132
|
+
]
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Cache port: values by key with a time to live. ``resource_engine.cache``
|
|
2
|
+
ships ``InMemoryCache``; ``resource-engine-redis`` a shared ``RedisCache``.
|
|
3
|
+
|
|
4
|
+
Values are plain data (dicts, lists, strings, numbers, dates, decimals);
|
|
5
|
+
implementations serialise them as they need.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Any, Protocol
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Cache(Protocol):
|
|
14
|
+
"""Port: a key-value cache with expiry."""
|
|
15
|
+
|
|
16
|
+
async def get(self, key: str) -> Any | None:
|
|
17
|
+
"""The value, or ``None`` when missing or expired."""
|
|
18
|
+
...
|
|
19
|
+
|
|
20
|
+
async def set(self, key: str, value: Any, ttl: float) -> None:
|
|
21
|
+
"""Store ``value`` for ``ttl`` seconds."""
|
|
22
|
+
...
|
|
23
|
+
|
|
24
|
+
async def delete(self, *keys: str) -> None:
|
|
25
|
+
"""Forget ``keys`` (missing ones are ignored)."""
|
|
26
|
+
...
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class AtomicCache(Cache, Protocol):
|
|
30
|
+
"""A cache that can store a key only when it is absent, atomically
|
|
31
|
+
(``InMemoryCache``, ``RedisCache``). Used to refuse replays (DPoP ``jti``)."""
|
|
32
|
+
|
|
33
|
+
async def add(self, key: str, value: Any, ttl: float) -> bool:
|
|
34
|
+
"""Store ``value`` unless ``key`` is present; ``True`` when stored."""
|
|
35
|
+
...
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
__all__ = [
|
|
39
|
+
"AtomicCache",
|
|
40
|
+
"Cache",
|
|
41
|
+
]
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Email port: hand a composed message to a mail service (SMTP, SES...).
|
|
2
|
+
|
|
3
|
+
``resource_engine.email`` composes messages from templates (``Mailer``) and
|
|
4
|
+
sends the ones requested inside a transaction after it commits
|
|
5
|
+
(``EmailRequested``). Adapters only deliver.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Mapping, Sequence
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from typing import Protocol
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class Attachment:
|
|
17
|
+
"""A file attached to an email."""
|
|
18
|
+
|
|
19
|
+
filename: str
|
|
20
|
+
content_type: str
|
|
21
|
+
content: bytes = field(repr=False)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class EmailMessage:
|
|
26
|
+
"""A message ready to send.
|
|
27
|
+
|
|
28
|
+
Attributes:
|
|
29
|
+
sender: The ``From`` address (``"Factures <factures@example.com>"``).
|
|
30
|
+
to / cc / bcc: Recipients; at least one in ``to``.
|
|
31
|
+
subject: One line.
|
|
32
|
+
text / html: The bodies; at least one. With both, clients pick.
|
|
33
|
+
reply_to: ``Reply-To`` addresses.
|
|
34
|
+
message_id: ``Message-ID`` (``<id@domain>``): stable across retries,
|
|
35
|
+
so a message sent twice is recognisably the same one.
|
|
36
|
+
headers: Extra headers (``List-Unsubscribe``...).
|
|
37
|
+
attachments: Files attached to the message.
|
|
38
|
+
tags: Provider metadata (SES tags...), never shown to recipients.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
sender: str
|
|
42
|
+
to: Sequence[str]
|
|
43
|
+
subject: str
|
|
44
|
+
text: str | None = None
|
|
45
|
+
html: str | None = None
|
|
46
|
+
cc: Sequence[str] = ()
|
|
47
|
+
bcc: Sequence[str] = ()
|
|
48
|
+
reply_to: Sequence[str] = ()
|
|
49
|
+
message_id: str | None = None
|
|
50
|
+
headers: Mapping[str, str] = field(default_factory=dict)
|
|
51
|
+
attachments: Sequence[Attachment] = ()
|
|
52
|
+
tags: Mapping[str, str] = field(default_factory=dict)
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def recipients(self) -> list[str]:
|
|
56
|
+
"""Every address the message goes to: ``to``, ``cc`` and ``bcc``."""
|
|
57
|
+
return [*self.to, *self.cc, *self.bcc]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class EmailSender(Protocol):
|
|
61
|
+
"""Delivers a message; returns the provider's id when it gives one.
|
|
62
|
+
|
|
63
|
+
Raises ``RemoteCallFailed`` (RE-E501) when the service can't be reached
|
|
64
|
+
or refuses the message for a reason worth retrying, and
|
|
65
|
+
``EmailRejected`` (RE-E502) for a permanent refusal (an invalid address).
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
async def send(self, message: EmailMessage) -> str | None:
|
|
69
|
+
"""Deliver ``message``; returns the provider's message id when it gives one."""
|
|
70
|
+
...
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(frozen=True)
|
|
74
|
+
class EmailEvent:
|
|
75
|
+
"""What a mail service reports after sending: a bounce, a complaint (the
|
|
76
|
+
recipient marked it as spam), a delivery, an unsubscribe.
|
|
77
|
+
|
|
78
|
+
Attributes:
|
|
79
|
+
kind: ``bounce``, ``complaint``, ``delivery`` or ``unsubscribe``.
|
|
80
|
+
address: The recipient it is about.
|
|
81
|
+
permanent: For bounces: the address will never accept mail (hard
|
|
82
|
+
bounce), not a full mailbox or a greylist (soft bounce).
|
|
83
|
+
reason: The provider's description.
|
|
84
|
+
provider: ``postmark``, ``sendgrid``, ``ses``...
|
|
85
|
+
message_id: The provider's id of the message, when it gives one.
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
kind: str
|
|
89
|
+
address: str
|
|
90
|
+
permanent: bool = False
|
|
91
|
+
reason: str = ""
|
|
92
|
+
provider: str = ""
|
|
93
|
+
message_id: str | None = None
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class SuppressionList(Protocol):
|
|
97
|
+
"""Addresses not to send to (hard bounces, complaints, unsubscribes)."""
|
|
98
|
+
|
|
99
|
+
async def suppressed(self, addresses: Sequence[str]) -> set[str]:
|
|
100
|
+
"""Which of ``addresses`` are suppressed (compared in lower case)."""
|
|
101
|
+
...
|
|
102
|
+
|
|
103
|
+
async def suppress(self, address: str, reason: str) -> None:
|
|
104
|
+
"""Stop sending to ``address``, recording why."""
|
|
105
|
+
...
|
|
106
|
+
|
|
107
|
+
async def release(self, address: str) -> None:
|
|
108
|
+
"""Send to it again (the user fixed their mailbox, asked to resubscribe)."""
|
|
109
|
+
...
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
__all__ = [
|
|
113
|
+
"Attachment",
|
|
114
|
+
"EmailEvent",
|
|
115
|
+
"EmailMessage",
|
|
116
|
+
"EmailSender",
|
|
117
|
+
"SuppressionList",
|
|
118
|
+
]
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Port: publishes domain events after commit."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from typing import Protocol, override
|
|
7
|
+
|
|
8
|
+
from resource_engine.domain.events import DomainEvent
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class EventPublisher(Protocol):
|
|
12
|
+
"""Publishes events after the transaction that produced them has committed.
|
|
13
|
+
|
|
14
|
+
For guaranteed delivery implement this on top of an Outbox table written
|
|
15
|
+
inside the transaction (planned; see docs/lifecycle.md).
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
async def publish(self, events: Sequence[DomainEvent]) -> None:
|
|
19
|
+
"""Publish ``events``, which their transaction has already committed."""
|
|
20
|
+
...
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class NullEventPublisher(EventPublisher):
|
|
24
|
+
"""A publisher that drops every event, for applications that publish none."""
|
|
25
|
+
|
|
26
|
+
@override
|
|
27
|
+
async def publish(self, events: Sequence[DomainEvent]) -> None:
|
|
28
|
+
return None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"EventPublisher",
|
|
33
|
+
"NullEventPublisher",
|
|
34
|
+
]
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Idempotency port: results of writes, by caller and key, so a retried
|
|
2
|
+
request returns the first result instead of running again."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from datetime import datetime
|
|
9
|
+
from typing import Any, Protocol, runtime_checkable
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class IdempotencyRecord:
|
|
14
|
+
"""One completed write.
|
|
15
|
+
|
|
16
|
+
Attributes:
|
|
17
|
+
scope: Who sent it (``Principal.id``, ``system:<job>`` or ``anonymous``).
|
|
18
|
+
key: The client's idempotency key.
|
|
19
|
+
fingerprint: SHA-256 of the request (operation, resource, record, input).
|
|
20
|
+
resource, operation: What ran.
|
|
21
|
+
result: The result as JSON, to rebuild it on a replay.
|
|
22
|
+
created_at, expires_at: When it ran and until when it is replayed.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
scope: str
|
|
26
|
+
key: str
|
|
27
|
+
fingerprint: str
|
|
28
|
+
resource: str
|
|
29
|
+
operation: str
|
|
30
|
+
result: Mapping[str, Any] = field(default_factory=dict)
|
|
31
|
+
created_at: datetime | None = None
|
|
32
|
+
expires_at: datetime | None = None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class IdempotencyStore(Protocol):
|
|
36
|
+
"""Records reached through the operation's unit of work.
|
|
37
|
+
|
|
38
|
+
``put`` happens in the operation's transaction: it commits with the change,
|
|
39
|
+
or not at all. Two transactions putting the same ``(scope, key)`` must not
|
|
40
|
+
both commit (a primary key in SQL).
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
async def get(self, scope: str, key: str) -> IdempotencyRecord | None:
|
|
44
|
+
"""The record for ``(scope, key)``, or ``None``."""
|
|
45
|
+
...
|
|
46
|
+
|
|
47
|
+
async def put(self, record: IdempotencyRecord) -> None:
|
|
48
|
+
"""Store ``record``, replacing an expired one with the same key."""
|
|
49
|
+
...
|
|
50
|
+
|
|
51
|
+
async def purge(self, before: datetime, limit: int) -> int:
|
|
52
|
+
"""Delete up to ``limit`` records that expired before ``before``."""
|
|
53
|
+
...
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@runtime_checkable
|
|
57
|
+
class SupportsIdempotency(Protocol):
|
|
58
|
+
"""A unit of work that stores idempotency records."""
|
|
59
|
+
|
|
60
|
+
def idempotency(self) -> IdempotencyStore:
|
|
61
|
+
"""The idempotency store, in this unit of work's transaction."""
|
|
62
|
+
...
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
__all__ = [
|
|
66
|
+
"IdempotencyRecord",
|
|
67
|
+
"IdempotencyStore",
|
|
68
|
+
"SupportsIdempotency",
|
|
69
|
+
]
|