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,230 @@
|
|
|
1
|
+
"""Error reporting: every unexpected failure reaches one ``ErrorReporter``.
|
|
2
|
+
|
|
3
|
+
```python
|
|
4
|
+
from resource_engine.reporting import set_reporter
|
|
5
|
+
from resource_engine_sentry import SentryReporter
|
|
6
|
+
|
|
7
|
+
set_reporter(SentryReporter(dsn="https://key@glitchtip.example.com/1"))
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
The engine reports, once per failure:
|
|
11
|
+
|
|
12
|
+
- **operations** that fail with something other than a client or business
|
|
13
|
+
error (``where="operation"``);
|
|
14
|
+
- **5xx responses** of the HTTP, GraphQL and MCP adapters (``http``,
|
|
15
|
+
``graphql``, ``mcp``);
|
|
16
|
+
- **messages** a consumer dead-letters or fails on (``consumer``), and
|
|
17
|
+
**outbox** batches that cannot be published (``outbox``);
|
|
18
|
+
- **jobs**, **timers** and **processes** that fail (``job``, ``timer``,
|
|
19
|
+
``process``), and work after commit (``after_commit``).
|
|
20
|
+
|
|
21
|
+
Expected errors (validation, not found, permission, conflicts, business rules)
|
|
22
|
+
are not reported: they are answers, not failures. Each report carries the log
|
|
23
|
+
context (correlation id, resource, operation, record, consumer, job...) and
|
|
24
|
+
the error's engine code. The default reporter logs at ``ERROR`` on
|
|
25
|
+
``resource_engine.errors``. See docs/observability.md#error-reporting.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import contextlib
|
|
31
|
+
import inspect
|
|
32
|
+
import logging
|
|
33
|
+
from collections.abc import Mapping
|
|
34
|
+
from dataclasses import dataclass, field
|
|
35
|
+
from typing import Any, Literal, Protocol, override
|
|
36
|
+
|
|
37
|
+
from resource_engine.logs import error_type, log_context
|
|
38
|
+
|
|
39
|
+
logger = logging.getLogger("resource_engine.errors")
|
|
40
|
+
|
|
41
|
+
type Level = Literal["error", "warning"]
|
|
42
|
+
|
|
43
|
+
_MARK = "_resource_engine_reported"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class ErrorReport:
|
|
48
|
+
"""One failure.
|
|
49
|
+
|
|
50
|
+
Attributes:
|
|
51
|
+
error: The exception.
|
|
52
|
+
where: The part of the engine it happened in (``operation``, ``http``...).
|
|
53
|
+
level: ``error``, or ``warning`` for expected errors that still matter
|
|
54
|
+
(a message dead-lettered because its payload is invalid).
|
|
55
|
+
code: The engine's code (``RE-E501``), a ``DomainError`` code, or the
|
|
56
|
+
exception's class name.
|
|
57
|
+
context: The log context and the call site's details (``route``,
|
|
58
|
+
``status``, ``service``...).
|
|
59
|
+
actor: The caller's id (``keycloak:ada``), when known.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
error: BaseException
|
|
63
|
+
where: str
|
|
64
|
+
level: Level = "error"
|
|
65
|
+
code: str | None = None
|
|
66
|
+
context: Mapping[str, Any] = field(default_factory=dict)
|
|
67
|
+
actor: str | None = None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class ErrorReporter(Protocol):
|
|
71
|
+
"""Receives every reported failure (sync or async)."""
|
|
72
|
+
|
|
73
|
+
def report(self, report: ErrorReport) -> Any:
|
|
74
|
+
"""Handle one reported failure; may return an awaitable."""
|
|
75
|
+
...
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class LoggingReporter(ErrorReporter):
|
|
79
|
+
"""Logs reports on ``resource_engine.errors`` with the traceback."""
|
|
80
|
+
|
|
81
|
+
def __init__(self, log: logging.Logger | None = None) -> None:
|
|
82
|
+
self.logger = log or logger
|
|
83
|
+
|
|
84
|
+
@override
|
|
85
|
+
def report(self, report: ErrorReport) -> None:
|
|
86
|
+
level = logging.ERROR if report.level == "error" else logging.WARNING
|
|
87
|
+
self.logger.log(
|
|
88
|
+
level,
|
|
89
|
+
"%s: %s: %s",
|
|
90
|
+
describe(report),
|
|
91
|
+
report.code,
|
|
92
|
+
report.error,
|
|
93
|
+
exc_info=(type(report.error), report.error, report.error.__traceback__),
|
|
94
|
+
extra={
|
|
95
|
+
"error_where": report.where,
|
|
96
|
+
"error_code": report.code,
|
|
97
|
+
**({"actor": report.actor} if report.actor else {}),
|
|
98
|
+
**{f"error_{k}": v for k, v in report.context.items() if k not in _LOGGED},
|
|
99
|
+
},
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def describe(report: ErrorReport) -> str:
|
|
104
|
+
"""A short title for a report (log message, issue title)."""
|
|
105
|
+
c = report.context
|
|
106
|
+
where = report.where
|
|
107
|
+
if where == "job":
|
|
108
|
+
return f"Job {c.get('job')} failed"
|
|
109
|
+
if c.get("hook"):
|
|
110
|
+
return f"{where} hook {c['hook']} failed for {c.get('resource')}"
|
|
111
|
+
if c.get("callback"):
|
|
112
|
+
return f"{where} {c['callback']} failed for {c.get('resource')}"
|
|
113
|
+
if where == "timer":
|
|
114
|
+
record = f"{c.get('resource')} {c.get('entity_id')!r}"
|
|
115
|
+
return f"Timed transition {c.get('timer')} failed for {record}"
|
|
116
|
+
if where == "consumer":
|
|
117
|
+
return (
|
|
118
|
+
f"Message {c.get('message_id')} ({c.get('event_type')}) failed in {c.get('consumer')}"
|
|
119
|
+
)
|
|
120
|
+
if where == "operation":
|
|
121
|
+
return f"{c.get('resource')} {c.get('operation')} failed"
|
|
122
|
+
if where in ("http", "graphql", "mcp") and c.get("route"):
|
|
123
|
+
return f"{c.get('method', where.upper())} {c['route']} failed"
|
|
124
|
+
if where == "outbox":
|
|
125
|
+
return "Publishing outbox messages failed"
|
|
126
|
+
return f"{where} failed"
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
# Fields the log context already carries onto every record.
|
|
130
|
+
_LOGGED = {
|
|
131
|
+
"correlation_id",
|
|
132
|
+
"resource",
|
|
133
|
+
"operation",
|
|
134
|
+
"entity_id",
|
|
135
|
+
"action",
|
|
136
|
+
"consumer",
|
|
137
|
+
"message_id",
|
|
138
|
+
"event_type",
|
|
139
|
+
"job",
|
|
140
|
+
"request_id",
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
_reporters: list[Any] = [LoggingReporter()]
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def set_reporter(*reporters: Any, logging_too: bool = True) -> None:
|
|
147
|
+
"""Send reports to ``reporters`` (and, with ``logging_too``, to the log)."""
|
|
148
|
+
_reporters[:] = [*([LoggingReporter()] if logging_too else []), *reporters]
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def get_reporters() -> list[Any]:
|
|
152
|
+
"""The error reporters installed."""
|
|
153
|
+
return list(_reporters)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def is_expected(error: BaseException) -> bool:
|
|
157
|
+
"""Client and business errors: answers to the caller, not failures."""
|
|
158
|
+
from resource_engine import errors as e
|
|
159
|
+
from resource_engine.domain import DomainError
|
|
160
|
+
|
|
161
|
+
if isinstance(error, DomainError):
|
|
162
|
+
return True
|
|
163
|
+
if isinstance(error, e.TransactionDoomed):
|
|
164
|
+
cause = error.__cause__
|
|
165
|
+
return cause is not None and is_expected(cause)
|
|
166
|
+
unexpected = (
|
|
167
|
+
e.ConfigurationError,
|
|
168
|
+
e.RemoteCallFailed,
|
|
169
|
+
e.StorageFailed,
|
|
170
|
+
e.PublishFailed,
|
|
171
|
+
e.ConditionNotSupported,
|
|
172
|
+
)
|
|
173
|
+
if isinstance(error, unexpected):
|
|
174
|
+
return False
|
|
175
|
+
return isinstance(error, e.ResourceEngineError)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
async def report_error(
|
|
179
|
+
error: BaseException,
|
|
180
|
+
*,
|
|
181
|
+
where: str,
|
|
182
|
+
level: Level | None = None,
|
|
183
|
+
actor: Any = None,
|
|
184
|
+
force: bool = False,
|
|
185
|
+
**context: Any,
|
|
186
|
+
) -> None:
|
|
187
|
+
"""Report ``error`` once (later calls for the same exception are ignored).
|
|
188
|
+
Expected errors are skipped unless ``force``. Never raises."""
|
|
189
|
+
if getattr(error, _MARK, False):
|
|
190
|
+
return
|
|
191
|
+
cause = error.__cause__
|
|
192
|
+
if cause is not None and getattr(cause, _MARK, False):
|
|
193
|
+
return # the original failure was reported (a doomed transaction, a wrapper)
|
|
194
|
+
if not force and is_expected(error):
|
|
195
|
+
return
|
|
196
|
+
with contextlib.suppress(Exception): # some exceptions forbid attributes
|
|
197
|
+
setattr(error, _MARK, True)
|
|
198
|
+
report = ErrorReport(
|
|
199
|
+
error=error,
|
|
200
|
+
where=where,
|
|
201
|
+
level=level or ("warning" if is_expected(error) else "error"),
|
|
202
|
+
code=error_type(error),
|
|
203
|
+
context={**log_context(), **{k: v for k, v in context.items() if v is not None}},
|
|
204
|
+
actor=getattr(actor, "id", None) or (str(actor) if isinstance(actor, str) else None),
|
|
205
|
+
)
|
|
206
|
+
for reporter in list(_reporters):
|
|
207
|
+
try:
|
|
208
|
+
result = reporter.report(report)
|
|
209
|
+
if inspect.isawaitable(result):
|
|
210
|
+
await result
|
|
211
|
+
except Exception: # a broken reporter must not hide the original failure
|
|
212
|
+
logger.exception("Error reporter %r failed", reporter)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def was_reported(error: BaseException) -> bool:
|
|
216
|
+
"""Whether ``error`` was already sent to the reporters."""
|
|
217
|
+
return bool(getattr(error, _MARK, False))
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
__all__ = [
|
|
221
|
+
"ErrorReport",
|
|
222
|
+
"ErrorReporter",
|
|
223
|
+
"LoggingReporter",
|
|
224
|
+
"describe",
|
|
225
|
+
"get_reporters",
|
|
226
|
+
"is_expected",
|
|
227
|
+
"report_error",
|
|
228
|
+
"set_reporter",
|
|
229
|
+
"was_reported",
|
|
230
|
+
]
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Example values from JSON Schemas: a starting point to edit in a form (the
|
|
2
|
+
explorer's request bodies and event payloads)."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def example(schema: Mapping[str, Any], schemas: Mapping[str, Any], depth: int = 0) -> Any:
|
|
11
|
+
"""A value to start editing from: the required fields (or, when none is,
|
|
12
|
+
the first one as a hint), empty strings, zeros, the first enum value."""
|
|
13
|
+
if "$ref" in schema:
|
|
14
|
+
return example(schemas.get(schema["$ref"].rsplit("/", 1)[-1], {}), schemas, depth)
|
|
15
|
+
for key in ("anyOf", "oneOf"):
|
|
16
|
+
if key in schema:
|
|
17
|
+
options = [s for s in schema[key] if s.get("type") != "null"]
|
|
18
|
+
return example(options[0], schemas, depth) if options else None
|
|
19
|
+
if "allOf" in schema:
|
|
20
|
+
return example(schema["allOf"][0], schemas, depth)
|
|
21
|
+
if "enum" in schema:
|
|
22
|
+
return schema["enum"][0]
|
|
23
|
+
if "const" in schema:
|
|
24
|
+
return schema["const"]
|
|
25
|
+
if "default" in schema and schema["default"] is not None:
|
|
26
|
+
return schema["default"]
|
|
27
|
+
kind = schema.get("type")
|
|
28
|
+
if kind == "object" or "properties" in schema:
|
|
29
|
+
if depth > 2:
|
|
30
|
+
return {}
|
|
31
|
+
properties = schema.get("properties", {})
|
|
32
|
+
names = [n for n in properties if n in schema.get("required", [])]
|
|
33
|
+
names = names or list(properties)[:1]
|
|
34
|
+
return {n: example(properties[n], schemas, depth + 1) for n in names}
|
|
35
|
+
if kind == "array":
|
|
36
|
+
return []
|
|
37
|
+
if kind == "integer":
|
|
38
|
+
return 0
|
|
39
|
+
if kind == "number":
|
|
40
|
+
return 0
|
|
41
|
+
if kind == "boolean":
|
|
42
|
+
return False
|
|
43
|
+
fmt = schema.get("format")
|
|
44
|
+
if fmt == "date":
|
|
45
|
+
return "2026-01-31"
|
|
46
|
+
if fmt == "date-time":
|
|
47
|
+
return "2026-01-31T10:00:00Z"
|
|
48
|
+
return ""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
__all__ = ["example"]
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Templates: locale fallback shared by every renderer, and ``StringTemplates``,
|
|
2
|
+
a renderer for tests and small apps (``string.Template`` placeholders).
|
|
3
|
+
|
|
4
|
+
For real templates (loops, conditions, inheritance, autoescaping) use
|
|
5
|
+
``resource_engine_jinja.JinjaTemplates``. See docs/email.md#templates.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import html
|
|
11
|
+
import re
|
|
12
|
+
from collections.abc import Mapping
|
|
13
|
+
from string import Template
|
|
14
|
+
from typing import Any, override
|
|
15
|
+
|
|
16
|
+
from resource_engine.errors import TemplateFailed, TemplateNotFound
|
|
17
|
+
from resource_engine.ports.templates import PreviewableTemplates
|
|
18
|
+
|
|
19
|
+
#: Extensions whose values are HTML-escaped.
|
|
20
|
+
HTML_EXTENSIONS = (".html", ".htm", ".xml")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def locale_candidates(locale: str | None, default: str | None = None) -> list[str | None]:
|
|
24
|
+
"""Where to look, most specific first: ``ca-ES`` → ``["ca-ES", "ca", <default>, None]``.
|
|
25
|
+
|
|
26
|
+
``None`` is the unlocalised template. ``_`` and ``-`` are accepted alike
|
|
27
|
+
(``pt_BR`` is ``pt-BR``).
|
|
28
|
+
"""
|
|
29
|
+
out: list[str | None] = []
|
|
30
|
+
for value in (locale, default):
|
|
31
|
+
if not value:
|
|
32
|
+
continue
|
|
33
|
+
value = value.replace("_", "-")
|
|
34
|
+
parts = value.split("-")
|
|
35
|
+
for size in range(len(parts), 0, -1):
|
|
36
|
+
candidate = "-".join(parts[:size])
|
|
37
|
+
if candidate not in out:
|
|
38
|
+
out.append(candidate)
|
|
39
|
+
out.append(None)
|
|
40
|
+
return out
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
#: A leading path segment read as a locale: ``ca``, ``pt-BR``, ``zh-Hant``, ``es-419``.
|
|
44
|
+
LOCALE = re.compile(r"^[a-z]{2,3}(-[A-Z]{2}|-[A-Z][a-z]{3}|-\d{3})?$")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def split_locale(key: str) -> tuple[str | None, str]:
|
|
48
|
+
"""``ca/email/x.txt`` → ``("ca", "email/x.txt")``; ``email/x.txt`` → ``(None, ...)``.
|
|
49
|
+
|
|
50
|
+
Top-level folders of two or three lower-case letters are locales, so
|
|
51
|
+
don't name template folders that way (``pdf/``): use ``documents/``.
|
|
52
|
+
"""
|
|
53
|
+
first, _, rest = key.partition("/")
|
|
54
|
+
if rest and LOCALE.match(first):
|
|
55
|
+
return first, rest
|
|
56
|
+
return None, key
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def localised(name: str, locale: str | None) -> str:
|
|
60
|
+
"""``email/x.txt`` in ``ca`` is ``ca/email/x.txt``."""
|
|
61
|
+
return f"{locale}/{name}" if locale else name
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def not_found(name: str, locale: str | None, tried: list[str]) -> TemplateNotFound:
|
|
65
|
+
"""The error for a template missing in every locale tried."""
|
|
66
|
+
return TemplateNotFound(
|
|
67
|
+
f"No template {name!r}" + (f" for locale {locale!r}" if locale else ""),
|
|
68
|
+
details={"name": name, "locale": locale, "tried": tried},
|
|
69
|
+
hint="Add the template, or one for a broader locale or with no locale.",
|
|
70
|
+
doc="docs/email.md#templates",
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class StringTemplates(PreviewableTemplates):
|
|
75
|
+
"""Templates from a mapping, with ``$name`` / ``${name}`` placeholders.
|
|
76
|
+
|
|
77
|
+
Keys are names with an optional locale prefix (``ca/email/x.txt``).
|
|
78
|
+
Values in ``.html`` templates are escaped. A missing variable is
|
|
79
|
+
``TemplateFailed``, never an empty string.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
def __init__(self, templates: Mapping[str, str], *, default_locale: str | None = None) -> None:
|
|
83
|
+
self.templates = dict(templates)
|
|
84
|
+
self.default_locale = default_locale
|
|
85
|
+
|
|
86
|
+
def _find(self, name: str, locale: str | None) -> tuple[str, str]:
|
|
87
|
+
tried = []
|
|
88
|
+
for candidate in locale_candidates(locale, self.default_locale):
|
|
89
|
+
key = localised(name, candidate)
|
|
90
|
+
tried.append(key)
|
|
91
|
+
if key in self.templates:
|
|
92
|
+
return key, self.templates[key]
|
|
93
|
+
raise not_found(name, locale, tried)
|
|
94
|
+
|
|
95
|
+
@override
|
|
96
|
+
def render(self, name: str, context: Mapping[str, Any], *, locale: str | None = None) -> str:
|
|
97
|
+
key, source = self._find(name, locale)
|
|
98
|
+
escape = name.endswith(HTML_EXTENSIONS)
|
|
99
|
+
values = {k: html.escape(str(v)) if escape else v for k, v in context.items()}
|
|
100
|
+
try:
|
|
101
|
+
return Template(source).substitute(values)
|
|
102
|
+
except (KeyError, ValueError) as exc:
|
|
103
|
+
raise TemplateFailed(
|
|
104
|
+
f"Template {key!r} failed: {exc!r}",
|
|
105
|
+
details={"name": key, "error": repr(exc)},
|
|
106
|
+
) from exc
|
|
107
|
+
|
|
108
|
+
@override
|
|
109
|
+
def exists(self, name: str, *, locale: str | None = None) -> bool:
|
|
110
|
+
try:
|
|
111
|
+
self._find(name, locale)
|
|
112
|
+
except TemplateNotFound:
|
|
113
|
+
return False
|
|
114
|
+
return True
|
|
115
|
+
|
|
116
|
+
@override
|
|
117
|
+
def names(self) -> list[str]:
|
|
118
|
+
return sorted({split_locale(key)[1] for key in self.templates})
|
|
119
|
+
|
|
120
|
+
@override
|
|
121
|
+
def variants(self, name: str) -> list[str | None]:
|
|
122
|
+
found = [loc for loc, rest in map(split_locale, self.templates) if rest == name]
|
|
123
|
+
return sorted(found, key=lambda loc: (loc is not None, loc or ""))
|
|
124
|
+
|
|
125
|
+
def preview(self, name: str, *, locale: str | None = None) -> str:
|
|
126
|
+
"""Placeholders stay as they are written (``$customer``)."""
|
|
127
|
+
if locale is None:
|
|
128
|
+
if name not in self.templates:
|
|
129
|
+
raise not_found(name, None, [name])
|
|
130
|
+
return self.templates[name]
|
|
131
|
+
_, source = self._find(name, locale)
|
|
132
|
+
return source
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
__all__ = [
|
|
136
|
+
"HTML_EXTENSIONS",
|
|
137
|
+
"LOCALE",
|
|
138
|
+
"StringTemplates",
|
|
139
|
+
"locale_candidates",
|
|
140
|
+
"localised",
|
|
141
|
+
"not_found",
|
|
142
|
+
"split_locale",
|
|
143
|
+
]
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Tenant scoping: confine operations on tenant-scoped resources to the caller's
|
|
2
|
+
tenant, independently of permission policies. See docs/tenancy.md."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from resource_engine.errors import TenantMismatch, TenantRequired
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class TenantScope:
|
|
14
|
+
"""``tenant`` the operation is confined to; ``cross`` callers may act on any
|
|
15
|
+
tenant (``tenant`` is then ``None`` unless they narrowed it)."""
|
|
16
|
+
|
|
17
|
+
tenant: str | None
|
|
18
|
+
cross: bool
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
async def is_cross_tenant(actor: Any, authorizer: Any) -> bool:
|
|
22
|
+
"""Whether ``actor`` may work across tenants: the engine itself, or a caller holding a cross-
|
|
23
|
+
tenant role."""
|
|
24
|
+
from resource_engine.authz.base import SystemPrincipal
|
|
25
|
+
from resource_engine.ports.identity import Principal
|
|
26
|
+
|
|
27
|
+
if isinstance(actor, SystemPrincipal):
|
|
28
|
+
return True
|
|
29
|
+
if not isinstance(actor, Principal) or authorizer is None:
|
|
30
|
+
return False
|
|
31
|
+
roles_of = getattr(authorizer, "roles_of", None)
|
|
32
|
+
config = getattr(authorizer, "config", None)
|
|
33
|
+
if roles_of is None or config is None:
|
|
34
|
+
return False
|
|
35
|
+
for name in await roles_of(actor):
|
|
36
|
+
role = config.system_role(name)
|
|
37
|
+
if role is not None and role.cross_tenant:
|
|
38
|
+
return True
|
|
39
|
+
return False
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
async def resolve_tenant(actor: Any, authorizer: Any, requested: str | None) -> TenantScope:
|
|
43
|
+
"""The scope of ``actor``; ``requested`` narrows cross-tenant callers and must
|
|
44
|
+
match the tenant of confined ones."""
|
|
45
|
+
if await is_cross_tenant(actor, authorizer):
|
|
46
|
+
return TenantScope(requested, True)
|
|
47
|
+
own = getattr(actor, "tenant", None)
|
|
48
|
+
if not own:
|
|
49
|
+
raise TenantRequired(
|
|
50
|
+
"This resource is tenant-scoped and the caller has no tenant",
|
|
51
|
+
hint="The identity provider must issue a tenant claim (Principal.tenant).",
|
|
52
|
+
details={"reason": "no tenant"},
|
|
53
|
+
doc="docs/tenancy.md",
|
|
54
|
+
)
|
|
55
|
+
if requested is not None and requested != own:
|
|
56
|
+
raise TenantMismatch(
|
|
57
|
+
f"Not allowed to act on tenant {requested!r}",
|
|
58
|
+
details={"reason": "other tenant", "tenant": requested},
|
|
59
|
+
doc="docs/tenancy.md",
|
|
60
|
+
)
|
|
61
|
+
return TenantScope(own, False)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
__all__ = [
|
|
65
|
+
"TenantScope",
|
|
66
|
+
"is_cross_tenant",
|
|
67
|
+
"resolve_tenant",
|
|
68
|
+
]
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""In-memory adapters for tests and prototypes."""
|
|
2
|
+
|
|
3
|
+
from resource_engine.testing.activity import InMemoryActivityLog
|
|
4
|
+
from resource_engine.testing.email import RecordingEmailSender
|
|
5
|
+
from resource_engine.testing.engine import ConditionEngine
|
|
6
|
+
from resource_engine.testing.memory import (
|
|
7
|
+
InMemoryInbox,
|
|
8
|
+
InMemoryLocks,
|
|
9
|
+
InMemoryQueue,
|
|
10
|
+
InMemoryRepository,
|
|
11
|
+
InMemoryStore,
|
|
12
|
+
InMemoryUnitOfWork,
|
|
13
|
+
RecordingEventPublisher,
|
|
14
|
+
RecordingMessagePublisher,
|
|
15
|
+
)
|
|
16
|
+
from resource_engine.testing.storage import InMemoryBlobStore
|
|
17
|
+
from resource_engine.testing.tracing import RecordedSpan, RecordingTracer
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"ConditionEngine",
|
|
21
|
+
"InMemoryActivityLog",
|
|
22
|
+
"InMemoryBlobStore",
|
|
23
|
+
"InMemoryInbox",
|
|
24
|
+
"InMemoryLocks",
|
|
25
|
+
"InMemoryQueue",
|
|
26
|
+
"InMemoryRepository",
|
|
27
|
+
"InMemoryStore",
|
|
28
|
+
"InMemoryUnitOfWork",
|
|
29
|
+
"RecordedSpan",
|
|
30
|
+
"RecordingEmailSender",
|
|
31
|
+
"RecordingEventPublisher",
|
|
32
|
+
"RecordingMessagePublisher",
|
|
33
|
+
"RecordingTracer",
|
|
34
|
+
]
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""``ActivityLog`` in this process (tests, single-process apps)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import dataclasses
|
|
6
|
+
import uuid
|
|
7
|
+
from collections.abc import Collection, Sequence
|
|
8
|
+
from datetime import UTC, datetime
|
|
9
|
+
from typing import override
|
|
10
|
+
|
|
11
|
+
from resource_engine.ports.activity import (
|
|
12
|
+
ActivityLog,
|
|
13
|
+
DeliveryRecord,
|
|
14
|
+
JobInfo,
|
|
15
|
+
JobRunRecord,
|
|
16
|
+
RequestStatus,
|
|
17
|
+
RunRequest,
|
|
18
|
+
WorkerJobs,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class InMemoryActivityLog(ActivityLog):
|
|
23
|
+
"""An activity log in memory, for tests."""
|
|
24
|
+
|
|
25
|
+
def __init__(self) -> None:
|
|
26
|
+
self.delivered: list[DeliveryRecord] = []
|
|
27
|
+
self.runs: list[JobRunRecord] = []
|
|
28
|
+
self.requests: dict[str, RunRequest] = {}
|
|
29
|
+
self.registered: dict[str, WorkerJobs] = {}
|
|
30
|
+
|
|
31
|
+
# ---------------------------------------------------------------- jobs
|
|
32
|
+
|
|
33
|
+
@override
|
|
34
|
+
async def register_jobs(self, owner: str, jobs: Sequence[JobInfo]) -> None:
|
|
35
|
+
self.registered[owner] = WorkerJobs(owner, tuple(jobs))
|
|
36
|
+
|
|
37
|
+
@override
|
|
38
|
+
async def workers(self) -> list[WorkerJobs]:
|
|
39
|
+
return sorted(self.registered.values(), key=lambda w: w.seen_at, reverse=True)
|
|
40
|
+
|
|
41
|
+
@override
|
|
42
|
+
async def record_job_run(self, run: JobRunRecord) -> None:
|
|
43
|
+
self.runs.append(run)
|
|
44
|
+
|
|
45
|
+
@override
|
|
46
|
+
async def job_runs(self, job: str | None = None, limit: int = 50) -> list[JobRunRecord]:
|
|
47
|
+
found = [r for r in self.runs if job is None or r.job == job]
|
|
48
|
+
return sorted(found, key=lambda r: r.at, reverse=True)[:limit]
|
|
49
|
+
|
|
50
|
+
@override
|
|
51
|
+
async def request_run(self, job: str, requested_by: str | None) -> RunRequest:
|
|
52
|
+
request = RunRequest(uuid.uuid4().hex, job, requested_by)
|
|
53
|
+
self.requests[request.id] = request
|
|
54
|
+
return request
|
|
55
|
+
|
|
56
|
+
@override
|
|
57
|
+
async def run_request(self, request_id: str) -> RunRequest | None:
|
|
58
|
+
return self.requests.get(request_id)
|
|
59
|
+
|
|
60
|
+
@override
|
|
61
|
+
async def claim_requests(
|
|
62
|
+
self, owner: str, jobs: Collection[str], limit: int = 10
|
|
63
|
+
) -> list[RunRequest]:
|
|
64
|
+
pending = sorted(
|
|
65
|
+
(r for r in self.requests.values() if r.status == "pending" and r.job in jobs),
|
|
66
|
+
key=lambda r: r.requested_at,
|
|
67
|
+
)[:limit]
|
|
68
|
+
claimed = [dataclasses.replace(r, status="running", claimed_by=owner) for r in pending]
|
|
69
|
+
for request in claimed:
|
|
70
|
+
self.requests[request.id] = request
|
|
71
|
+
return claimed
|
|
72
|
+
|
|
73
|
+
@override
|
|
74
|
+
async def finish_request(
|
|
75
|
+
self, request_id: str, status: RequestStatus, error: str | None = None
|
|
76
|
+
) -> None:
|
|
77
|
+
request = self.requests.get(request_id)
|
|
78
|
+
if request is not None:
|
|
79
|
+
self.requests[request_id] = dataclasses.replace(
|
|
80
|
+
request, status=status, error=error, finished_at=datetime.now(UTC)
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
# ---------------------------------------------------------- deliveries
|
|
84
|
+
|
|
85
|
+
@override
|
|
86
|
+
async def record_delivery(self, record: DeliveryRecord) -> None:
|
|
87
|
+
self.delivered.append(record)
|
|
88
|
+
|
|
89
|
+
@override
|
|
90
|
+
async def deliveries(self, message_id: str) -> list[DeliveryRecord]:
|
|
91
|
+
return sorted((r for r in self.delivered if r.message_id == message_id), key=lambda r: r.at)
|
|
92
|
+
|
|
93
|
+
@override
|
|
94
|
+
async def dead_letters(self, limit: int = 50) -> list[DeliveryRecord]:
|
|
95
|
+
found = [r for r in self.delivered if r.outcome == "dead_letter"]
|
|
96
|
+
return sorted(found, key=lambda r: r.at, reverse=True)[:limit]
|
|
97
|
+
|
|
98
|
+
@override
|
|
99
|
+
async def purge(self, before: datetime, limit: int) -> int:
|
|
100
|
+
count = 0
|
|
101
|
+
for record in [r for r in self.delivered if r.at < before][:limit]:
|
|
102
|
+
self.delivered.remove(record)
|
|
103
|
+
count += 1
|
|
104
|
+
for run in [r for r in self.runs if r.at < before][: limit - count]:
|
|
105
|
+
self.runs.remove(run)
|
|
106
|
+
count += 1
|
|
107
|
+
finished = [
|
|
108
|
+
r
|
|
109
|
+
for r in self.requests.values()
|
|
110
|
+
if r.finished_at is not None and r.finished_at < before
|
|
111
|
+
][: limit - count]
|
|
112
|
+
for request in finished:
|
|
113
|
+
del self.requests[request.id]
|
|
114
|
+
count += 1
|
|
115
|
+
for owner in [w.owner for w in self.registered.values() if w.seen_at < before][
|
|
116
|
+
: limit - count
|
|
117
|
+
]:
|
|
118
|
+
del self.registered[owner]
|
|
119
|
+
count += 1
|
|
120
|
+
return count
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
__all__ = ["InMemoryActivityLog"]
|