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,233 @@
|
|
|
1
|
+
"""Documents generated from templates: an invoice, a delivery note, a
|
|
2
|
+
certificate, rendered per locale and attached to a record's document slot.
|
|
3
|
+
|
|
4
|
+
```python
|
|
5
|
+
generator = DocumentGenerator(templates, pdf=GotenbergPdfConverter(http, "http://gotenberg:3000"))
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class PrintInvoice(Action):
|
|
9
|
+
async def execute(self, ctx: OperationContext) -> None:
|
|
10
|
+
await generator.attach(ctx, "printed", "invoice", format="pdf", locale="ca")
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
- **Templates** come from the ``TemplateRenderer`` (``JinjaTemplates``) under
|
|
14
|
+
``documents/``: ``documents/invoice.html`` for HTML and PDF,
|
|
15
|
+
``documents/invoice.md`` or ``.txt`` for text. They get ``record`` (the
|
|
16
|
+
entity's fields), ``resource`` and whatever ``context`` adds, in ``locale``.
|
|
17
|
+
- **PDF** goes through the ``PdfConverter`` port: the HTML template, printed
|
|
18
|
+
by ``GotenbergPdfConverter`` (``resource-engine-http``, headless Chromium).
|
|
19
|
+
- **Attaching** stores the result in the record's slot inside the operation,
|
|
20
|
+
like any upload: it is part of the change and undone if it rolls back.
|
|
21
|
+
- **Printouts** render a record on request without storing anything:
|
|
22
|
+
``Resource.printouts = {"invoice": Printout(formats=("pdf", "html"))}`` and
|
|
23
|
+
``ResourceManager(generator=...)`` serve ``GET /invoices/7/printouts/invoice``.
|
|
24
|
+
The record is read as the caller (``get`` permission, row filter, tenant),
|
|
25
|
+
and fields they may not read are left out of the template's ``record``.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import dataclasses
|
|
31
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
32
|
+
from dataclasses import dataclass
|
|
33
|
+
from typing import Any, Literal, Protocol
|
|
34
|
+
|
|
35
|
+
from resource_engine.errors import ConfigurationError, OperationNotEnabled, TemplateNotFound
|
|
36
|
+
|
|
37
|
+
type DocumentFormat = Literal["pdf", "html", "md", "txt"]
|
|
38
|
+
|
|
39
|
+
CONTENT_TYPES = {
|
|
40
|
+
"pdf": "application/pdf",
|
|
41
|
+
"html": "text/html; charset=utf-8",
|
|
42
|
+
"md": "text/markdown; charset=utf-8",
|
|
43
|
+
"txt": "text/plain; charset=utf-8",
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class PdfConverter(Protocol):
|
|
48
|
+
"""Prints HTML to PDF (``GotenbergPdfConverter``)."""
|
|
49
|
+
|
|
50
|
+
async def html_to_pdf(self, html: str) -> bytes:
|
|
51
|
+
"""The PDF printed from ``html``."""
|
|
52
|
+
...
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class GeneratedDocument:
|
|
57
|
+
"""A generated document: its bytes, media type and file extension."""
|
|
58
|
+
|
|
59
|
+
content: bytes
|
|
60
|
+
content_type: str
|
|
61
|
+
extension: str
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def record_context(entity: Any) -> dict[str, Any]:
|
|
65
|
+
"""An entity's fields for a template."""
|
|
66
|
+
if dataclasses.is_dataclass(entity) and not isinstance(entity, type):
|
|
67
|
+
return {f.name: getattr(entity, f.name) for f in dataclasses.fields(entity)}
|
|
68
|
+
if hasattr(entity, "model_dump"):
|
|
69
|
+
dumped: dict[str, Any] = entity.model_dump()
|
|
70
|
+
return dumped
|
|
71
|
+
return {k: v for k, v in vars(entity).items() if not k.startswith("_")}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(frozen=True)
|
|
75
|
+
class Printout:
|
|
76
|
+
"""A document rendered from one record on request (``Resource.printouts``).
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
template: Template name under ``documents/`` (default: the printout's name).
|
|
80
|
+
formats: Formats it can be asked for; the first is the default.
|
|
81
|
+
context: Extra template values from the record's readable fields (a
|
|
82
|
+
dict) and the caller: ``lambda record, actor: {"copy": True}``.
|
|
83
|
+
description: For the API documents.
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
template: str | None = None
|
|
87
|
+
formats: Sequence[DocumentFormat] = ("pdf",)
|
|
88
|
+
context: Callable[[Any, Any], Mapping[str, Any]] | None = None
|
|
89
|
+
description: str | None = None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def check_printouts(registry: Any, generator: Any) -> None:
|
|
93
|
+
"""Every printout has known formats. Without a generator printouts aren't
|
|
94
|
+
served (no route), and asking for one is RE-E001."""
|
|
95
|
+
for definition in registry:
|
|
96
|
+
printouts = definition.resource_cls.printouts
|
|
97
|
+
for name, printout in printouts.items():
|
|
98
|
+
unknown = [f for f in printout.formats if f not in CONTENT_TYPES]
|
|
99
|
+
if unknown or not printout.formats:
|
|
100
|
+
raise ConfigurationError(
|
|
101
|
+
f"Printout {definition.name}.{name} has unknown formats {unknown}",
|
|
102
|
+
hint=f"Use some of {sorted(CONTENT_TYPES)}.",
|
|
103
|
+
doc="docs/documents.md#printouts",
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class DocumentGenerator:
|
|
108
|
+
"""Renders document templates and attaches the results to records.
|
|
109
|
+
|
|
110
|
+
Args:
|
|
111
|
+
templates: The ``TemplateRenderer``.
|
|
112
|
+
pdf: The ``PdfConverter`` for ``format="pdf"``.
|
|
113
|
+
prefix: Folder of the document templates.
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
def __init__(
|
|
117
|
+
self, templates: Any, *, pdf: PdfConverter | None = None, prefix: str = "documents/"
|
|
118
|
+
) -> None:
|
|
119
|
+
self.templates = templates
|
|
120
|
+
self.pdf = pdf
|
|
121
|
+
self.prefix = prefix
|
|
122
|
+
|
|
123
|
+
async def generate(
|
|
124
|
+
self,
|
|
125
|
+
template: str,
|
|
126
|
+
context: Mapping[str, Any],
|
|
127
|
+
*,
|
|
128
|
+
format: DocumentFormat = "pdf",
|
|
129
|
+
locale: str | None = None,
|
|
130
|
+
) -> GeneratedDocument:
|
|
131
|
+
"""Render ``template`` with ``context`` (HTML or PDF, in ``locale``), ready to attach to a
|
|
132
|
+
record."""
|
|
133
|
+
if format not in CONTENT_TYPES:
|
|
134
|
+
raise ConfigurationError(f"Unknown document format {format!r}")
|
|
135
|
+
source = "html" if format == "pdf" else format
|
|
136
|
+
name = f"{self.prefix}{template}.{source}"
|
|
137
|
+
if not self.templates.exists(name, locale=locale):
|
|
138
|
+
raise TemplateNotFound(
|
|
139
|
+
f"No document template {name!r}",
|
|
140
|
+
details={"name": name, "locale": locale, "tried": [name]},
|
|
141
|
+
doc="docs/documents.md#generated-documents",
|
|
142
|
+
)
|
|
143
|
+
text = self.templates.render(name, dict(context), locale=locale)
|
|
144
|
+
if format == "pdf":
|
|
145
|
+
if self.pdf is None:
|
|
146
|
+
raise ConfigurationError(
|
|
147
|
+
"PDF documents need a PdfConverter",
|
|
148
|
+
hint="DocumentGenerator(templates, pdf=GotenbergPdfConverter(...)).",
|
|
149
|
+
)
|
|
150
|
+
return GeneratedDocument(await self.pdf.html_to_pdf(text), CONTENT_TYPES["pdf"], "pdf")
|
|
151
|
+
return GeneratedDocument(text.encode("utf-8"), CONTENT_TYPES[format], format)
|
|
152
|
+
|
|
153
|
+
async def attach(
|
|
154
|
+
self,
|
|
155
|
+
ctx: Any,
|
|
156
|
+
slot: str,
|
|
157
|
+
template: str,
|
|
158
|
+
*,
|
|
159
|
+
format: DocumentFormat = "pdf",
|
|
160
|
+
filename: str | None = None,
|
|
161
|
+
context: Mapping[str, Any] | None = None,
|
|
162
|
+
locale: str | None = None,
|
|
163
|
+
) -> Any:
|
|
164
|
+
"""Render ``template`` for the operation's record and attach it to
|
|
165
|
+
``slot`` (inside the operation: a rollback removes it)."""
|
|
166
|
+
from resource_engine.documents.model import NewDocument
|
|
167
|
+
|
|
168
|
+
values = {
|
|
169
|
+
"record": record_context(ctx.entity),
|
|
170
|
+
"resource": ctx.resource.name,
|
|
171
|
+
**dict(context or {}),
|
|
172
|
+
}
|
|
173
|
+
document = await self.generate(template, values, format=format, locale=locale)
|
|
174
|
+
name = filename or f"{template}-{getattr(ctx.entity, 'id', 'record')}.{document.extension}"
|
|
175
|
+
return await ctx.documents.attach(
|
|
176
|
+
NewDocument(slot, document.content, name, document.content_type.split(";")[0])
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
async def printout(
|
|
180
|
+
self,
|
|
181
|
+
manager: Any,
|
|
182
|
+
resource: str,
|
|
183
|
+
entity_id: Any,
|
|
184
|
+
name: str,
|
|
185
|
+
*,
|
|
186
|
+
format: DocumentFormat | None = None,
|
|
187
|
+
locale: str | None = None,
|
|
188
|
+
actor: Any = None,
|
|
189
|
+
tenant: str | None = None,
|
|
190
|
+
) -> tuple[GeneratedDocument, str]:
|
|
191
|
+
"""Render printout ``name`` of one record as ``actor``: ``(document,
|
|
192
|
+
file name)``. Nothing is stored."""
|
|
193
|
+
from pydantic import BaseModel
|
|
194
|
+
|
|
195
|
+
from resource_engine.authz.fields import hidden_fields
|
|
196
|
+
|
|
197
|
+
definition = manager.registry.get(resource)
|
|
198
|
+
printout = definition.resource_cls.printouts.get(name)
|
|
199
|
+
if printout is None:
|
|
200
|
+
raise OperationNotEnabled(
|
|
201
|
+
f"{resource} has no printout {name!r}",
|
|
202
|
+
details={"printouts": sorted(definition.resource_cls.printouts)},
|
|
203
|
+
)
|
|
204
|
+
chosen = format or printout.formats[0]
|
|
205
|
+
if chosen not in printout.formats:
|
|
206
|
+
raise OperationNotEnabled(
|
|
207
|
+
f"Printout {resource}.{name} is not available as {chosen}",
|
|
208
|
+
details={"formats": list(printout.formats)},
|
|
209
|
+
)
|
|
210
|
+
record = await manager.get(resource, entity_id, actor=actor, tenant=tenant)
|
|
211
|
+
values = (
|
|
212
|
+
record.model_dump(exclude=set(hidden_fields(record)))
|
|
213
|
+
if isinstance(record, BaseModel)
|
|
214
|
+
else record_context(record)
|
|
215
|
+
)
|
|
216
|
+
context = {"record": values, "resource": resource}
|
|
217
|
+
if printout.context is not None:
|
|
218
|
+
context.update(printout.context(values, actor))
|
|
219
|
+
document = await self.generate(
|
|
220
|
+
printout.template or name, context, format=chosen, locale=locale
|
|
221
|
+
)
|
|
222
|
+
return document, f"{name}-{entity_id}.{document.extension}"
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
__all__ = [
|
|
226
|
+
"CONTENT_TYPES",
|
|
227
|
+
"DocumentGenerator",
|
|
228
|
+
"GeneratedDocument",
|
|
229
|
+
"PdfConverter",
|
|
230
|
+
"Printout",
|
|
231
|
+
"check_printouts",
|
|
232
|
+
"record_context",
|
|
233
|
+
]
|
resource_engine/i18n.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
"""Translations: gettext catalogues per locale and the locale of the current
|
|
2
|
+
request, with the standard library only (compiled ``.mo`` files).
|
|
3
|
+
|
|
4
|
+
```python
|
|
5
|
+
from resource_engine.i18n import Translations, set_translations, use_locale, gettext as _
|
|
6
|
+
|
|
7
|
+
set_translations(Translations("invoices/locale", default_locale="ca"))
|
|
8
|
+
with use_locale("en"):
|
|
9
|
+
_("Factura aprovada") # → "Invoice approved"
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
- **Catalogues:** ``<directory>/<locale>/LC_MESSAGES/<domain>.mo``, written
|
|
13
|
+
by ``resource-engine i18n compile`` from the ``.po`` files translators edit.
|
|
14
|
+
- **Locale:** a context variable, set per request by the HTTP adapter
|
|
15
|
+
(``Accept-Language``, or the principal's ``locale`` claim) and per message by
|
|
16
|
+
the mailer. ``ca-ES`` falls back to ``ca``, then to the default locale, then
|
|
17
|
+
to the text as written in the code.
|
|
18
|
+
- **Engine messages:** the engine's own texts (error titles) have their own
|
|
19
|
+
catalogue (domain ``resource_engine``), shipped with the package; an
|
|
20
|
+
application catalogue can override them.
|
|
21
|
+
|
|
22
|
+
See docs/i18n.md.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import gettext as _gettext
|
|
28
|
+
from collections.abc import Iterator, Sequence
|
|
29
|
+
from contextlib import contextmanager
|
|
30
|
+
from contextvars import ContextVar
|
|
31
|
+
from importlib.resources import files
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
|
|
34
|
+
from resource_engine.templates import locale_candidates
|
|
35
|
+
|
|
36
|
+
ENGINE_DOMAIN = "resource_engine"
|
|
37
|
+
|
|
38
|
+
_locale: ContextVar[str | None] = ContextVar("resource_engine_locale", default=None)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def get_locale() -> str | None:
|
|
42
|
+
"""The locale of the current request or message, if any."""
|
|
43
|
+
return _locale.get()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@contextmanager
|
|
47
|
+
def use_locale(locale: str | None) -> Iterator[None]:
|
|
48
|
+
"""Run a block in ``locale`` (``None`` keeps the texts as written)."""
|
|
49
|
+
token = _locale.set(locale)
|
|
50
|
+
try:
|
|
51
|
+
yield
|
|
52
|
+
finally:
|
|
53
|
+
_locale.reset(token)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def set_locale(locale: str | None) -> None:
|
|
57
|
+
"""Set the locale for the rest of the current context (a request)."""
|
|
58
|
+
_locale.set(locale)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class Translations:
|
|
62
|
+
"""Compiled catalogues of one domain, per locale.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
directory: Holds ``<locale>/LC_MESSAGES/<domain>.mo``.
|
|
66
|
+
domain: The catalogue name (``messages``).
|
|
67
|
+
default_locale: Tried after the requested locale.
|
|
68
|
+
locales: The locales offered (for negotiation); by default the
|
|
69
|
+
folders found in ``directory``.
|
|
70
|
+
fallback: Another ``Translations`` asked when this one has no
|
|
71
|
+
translation (the engine's catalogue behind the application's).
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
def __init__(
|
|
75
|
+
self,
|
|
76
|
+
directory: str | Path,
|
|
77
|
+
*,
|
|
78
|
+
domain: str = "messages",
|
|
79
|
+
default_locale: str | None = None,
|
|
80
|
+
locales: Sequence[str] | None = None,
|
|
81
|
+
fallback: Translations | None = None,
|
|
82
|
+
) -> None:
|
|
83
|
+
self.directory = Path(str(directory))
|
|
84
|
+
self.domain = domain
|
|
85
|
+
self.default_locale = default_locale
|
|
86
|
+
self.fallback = fallback
|
|
87
|
+
found = sorted(
|
|
88
|
+
p.name
|
|
89
|
+
for p in (self.directory.iterdir() if self.directory.is_dir() else ())
|
|
90
|
+
if (p / "LC_MESSAGES" / f"{domain}.mo").is_file()
|
|
91
|
+
)
|
|
92
|
+
self.locales = list(locales) if locales is not None else found
|
|
93
|
+
self._catalogues: dict[str, _gettext.NullTranslations | None] = {}
|
|
94
|
+
|
|
95
|
+
def _catalogue(self, locale: str) -> _gettext.NullTranslations | None:
|
|
96
|
+
if locale not in self._catalogues:
|
|
97
|
+
path = self.directory / locale.replace("-", "_") / "LC_MESSAGES" / f"{self.domain}.mo"
|
|
98
|
+
if not path.is_file():
|
|
99
|
+
path = self.directory / locale / "LC_MESSAGES" / f"{self.domain}.mo"
|
|
100
|
+
catalogue = None
|
|
101
|
+
if path.is_file():
|
|
102
|
+
with path.open("rb") as handle:
|
|
103
|
+
catalogue = _gettext.GNUTranslations(handle)
|
|
104
|
+
self._catalogues[locale] = catalogue
|
|
105
|
+
return self._catalogues[locale]
|
|
106
|
+
|
|
107
|
+
def _lookup(self, key: str, locale: str | None) -> str | None:
|
|
108
|
+
for candidate in locale_candidates(locale, self.default_locale)[:-1]:
|
|
109
|
+
if candidate is None:
|
|
110
|
+
continue
|
|
111
|
+
catalogue = self._catalogue(candidate)
|
|
112
|
+
if catalogue is None:
|
|
113
|
+
continue
|
|
114
|
+
found = catalogue._catalog.get(key) # type: ignore[attr-defined]
|
|
115
|
+
if isinstance(found, str) and found:
|
|
116
|
+
return found
|
|
117
|
+
return None
|
|
118
|
+
|
|
119
|
+
def gettext(self, message: str, locale: str | None = None) -> str:
|
|
120
|
+
"""``message`` in ``locale`` (the current one by default)."""
|
|
121
|
+
locale = locale if locale is not None else get_locale()
|
|
122
|
+
found = self._lookup(message, locale)
|
|
123
|
+
if found is not None:
|
|
124
|
+
return found
|
|
125
|
+
return self.fallback.gettext(message, locale) if self.fallback else message
|
|
126
|
+
|
|
127
|
+
def pgettext(self, context: str, message: str, locale: str | None = None) -> str:
|
|
128
|
+
"""``message`` disambiguated by ``context`` (gettext's ``msgctxt``)."""
|
|
129
|
+
locale = locale if locale is not None else get_locale()
|
|
130
|
+
found = self._lookup(f"{context}\x04{message}", locale)
|
|
131
|
+
if found is not None:
|
|
132
|
+
return found
|
|
133
|
+
return self.fallback.pgettext(context, message, locale) if self.fallback else message
|
|
134
|
+
|
|
135
|
+
def ngettext(self, singular: str, plural: str, n: int, locale: str | None = None) -> str:
|
|
136
|
+
"""The singular or plural text for ``n``, in ``locale`` (the current one by default)."""
|
|
137
|
+
locale = locale if locale is not None else get_locale()
|
|
138
|
+
for candidate in locale_candidates(locale, self.default_locale)[:-1]:
|
|
139
|
+
if candidate is None:
|
|
140
|
+
continue
|
|
141
|
+
catalogue = self._catalogue(candidate)
|
|
142
|
+
if catalogue is not None and (singular, 0) in catalogue._catalog: # type: ignore[attr-defined]
|
|
143
|
+
return catalogue.ngettext(singular, plural, n)
|
|
144
|
+
if self.fallback:
|
|
145
|
+
return self.fallback.ngettext(singular, plural, n, locale)
|
|
146
|
+
return singular if n == 1 else plural
|
|
147
|
+
|
|
148
|
+
def negotiate(self, accept_language: str | None) -> str | None:
|
|
149
|
+
"""The best offered locale for an ``Accept-Language`` header."""
|
|
150
|
+
return negotiate(accept_language, self.offered())
|
|
151
|
+
|
|
152
|
+
def offered(self) -> list[str]:
|
|
153
|
+
"""The locales with a catalogue, the default first."""
|
|
154
|
+
locales = list(self.locales)
|
|
155
|
+
if self.default_locale and self.default_locale not in locales:
|
|
156
|
+
locales.insert(0, self.default_locale)
|
|
157
|
+
return locales
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def negotiate(accept_language: str | None, offered: Sequence[str]) -> str | None:
|
|
161
|
+
"""``ca-ES,ca;q=0.9,en;q=0.5`` against ``["en", "ca"]`` → ``"ca"``.
|
|
162
|
+
|
|
163
|
+
Exact matches win, then the primary language (``ca-ES`` → ``ca``, and
|
|
164
|
+
``pt`` → ``pt-BR`` when only that is offered). ``q=0`` refuses a language.
|
|
165
|
+
"""
|
|
166
|
+
if not accept_language or not offered:
|
|
167
|
+
return None
|
|
168
|
+
wanted = []
|
|
169
|
+
for position, part in enumerate(accept_language.split(",")):
|
|
170
|
+
tag, _, params = part.strip().partition(";")
|
|
171
|
+
quality = 1.0
|
|
172
|
+
for param in params.split(";"):
|
|
173
|
+
name, _, value = param.strip().partition("=")
|
|
174
|
+
if name == "q":
|
|
175
|
+
try:
|
|
176
|
+
quality = float(value)
|
|
177
|
+
except ValueError:
|
|
178
|
+
quality = 0.0
|
|
179
|
+
if tag and quality > 0:
|
|
180
|
+
wanted.append((-quality, position, tag.strip().replace("_", "-")))
|
|
181
|
+
lower = {o.lower(): o for o in offered}
|
|
182
|
+
for _, _, tag in sorted(wanted):
|
|
183
|
+
if tag == "*":
|
|
184
|
+
return offered[0]
|
|
185
|
+
if tag.lower() in lower:
|
|
186
|
+
return lower[tag.lower()]
|
|
187
|
+
primary = tag.split("-")[0].lower()
|
|
188
|
+
if primary in lower:
|
|
189
|
+
return lower[primary]
|
|
190
|
+
for option in offered:
|
|
191
|
+
if option.lower().split("-")[0] == primary:
|
|
192
|
+
return option
|
|
193
|
+
return None
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def engine_translations() -> Translations:
|
|
197
|
+
"""The engine's own catalogue (error titles), shipped with the package."""
|
|
198
|
+
return Translations(Path(str(files("resource_engine") / "locale")), domain=ENGINE_DOMAIN)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
_active: Translations = engine_translations()
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def set_translations(translations: Translations | None) -> None:
|
|
205
|
+
"""Install the application's catalogue (the engine's stays behind it)."""
|
|
206
|
+
global _active
|
|
207
|
+
engine = engine_translations()
|
|
208
|
+
if translations is None:
|
|
209
|
+
_active = engine
|
|
210
|
+
return
|
|
211
|
+
if translations.fallback is None and translations.domain != ENGINE_DOMAIN:
|
|
212
|
+
translations.fallback = engine
|
|
213
|
+
_active = translations
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def get_translations() -> Translations:
|
|
217
|
+
"""The translations of the current context."""
|
|
218
|
+
return _active
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def gettext(message: str) -> str:
|
|
222
|
+
"""``message`` in the current locale, from the installed catalogue."""
|
|
223
|
+
return _active.gettext(message)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def pgettext(context: str, message: str) -> str:
|
|
227
|
+
"""``message`` translated within ``context``, in the current translations."""
|
|
228
|
+
return _active.pgettext(context, message)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def ngettext(singular: str, plural: str, n: int) -> str:
|
|
232
|
+
"""The singular or plural form for ``n``, translated."""
|
|
233
|
+
return _active.ngettext(singular, plural, n)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
_ = gettext
|
|
237
|
+
|
|
238
|
+
__all__ = [
|
|
239
|
+
"ENGINE_DOMAIN",
|
|
240
|
+
"Translations",
|
|
241
|
+
"engine_translations",
|
|
242
|
+
"get_locale",
|
|
243
|
+
"get_translations",
|
|
244
|
+
"gettext",
|
|
245
|
+
"negotiate",
|
|
246
|
+
"ngettext",
|
|
247
|
+
"pgettext",
|
|
248
|
+
"set_locale",
|
|
249
|
+
"set_translations",
|
|
250
|
+
"use_locale",
|
|
251
|
+
]
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Authenticating a request: a token, and for sender-constrained tokens the
|
|
2
|
+
proof that the caller holds the key the token is bound to.
|
|
3
|
+
|
|
4
|
+
Entry adapters build ``Credentials`` from the request and call
|
|
5
|
+
``authenticate``. Plain ``Authenticator`` implementations see the token only;
|
|
6
|
+
a ``RequestAuthenticator`` (``resource_engine_oidc.SenderConstrained``) also
|
|
7
|
+
checks the DPoP proof or the client certificate. See docs/identity.md.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from resource_engine.errors import AuthenticationFailed
|
|
13
|
+
from resource_engine.ports.identity import Authenticator, Credentials, Principal
|
|
14
|
+
|
|
15
|
+
SCHEMES = ("bearer", "dpop")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def parse_authorization(header: str | None) -> tuple[str, str] | None:
|
|
19
|
+
"""``Authorization`` → ``(scheme, token)`` for ``Bearer`` and ``DPoP``."""
|
|
20
|
+
scheme, _, token = (header or "").partition(" ")
|
|
21
|
+
scheme, token = scheme.lower(), token.strip()
|
|
22
|
+
if scheme in SCHEMES and token:
|
|
23
|
+
return scheme, token
|
|
24
|
+
return None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
async def authenticate(authenticator: Authenticator, credentials: Credentials) -> Principal:
|
|
28
|
+
"""The caller behind ``credentials``.
|
|
29
|
+
|
|
30
|
+
A ``DPoP`` token needs an authenticator that checks proofs: with any other
|
|
31
|
+
it is refused rather than accepted as a bearer token.
|
|
32
|
+
"""
|
|
33
|
+
check = getattr(authenticator, "authenticate_request", None)
|
|
34
|
+
if check is not None:
|
|
35
|
+
principal: Principal = await check(credentials)
|
|
36
|
+
return principal
|
|
37
|
+
if credentials.scheme != "bearer":
|
|
38
|
+
raise AuthenticationFailed(
|
|
39
|
+
"DPoP tokens are not accepted here",
|
|
40
|
+
reason="unsupported_scheme",
|
|
41
|
+
hint="Wrap the authenticator in SenderConstrained to accept DPoP.",
|
|
42
|
+
)
|
|
43
|
+
return await authenticator.authenticate(credentials.token)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
__all__ = ["SCHEMES", "authenticate", "parse_authorization"]
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""The integration API: what packages built on the engine need from its
|
|
2
|
+
internals.
|
|
3
|
+
|
|
4
|
+
Interfaces (FastAPI, GraphQL, MCP), stores (SQLAlchemy, the cloud adapters) and
|
|
5
|
+
tools (devtools) serialize records, offer filters, translate permission
|
|
6
|
+
conditions and describe events the same way the engine does. Applications
|
|
7
|
+
don't need these names; packages that extend the engine import them from here,
|
|
8
|
+
never from ``resource_engine.application`` or a deeper module.
|
|
9
|
+
|
|
10
|
+
This module is public, and its names follow the compatibility rules in
|
|
11
|
+
docs/stability.md like the rest of the public API, so an adapter released
|
|
12
|
+
against one core version keeps working with that version's patch releases.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from resource_engine.application.hooks import has_external_effect
|
|
18
|
+
from resource_engine.application.manager import EXPAND_PAGE_SIZE
|
|
19
|
+
from resource_engine.application.relations import LinkDefinition, dump_read, needs_dump
|
|
20
|
+
from resource_engine.application.searching import like_pattern, operators_for
|
|
21
|
+
from resource_engine.application.timers import pending_timers
|
|
22
|
+
from resource_engine.application.views import Measure
|
|
23
|
+
from resource_engine.audit.recorder import actor_id
|
|
24
|
+
from resource_engine.authz.catalog import FIELD_KINDS
|
|
25
|
+
from resource_engine.authz.conditions import conjunction, disjunction, negation
|
|
26
|
+
from resource_engine.authz.evaluator import names_field
|
|
27
|
+
from resource_engine.documents.content import Measured
|
|
28
|
+
from resource_engine.domain.events import DomainEvent, event_doc
|
|
29
|
+
from resource_engine.logs import _trace_ids
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def trace_ids() -> tuple[str | None, str | None]:
|
|
33
|
+
"""The current trace and span ids (W3C ``traceparent``), or ``None`` for
|
|
34
|
+
each when no span is active, as log records and error reports carry them."""
|
|
35
|
+
return _trace_ids()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def engine_events() -> dict[str, type[DomainEvent]]:
|
|
39
|
+
"""The events the engine itself publishes for every application (records
|
|
40
|
+
created, updated, deleted, transitions, actions and documents), by class
|
|
41
|
+
name. Their abstract bases are left out."""
|
|
42
|
+
from resource_engine.application import events as lifecycle
|
|
43
|
+
from resource_engine.application.events import ResourceEvent
|
|
44
|
+
from resource_engine.documents import events as documents
|
|
45
|
+
from resource_engine.documents.events import DocumentEvent
|
|
46
|
+
|
|
47
|
+
found: dict[str, type[DomainEvent]] = {}
|
|
48
|
+
for module in (lifecycle, documents):
|
|
49
|
+
for value in vars(module).values():
|
|
50
|
+
if (
|
|
51
|
+
isinstance(value, type)
|
|
52
|
+
and issubclass(value, DomainEvent)
|
|
53
|
+
and value not in (DomainEvent, ResourceEvent, DocumentEvent)
|
|
54
|
+
and value.__module__ == module.__name__
|
|
55
|
+
):
|
|
56
|
+
found[value.__name__] = value
|
|
57
|
+
return found
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
__all__ = [
|
|
61
|
+
"EXPAND_PAGE_SIZE",
|
|
62
|
+
"FIELD_KINDS",
|
|
63
|
+
"LinkDefinition",
|
|
64
|
+
"Measure",
|
|
65
|
+
"Measured",
|
|
66
|
+
"actor_id",
|
|
67
|
+
"conjunction",
|
|
68
|
+
"disjunction",
|
|
69
|
+
"dump_read",
|
|
70
|
+
"engine_events",
|
|
71
|
+
"event_doc",
|
|
72
|
+
"has_external_effect",
|
|
73
|
+
"like_pattern",
|
|
74
|
+
"names_field",
|
|
75
|
+
"needs_dump",
|
|
76
|
+
"negation",
|
|
77
|
+
"operators_for",
|
|
78
|
+
"pending_timers",
|
|
79
|
+
"trace_ids",
|
|
80
|
+
]
|