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,145 @@
|
|
|
1
|
+
"""What a repository and its unit of work can do, so the engine refuses
|
|
2
|
+
queries a store can't run (a sort without an index, a deep offset) with a
|
|
3
|
+
clear error instead of a slow scan or a store error.
|
|
4
|
+
|
|
5
|
+
Repositories and units of work declare their capabilities as class (or
|
|
6
|
+
instance) attributes; missing attributes take the defaults of a SQL store:
|
|
7
|
+
|
|
8
|
+
| Attribute | On | Default | Meaning |
|
|
9
|
+
|---|---|---|---|
|
|
10
|
+
| ``supports_conditions`` | repository | ``False`` | ``list`` applies row filters |
|
|
11
|
+
| ``supports_versions`` | repository | ``False`` | compare-and-set on ``expected_version`` |
|
|
12
|
+
| ``filterable`` | repository | ``None`` (any) | fields ``list`` can filter by |
|
|
13
|
+
| ``sortable`` | repository | ``None`` (any) | fields ``list`` can sort by |
|
|
14
|
+
| ``max_offset`` | repository | ``None`` (any) | deepest offset ``list`` pages to |
|
|
15
|
+
| ``transaction_scope`` | unit of work | ``"unit_of_work"`` | what commits atomically |
|
|
16
|
+
| ``max_writes`` | unit of work | ``None`` | writes one commit can hold |
|
|
17
|
+
|
|
18
|
+
``transaction_scope`` is ``"unit_of_work"`` (everything, like SQL),
|
|
19
|
+
``"partition"`` (atomic per partition key, Cosmos DB), ``"compensated"``
|
|
20
|
+
(writes happen at once and a rollback undoes them with compensating writes:
|
|
21
|
+
others may see them before the commit, and an undone delete comes back with a
|
|
22
|
+
new id; ``CompositeStore`` with a remote store) or ``"none"`` (each write on
|
|
23
|
+
its own, remote APIs; ``transactional = False`` means the same).
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import logging
|
|
29
|
+
import typing
|
|
30
|
+
from collections.abc import Iterable
|
|
31
|
+
from dataclasses import dataclass
|
|
32
|
+
from typing import Any, Literal
|
|
33
|
+
|
|
34
|
+
from resource_engine.application.query import ListQuery
|
|
35
|
+
from resource_engine.errors import QueryNotSupported
|
|
36
|
+
|
|
37
|
+
logger = logging.getLogger(__name__)
|
|
38
|
+
|
|
39
|
+
type TransactionScope = Literal["unit_of_work", "partition", "compensated", "none"]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class Capabilities:
|
|
44
|
+
"""What a store can do: apply row conditions, keep versions, filter and sort which fields, how
|
|
45
|
+
deep it pages."""
|
|
46
|
+
|
|
47
|
+
conditions: bool = False
|
|
48
|
+
versions: bool = False
|
|
49
|
+
filterable: frozenset[str] | None = None
|
|
50
|
+
sortable: frozenset[str] | None = None
|
|
51
|
+
max_offset: int | None = None
|
|
52
|
+
transaction_scope: TransactionScope = "unit_of_work"
|
|
53
|
+
max_writes: int | None = None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _fields(value: Iterable[str] | None) -> frozenset[str] | None:
|
|
57
|
+
return None if value is None else frozenset(value)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def capabilities(repository: Any, uow: Any = None) -> Capabilities:
|
|
61
|
+
"""The declared capabilities of ``repository`` (and of its unit of work)."""
|
|
62
|
+
scope = getattr(uow, "transaction_scope", None)
|
|
63
|
+
if scope is None:
|
|
64
|
+
scope = "none" if getattr(uow, "transactional", True) is False else "unit_of_work"
|
|
65
|
+
return Capabilities(
|
|
66
|
+
conditions=bool(getattr(repository, "supports_conditions", False)),
|
|
67
|
+
versions=bool(getattr(repository, "supports_versions", False)),
|
|
68
|
+
filterable=_fields(getattr(repository, "filterable", None)),
|
|
69
|
+
sortable=_fields(getattr(repository, "sortable", None)),
|
|
70
|
+
max_offset=getattr(repository, "max_offset", None),
|
|
71
|
+
transaction_scope=typing.cast(TransactionScope, scope),
|
|
72
|
+
max_writes=getattr(uow, "max_writes", None),
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def check_query(resource: str, repository: Any, query: ListQuery) -> None:
|
|
77
|
+
"""Raise ``QueryNotSupported`` (RE-E103) when the repository can't run ``query``."""
|
|
78
|
+
caps = capabilities(repository)
|
|
79
|
+
problems: dict[str, Any] = {}
|
|
80
|
+
if caps.filterable is not None:
|
|
81
|
+
bad = sorted(f for f in query.filters if f not in caps.filterable)
|
|
82
|
+
if bad:
|
|
83
|
+
problems["filters"] = bad
|
|
84
|
+
if caps.sortable is not None:
|
|
85
|
+
bad = [o.lstrip("-") for o in query.order_by if o.lstrip("-") not in caps.sortable]
|
|
86
|
+
if bad:
|
|
87
|
+
problems["order_by"] = bad
|
|
88
|
+
if caps.max_offset is not None and query.offset > caps.max_offset:
|
|
89
|
+
problems["offset"] = query.offset
|
|
90
|
+
if not problems:
|
|
91
|
+
return
|
|
92
|
+
parts = []
|
|
93
|
+
if "filters" in problems:
|
|
94
|
+
parts.append(f"can't filter by {problems['filters']}")
|
|
95
|
+
if "order_by" in problems:
|
|
96
|
+
parts.append(f"can't sort by {problems['order_by']}")
|
|
97
|
+
if "offset" in problems:
|
|
98
|
+
parts.append(f"can't page past offset {caps.max_offset}")
|
|
99
|
+
raise QueryNotSupported(
|
|
100
|
+
f"The store of {resource!r} " + "; ".join(parts),
|
|
101
|
+
hint=(
|
|
102
|
+
f"Filterable here: {sorted(caps.filterable) if caps.filterable is not None else 'any'}"
|
|
103
|
+
f"; sortable: {sorted(caps.sortable) if caps.sortable is not None else 'any'}. "
|
|
104
|
+
"Add an index to the store, or narrow the query."
|
|
105
|
+
),
|
|
106
|
+
details={
|
|
107
|
+
**problems,
|
|
108
|
+
"filterable": sorted(caps.filterable) if caps.filterable is not None else None,
|
|
109
|
+
"sortable": sorted(caps.sortable) if caps.sortable is not None else None,
|
|
110
|
+
},
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def capability_problems(registry: Any, uow: Any) -> list[str]:
|
|
115
|
+
"""What the resources declare beyond what their repositories can do: call it
|
|
116
|
+
at startup or in a test (``assert not capability_problems(registry, uow)``)
|
|
117
|
+
with an open unit of work."""
|
|
118
|
+
problems: list[str] = []
|
|
119
|
+
for definition in registry:
|
|
120
|
+
try:
|
|
121
|
+
repository = uow.repository(definition.name)
|
|
122
|
+
except Exception as exc: # not served by this unit of work: nothing to compare
|
|
123
|
+
logger.debug("capabilities: no repository for %s (%s)", definition.name, exc)
|
|
124
|
+
continue
|
|
125
|
+
caps = capabilities(repository, uow)
|
|
126
|
+
if caps.filterable is not None:
|
|
127
|
+
extra = sorted(set(definition.filterable) - caps.filterable)
|
|
128
|
+
if extra:
|
|
129
|
+
problems.append(f"{definition.name}: filterable {extra} not indexed by the store")
|
|
130
|
+
if caps.sortable is not None:
|
|
131
|
+
extra = sorted(set(definition.sortable) - caps.sortable)
|
|
132
|
+
if extra:
|
|
133
|
+
problems.append(f"{definition.name}: sortable {extra} not indexed by the store")
|
|
134
|
+
if getattr(definition, "version_field", None) and not caps.versions:
|
|
135
|
+
problems.append(f"{definition.name}: versioned, but the store can't compare versions")
|
|
136
|
+
return problems
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
__all__ = [
|
|
140
|
+
"Capabilities",
|
|
141
|
+
"TransactionScope",
|
|
142
|
+
"capabilities",
|
|
143
|
+
"capability_problems",
|
|
144
|
+
"check_query",
|
|
145
|
+
]
|
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
"""One operation across several stores: SQL resources and remote ones (REST,
|
|
2
|
+
SOAP, OData) or query-engine views, with compensations for remote writes.
|
|
3
|
+
|
|
4
|
+
```python
|
|
5
|
+
from resource_engine.composite import CompositeStore
|
|
6
|
+
|
|
7
|
+
store = CompositeStore(
|
|
8
|
+
sql_uow, # the primary store: outbox, inbox...
|
|
9
|
+
{"partners": erp_uow, "daily_sales": lake.unit_of_work},
|
|
10
|
+
compensations={"erp_orders": {"add": cancel_order}},
|
|
11
|
+
)
|
|
12
|
+
manager = ResourceManager(registry, store.unit_of_work)
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
- **Routing:** each resource goes to the store that holds it; everything
|
|
16
|
+
else, and the outbox, inbox and idempotency records, to the primary store.
|
|
17
|
+
Resources sharing a factory share one unit of work per operation.
|
|
18
|
+
- **Remote writes** happen when they are made: a remote system can't take
|
|
19
|
+
part in the database transaction. Each one records its compensation, the
|
|
20
|
+
write that undoes it (a create is undone by a delete, an update by the
|
|
21
|
+
record as it was, a delete by creating it again). If the operation fails,
|
|
22
|
+
or the primary commit fails after them, the compensations run in reverse
|
|
23
|
+
order.
|
|
24
|
+
- **Compensations are best effort:** a failing one is logged and reported
|
|
25
|
+
(``ErrorReporter``) and the others still run. When "delete" isn't the right
|
|
26
|
+
inverse for a remote API (an order must be cancelled, not deleted), give
|
|
27
|
+
your own per resource and write kind.
|
|
28
|
+
- Transactional stores (``transactional`` not ``False``) commit and roll back
|
|
29
|
+
normally; read-only ones (query engines) just serve reads.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
import copy
|
|
35
|
+
import inspect
|
|
36
|
+
import logging
|
|
37
|
+
from collections.abc import Awaitable, Callable, Mapping
|
|
38
|
+
from dataclasses import dataclass
|
|
39
|
+
from typing import Any, override
|
|
40
|
+
|
|
41
|
+
from resource_engine.application.query import ListQuery, Page
|
|
42
|
+
from resource_engine.ports.repository import Repository
|
|
43
|
+
from resource_engine.ports.unit_of_work import UnitOfWork
|
|
44
|
+
|
|
45
|
+
log = logging.getLogger("resource_engine.composite")
|
|
46
|
+
|
|
47
|
+
type Compensation = Callable[..., Awaitable[None] | None]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass
|
|
51
|
+
class _Undo:
|
|
52
|
+
resource: str
|
|
53
|
+
kind: str
|
|
54
|
+
repository: Any
|
|
55
|
+
before: Any
|
|
56
|
+
after: Any
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class CompensatingRepository(Repository[Any]):
|
|
60
|
+
"""Wraps a non-transactional repository: every write records how to undo it."""
|
|
61
|
+
|
|
62
|
+
def __init__(
|
|
63
|
+
self,
|
|
64
|
+
inner: Any,
|
|
65
|
+
resource: str,
|
|
66
|
+
log_: list[_Undo],
|
|
67
|
+
*,
|
|
68
|
+
id_field: str = "id",
|
|
69
|
+
) -> None:
|
|
70
|
+
self.inner = inner
|
|
71
|
+
self.resource = resource
|
|
72
|
+
self.undo_log = log_
|
|
73
|
+
self.id_field = id_field
|
|
74
|
+
# what the wrapped store can do (resource_engine.capabilities)
|
|
75
|
+
self.supports_conditions = getattr(inner, "supports_conditions", False)
|
|
76
|
+
self.supports_versions = getattr(inner, "supports_versions", False)
|
|
77
|
+
self.filterable = getattr(inner, "filterable", None)
|
|
78
|
+
self.sortable = getattr(inner, "sortable", None)
|
|
79
|
+
self.max_offset = getattr(inner, "max_offset", None)
|
|
80
|
+
|
|
81
|
+
@override
|
|
82
|
+
async def get(self, entity_id: Any) -> Any:
|
|
83
|
+
return await self.inner.get(entity_id)
|
|
84
|
+
|
|
85
|
+
@override
|
|
86
|
+
async def list(self, query: ListQuery) -> Page[Any]:
|
|
87
|
+
page: Page[Any] = await self.inner.list(query)
|
|
88
|
+
return page
|
|
89
|
+
|
|
90
|
+
@override
|
|
91
|
+
async def add(self, entity: Any) -> Any:
|
|
92
|
+
stored = await self.inner.add(entity)
|
|
93
|
+
self.undo_log.append(_Undo(self.resource, "add", self.inner, None, copy.copy(stored)))
|
|
94
|
+
return stored
|
|
95
|
+
|
|
96
|
+
@override
|
|
97
|
+
async def update(self, entity: Any, **kw: Any) -> Any:
|
|
98
|
+
before = await self.inner.get(getattr(entity, self.id_field))
|
|
99
|
+
stored = await self.inner.update(entity, **kw)
|
|
100
|
+
self.undo_log.append(
|
|
101
|
+
_Undo(self.resource, "update", self.inner, copy.copy(before), copy.copy(stored))
|
|
102
|
+
)
|
|
103
|
+
return stored
|
|
104
|
+
|
|
105
|
+
@override
|
|
106
|
+
async def delete(self, entity: Any, **kw: Any) -> None:
|
|
107
|
+
before = copy.copy(entity)
|
|
108
|
+
await self.inner.delete(entity, **kw)
|
|
109
|
+
self.undo_log.append(_Undo(self.resource, "delete", self.inner, before, None))
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class CompositeUnitOfWork(UnitOfWork):
|
|
113
|
+
"""Routes repositories to their stores and coordinates commit and rollback."""
|
|
114
|
+
|
|
115
|
+
def __init__(
|
|
116
|
+
self,
|
|
117
|
+
primary: Callable[[], Any],
|
|
118
|
+
stores: Mapping[str, Callable[[], Any]],
|
|
119
|
+
compensations: Mapping[str, Mapping[str, Compensation]],
|
|
120
|
+
id_fields: Mapping[str, str],
|
|
121
|
+
) -> None:
|
|
122
|
+
self._primary_factory = primary
|
|
123
|
+
self._stores = stores
|
|
124
|
+
self._compensations = compensations
|
|
125
|
+
self._id_fields = id_fields
|
|
126
|
+
self.primary: Any = None
|
|
127
|
+
self._opened: dict[int, Any] = {} # by factory id: one unit of work per store
|
|
128
|
+
self._wrapped: dict[str, Any] = {}
|
|
129
|
+
self._undo: list[_Undo] = []
|
|
130
|
+
self._committed = False
|
|
131
|
+
|
|
132
|
+
async def __aenter__(self) -> CompositeUnitOfWork:
|
|
133
|
+
self.primary = self._primary_factory()
|
|
134
|
+
await self.primary.__aenter__()
|
|
135
|
+
return self
|
|
136
|
+
|
|
137
|
+
async def _open(self, factory: Callable[[], Any]) -> Any:
|
|
138
|
+
key = id(factory)
|
|
139
|
+
if key not in self._opened:
|
|
140
|
+
uow = factory()
|
|
141
|
+
await uow.__aenter__()
|
|
142
|
+
self._opened[key] = uow
|
|
143
|
+
return self._opened[key]
|
|
144
|
+
|
|
145
|
+
@override
|
|
146
|
+
def repository(self, resource_name: str) -> Any:
|
|
147
|
+
if resource_name not in self._stores:
|
|
148
|
+
return self.primary.repository(resource_name)
|
|
149
|
+
if resource_name in self._wrapped:
|
|
150
|
+
return self._wrapped[resource_name]
|
|
151
|
+
raise RuntimeError( # pragma: no cover - opened by ``prepare``
|
|
152
|
+
f"The store of {resource_name!r} isn't open"
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
async def prepare(self, resource_name: str) -> None:
|
|
156
|
+
"""Open the store of ``resource_name`` (the manager calls ``repository``
|
|
157
|
+
synchronously, so stores are opened up front by ``unit_of_work``)."""
|
|
158
|
+
factory = self._stores[resource_name]
|
|
159
|
+
uow = await self._open(factory)
|
|
160
|
+
inner = uow.repository(resource_name)
|
|
161
|
+
if getattr(uow, "transactional", True) is False:
|
|
162
|
+
inner = CompensatingRepository(
|
|
163
|
+
inner, resource_name, self._undo, id_field=self._id_fields.get(resource_name, "id")
|
|
164
|
+
)
|
|
165
|
+
self._wrapped[resource_name] = inner
|
|
166
|
+
|
|
167
|
+
@property
|
|
168
|
+
def transaction_scope(self) -> str:
|
|
169
|
+
"""``"compensated"`` when a store can't roll back (its writes are undone
|
|
170
|
+
by compensations), else the primary's (``resource_engine.capabilities``)."""
|
|
171
|
+
if any(getattr(u, "transactional", True) is False for u in self._opened.values()):
|
|
172
|
+
return "compensated"
|
|
173
|
+
return getattr(self.primary, "transaction_scope", "unit_of_work")
|
|
174
|
+
|
|
175
|
+
def __getattr__(self, name: str) -> Any:
|
|
176
|
+
# outbox(), inbox(), idempotency()...: the primary store's
|
|
177
|
+
if name.startswith("_") or self.primary is None:
|
|
178
|
+
raise AttributeError(name)
|
|
179
|
+
return getattr(self.primary, name)
|
|
180
|
+
|
|
181
|
+
@override
|
|
182
|
+
async def commit(self) -> None:
|
|
183
|
+
try:
|
|
184
|
+
for uow in self._opened.values():
|
|
185
|
+
if getattr(uow, "transactional", True) is not False:
|
|
186
|
+
await uow.commit()
|
|
187
|
+
await self.primary.commit()
|
|
188
|
+
except BaseException:
|
|
189
|
+
await self._compensate()
|
|
190
|
+
raise
|
|
191
|
+
self._committed = True
|
|
192
|
+
self._undo.clear()
|
|
193
|
+
|
|
194
|
+
@override
|
|
195
|
+
async def rollback(self) -> None:
|
|
196
|
+
await self.primary.rollback()
|
|
197
|
+
for uow in self._opened.values():
|
|
198
|
+
await uow.rollback()
|
|
199
|
+
await self._compensate()
|
|
200
|
+
|
|
201
|
+
async def _compensate(self) -> None:
|
|
202
|
+
while self._undo:
|
|
203
|
+
undo = self._undo.pop()
|
|
204
|
+
custom = self._compensations.get(undo.resource, {}).get(undo.kind)
|
|
205
|
+
try:
|
|
206
|
+
if custom is not None:
|
|
207
|
+
result = custom(undo.repository, undo.before, undo.after)
|
|
208
|
+
if inspect.isawaitable(result):
|
|
209
|
+
await result
|
|
210
|
+
elif undo.kind == "add":
|
|
211
|
+
await undo.repository.delete(undo.after)
|
|
212
|
+
elif undo.kind == "update" and undo.before is not None:
|
|
213
|
+
await undo.repository.update(undo.before)
|
|
214
|
+
elif undo.kind == "delete":
|
|
215
|
+
await undo.repository.add(undo.before)
|
|
216
|
+
except Exception as exc:
|
|
217
|
+
log.exception("Compensation of %s %s failed", undo.kind, undo.resource)
|
|
218
|
+
from resource_engine.reporting import report_error
|
|
219
|
+
|
|
220
|
+
await report_error(
|
|
221
|
+
exc,
|
|
222
|
+
where="composite.compensation",
|
|
223
|
+
force=True,
|
|
224
|
+
resource=undo.resource,
|
|
225
|
+
write=undo.kind,
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
|
|
229
|
+
try:
|
|
230
|
+
if not self._committed:
|
|
231
|
+
await self.rollback()
|
|
232
|
+
finally:
|
|
233
|
+
for uow in self._opened.values():
|
|
234
|
+
await uow.__aexit__(exc_type, exc, tb)
|
|
235
|
+
await self.primary.__aexit__(exc_type, exc, tb)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
class _Opening:
|
|
239
|
+
"""Async context manager that opens the composite and its stores."""
|
|
240
|
+
|
|
241
|
+
def __init__(self, uow: CompositeUnitOfWork, resources: list[str]) -> None:
|
|
242
|
+
self.uow = uow
|
|
243
|
+
self.resources = resources
|
|
244
|
+
|
|
245
|
+
async def __aenter__(self) -> CompositeUnitOfWork:
|
|
246
|
+
await self.uow.__aenter__()
|
|
247
|
+
try:
|
|
248
|
+
for name in self.resources:
|
|
249
|
+
await self.uow.prepare(name)
|
|
250
|
+
except BaseException as exc:
|
|
251
|
+
await self.uow.__aexit__(type(exc), exc, exc.__traceback__)
|
|
252
|
+
raise
|
|
253
|
+
return self.uow
|
|
254
|
+
|
|
255
|
+
async def __aexit__(self, *exc: Any) -> None:
|
|
256
|
+
await self.uow.__aexit__(*exc)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
class CompositeStore:
|
|
260
|
+
"""Units of work spanning a primary store and others, by resource.
|
|
261
|
+
|
|
262
|
+
Args:
|
|
263
|
+
primary: The primary store's unit-of-work factory (SQL): resources not
|
|
264
|
+
listed in ``stores``, and the outbox, inbox and idempotency records.
|
|
265
|
+
stores: Resource name → the unit-of-work factory that holds it.
|
|
266
|
+
compensations: Resource name → ``{"add"|"update"|"delete": fn}``, each
|
|
267
|
+
``fn(repository, before, after)`` undoing that write instead of
|
|
268
|
+
the default inverse.
|
|
269
|
+
registry: To read each resource's id field (default ``id``).
|
|
270
|
+
"""
|
|
271
|
+
|
|
272
|
+
def __init__(
|
|
273
|
+
self,
|
|
274
|
+
primary: Callable[[], Any],
|
|
275
|
+
stores: Mapping[str, Callable[[], Any]],
|
|
276
|
+
*,
|
|
277
|
+
compensations: Mapping[str, Mapping[str, Compensation]] | None = None,
|
|
278
|
+
registry: Any = None,
|
|
279
|
+
) -> None:
|
|
280
|
+
self.primary = primary
|
|
281
|
+
self.stores = dict(stores)
|
|
282
|
+
self.compensations = dict(compensations or {})
|
|
283
|
+
self.id_fields = (
|
|
284
|
+
{name: registry.get(name).id_field for name in self.stores if name in registry}
|
|
285
|
+
if registry is not None
|
|
286
|
+
else {}
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
def unit_of_work(self) -> _Opening:
|
|
290
|
+
"""A unit of work over the primary store and the others."""
|
|
291
|
+
uow = CompositeUnitOfWork(self.primary, self.stores, self.compensations, self.id_fields)
|
|
292
|
+
return _Opening(uow, list(self.stores))
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
__all__ = ["CompensatingRepository", "CompositeStore", "CompositeUnitOfWork"]
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Documents attached to resources: slots, uploads, processing and clean-up.
|
|
2
|
+
|
|
3
|
+
See docs/documents.md.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from resource_engine.application.slots import DocumentSlot
|
|
7
|
+
from resource_engine.documents.events import (
|
|
8
|
+
DocumentAttached,
|
|
9
|
+
DocumentDetached,
|
|
10
|
+
DocumentEvent,
|
|
11
|
+
DocumentProcessed,
|
|
12
|
+
DocumentRejected,
|
|
13
|
+
)
|
|
14
|
+
from resource_engine.documents.janitor import DocumentJanitor, JanitorStats
|
|
15
|
+
from resource_engine.documents.machine import DocumentStateMachine
|
|
16
|
+
from resource_engine.documents.manager import (
|
|
17
|
+
ContextDocuments,
|
|
18
|
+
DocumentManager,
|
|
19
|
+
UploadTicket,
|
|
20
|
+
)
|
|
21
|
+
from resource_engine.documents.model import (
|
|
22
|
+
Document,
|
|
23
|
+
DocumentRead,
|
|
24
|
+
NewDocument,
|
|
25
|
+
content_disposition,
|
|
26
|
+
safe_filename,
|
|
27
|
+
)
|
|
28
|
+
from resource_engine.documents.pipeline import (
|
|
29
|
+
DocumentPipeline,
|
|
30
|
+
DocumentProcessor,
|
|
31
|
+
ProcessingResult,
|
|
32
|
+
)
|
|
33
|
+
from resource_engine.documents.processors import (
|
|
34
|
+
BuiltinTextExtractor,
|
|
35
|
+
ContentTypeCheck,
|
|
36
|
+
ExtractedText,
|
|
37
|
+
TextExtraction,
|
|
38
|
+
TextExtractor,
|
|
39
|
+
)
|
|
40
|
+
from resource_engine.documents.resource import DocumentResource
|
|
41
|
+
|
|
42
|
+
__all__ = [
|
|
43
|
+
"BuiltinTextExtractor",
|
|
44
|
+
"ContentTypeCheck",
|
|
45
|
+
"ContextDocuments",
|
|
46
|
+
"Document",
|
|
47
|
+
"DocumentAttached",
|
|
48
|
+
"DocumentDetached",
|
|
49
|
+
"DocumentEvent",
|
|
50
|
+
"DocumentJanitor",
|
|
51
|
+
"DocumentManager",
|
|
52
|
+
"DocumentPipeline",
|
|
53
|
+
"DocumentProcessed",
|
|
54
|
+
"DocumentProcessor",
|
|
55
|
+
"DocumentRead",
|
|
56
|
+
"DocumentRejected",
|
|
57
|
+
"DocumentResource",
|
|
58
|
+
"DocumentSlot",
|
|
59
|
+
"DocumentStateMachine",
|
|
60
|
+
"ExtractedText",
|
|
61
|
+
"JanitorStats",
|
|
62
|
+
"NewDocument",
|
|
63
|
+
"ProcessingResult",
|
|
64
|
+
"TextExtraction",
|
|
65
|
+
"TextExtractor",
|
|
66
|
+
"UploadTicket",
|
|
67
|
+
"content_disposition",
|
|
68
|
+
"safe_filename",
|
|
69
|
+
]
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Streaming helpers shared by blob store adapters."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
from collections.abc import AsyncIterable, AsyncIterator
|
|
7
|
+
|
|
8
|
+
from resource_engine.errors import DocumentTooLarge
|
|
9
|
+
from resource_engine.ports.storage import Content
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
async def iter_chunks(content: Content, chunk_size: int = 1024 * 1024) -> AsyncIterator[bytes]:
|
|
13
|
+
"""Content as chunks of at most ``chunk_size`` bytes, whether it came as bytes or as a
|
|
14
|
+
stream."""
|
|
15
|
+
if isinstance(content, bytes | bytearray | memoryview):
|
|
16
|
+
data = bytes(content)
|
|
17
|
+
for start in range(0, len(data), chunk_size):
|
|
18
|
+
yield data[start : start + chunk_size]
|
|
19
|
+
return
|
|
20
|
+
async for chunk in content:
|
|
21
|
+
if chunk:
|
|
22
|
+
yield bytes(chunk)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Measured:
|
|
26
|
+
"""Wraps content, counting bytes and hashing them while it is streamed.
|
|
27
|
+
|
|
28
|
+
Iterating raises ``DocumentTooLarge`` as soon as ``max_bytes`` is exceeded, so
|
|
29
|
+
adapters can abort the upload without reading the rest.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __init__(self, content: Content, *, max_bytes: int | None = None) -> None:
|
|
33
|
+
self._content = content
|
|
34
|
+
self.max_bytes = max_bytes
|
|
35
|
+
self.size = 0
|
|
36
|
+
self._hash = hashlib.sha256()
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def sha256(self) -> str:
|
|
40
|
+
"""The hex sha256 of the bytes streamed so far."""
|
|
41
|
+
return self._hash.hexdigest()
|
|
42
|
+
|
|
43
|
+
async def __aiter__(self) -> AsyncIterator[bytes]:
|
|
44
|
+
async for chunk in iter_chunks(self._content):
|
|
45
|
+
self.size += len(chunk)
|
|
46
|
+
if self.max_bytes is not None and self.size > self.max_bytes:
|
|
47
|
+
raise DocumentTooLarge(
|
|
48
|
+
f"Content exceeds the limit of {self.max_bytes} bytes",
|
|
49
|
+
details={"max_bytes": self.max_bytes},
|
|
50
|
+
)
|
|
51
|
+
self._hash.update(chunk)
|
|
52
|
+
yield chunk
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
async def read_all(stream: AsyncIterable[bytes]) -> bytes:
|
|
56
|
+
"""A whole stream, as bytes."""
|
|
57
|
+
return b"".join([chunk async for chunk in stream])
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Events recorded by document operations.
|
|
2
|
+
|
|
3
|
+
``resource``/``entity_id`` are the *owner's*, so the envelope key keeps all events
|
|
4
|
+
of an entity (its own and its documents') in order.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
|
|
11
|
+
from resource_engine.application.events import ResourceEvent
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True, kw_only=True)
|
|
15
|
+
class DocumentEvent(ResourceEvent):
|
|
16
|
+
"""Base of the events about a record's documents."""
|
|
17
|
+
|
|
18
|
+
document_id: str
|
|
19
|
+
slot: str
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True, kw_only=True)
|
|
23
|
+
class DocumentAttached(DocumentEvent):
|
|
24
|
+
"""Content is stored. ``processing`` tells the pipeline to pick it up."""
|
|
25
|
+
|
|
26
|
+
content_type: str
|
|
27
|
+
size: int | None
|
|
28
|
+
processing: bool
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True, kw_only=True)
|
|
32
|
+
class DocumentDetached(DocumentEvent):
|
|
33
|
+
"""A document was removed from a record."""
|
|
34
|
+
|
|
35
|
+
pass
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True, kw_only=True)
|
|
39
|
+
class DocumentProcessed(DocumentEvent):
|
|
40
|
+
"""A document passed every processor and can be downloaded."""
|
|
41
|
+
|
|
42
|
+
pass
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True, kw_only=True)
|
|
46
|
+
class DocumentRejected(DocumentEvent):
|
|
47
|
+
"""A processor refused a document; ``error`` says why."""
|
|
48
|
+
|
|
49
|
+
error: str
|