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,76 @@
|
|
|
1
|
+
"""Decoding inbound message bodies into envelopes (transport-neutral).
|
|
2
|
+
|
|
3
|
+
Accepted formats, detected automatically:
|
|
4
|
+
|
|
5
|
+
- the envelope JSON written by the engine's publishers;
|
|
6
|
+
- CloudEvents 1.0 in structured mode (``application/cloudevents+json`` or any JSON
|
|
7
|
+
object with ``specversion``);
|
|
8
|
+
- CloudEvents 1.0 in binary mode (``ce-*`` HTTP headers, JSON ``data`` as the body).
|
|
9
|
+
|
|
10
|
+
Broker adapters unwrap their own framing (SNS notifications, Pub/Sub push) first.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
from collections.abc import Callable, Mapping
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from resource_engine.errors import UndecodableMessage
|
|
20
|
+
from resource_engine.messaging.cloudevents import from_cloudevent
|
|
21
|
+
from resource_engine.messaging.envelope import EventEnvelope
|
|
22
|
+
from resource_engine.ports.messaging import ReceivedMessage
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def envelope_from_json(data: Any, *, type_prefix: str = "") -> EventEnvelope:
|
|
26
|
+
"""Envelope from a decoded JSON object (envelope or structured CloudEvent)."""
|
|
27
|
+
if not isinstance(data, Mapping):
|
|
28
|
+
raise UndecodableMessage(f"Expected a JSON object, got {type(data).__name__}")
|
|
29
|
+
try:
|
|
30
|
+
if "specversion" in data:
|
|
31
|
+
return from_cloudevent(data, type_prefix=type_prefix)
|
|
32
|
+
return EventEnvelope.from_dict(data)
|
|
33
|
+
except (KeyError, TypeError, ValueError) as exc:
|
|
34
|
+
raise UndecodableMessage(
|
|
35
|
+
f"Not an event envelope or CloudEvent: {type(exc).__name__}: {exc}",
|
|
36
|
+
hint="Producers must send the envelope JSON or a CloudEvents 1.0 event.",
|
|
37
|
+
) from exc
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def decode_body(body: str | bytes, *, type_prefix: str = "") -> EventEnvelope:
|
|
41
|
+
"""Envelope from a JSON body. Raises ``UndecodableMessage`` (RE-E405)."""
|
|
42
|
+
try:
|
|
43
|
+
data = json.loads(body)
|
|
44
|
+
except (ValueError, UnicodeDecodeError) as exc:
|
|
45
|
+
raise UndecodableMessage(f"Body is not JSON: {exc}") from exc
|
|
46
|
+
return envelope_from_json(data, type_prefix=type_prefix)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def decode_http(headers: Mapping[str, str], body: bytes, *, type_prefix: str = "") -> EventEnvelope:
|
|
50
|
+
"""Envelope from an HTTP request (headers are matched case-insensitively)."""
|
|
51
|
+
lower = {k.lower(): v for k, v in headers.items()}
|
|
52
|
+
if "ce-id" in lower and "ce-specversion" in lower: # CloudEvents binary mode
|
|
53
|
+
event: dict[str, Any] = {k[3:]: v for k, v in lower.items() if k.startswith("ce-")}
|
|
54
|
+
try:
|
|
55
|
+
event["data"] = json.loads(body) if body else {}
|
|
56
|
+
except ValueError as exc:
|
|
57
|
+
raise UndecodableMessage(f"CloudEvent data is not JSON: {exc}") from exc
|
|
58
|
+
return envelope_from_json(event, type_prefix=type_prefix)
|
|
59
|
+
return decode_body(body, type_prefix=type_prefix)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def try_decode(
|
|
63
|
+
decode: Callable[[], EventEnvelope],
|
|
64
|
+
*,
|
|
65
|
+
handle: Any = None,
|
|
66
|
+
delivery_count: int | None = None,
|
|
67
|
+
message_id: str | None = None,
|
|
68
|
+
) -> ReceivedMessage:
|
|
69
|
+
"""Run ``decode`` and wrap the result; decode errors become a poison message
|
|
70
|
+
(``envelope=None``) that the processor dead-letters instead of crashing the loop.
|
|
71
|
+
"""
|
|
72
|
+
try:
|
|
73
|
+
envelope = decode()
|
|
74
|
+
except UndecodableMessage as exc:
|
|
75
|
+
return ReceivedMessage(None, handle, delivery_count, exc.message, message_id)
|
|
76
|
+
return ReceivedMessage(envelope, handle, delivery_count, None, message_id or envelope.id)
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""What operators ask when an event didn't arrive (the explorer's outbox and
|
|
2
|
+
dead letters, docs/explorer.md#outbox-and-dead-letters):
|
|
3
|
+
|
|
4
|
+
- **The outbox:** messages not sent yet, with their attempts and last error
|
|
5
|
+
(the relay keeps retrying them). It needs an ``InspectableOutbox``.
|
|
6
|
+
- **Dead letters:** messages a consumer gave up on, from the ``ActivityLog``
|
|
7
|
+
(``ActivityMessageObserver`` records each consumer's outcome), and whether
|
|
8
|
+
the outbox still holds them.
|
|
9
|
+
- **Send again:** the outbox record goes back to the queue and the relay
|
|
10
|
+
publishes it again. Consumers that already handled it skip it (their
|
|
11
|
+
inbox), so only the ones that failed run it again.
|
|
12
|
+
|
|
13
|
+
Seeing needs ``events:read``; sending again ``events:redrive``, audited.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
from resource_engine.errors import ConfigurationError, EntityNotFound
|
|
22
|
+
from resource_engine.explorer import EVENTS_READ, EVENTS_REDRIVE, require
|
|
23
|
+
from resource_engine.ports.messaging import InspectableOutbox, OutboxRecord
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class DeadLetter:
|
|
28
|
+
"""A message a consumer gave up on."""
|
|
29
|
+
|
|
30
|
+
message_id: str
|
|
31
|
+
event_type: str
|
|
32
|
+
consumer: str
|
|
33
|
+
error: str | None
|
|
34
|
+
at: Any
|
|
35
|
+
in_outbox: bool # it can be sent again
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class MessagingInspector:
|
|
39
|
+
"""The outbox and the dead letters, for operators.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
manager: The ``ResourceManager`` (its units of work, authorizer, audit).
|
|
43
|
+
activity: The ``ActivityLog`` the consumers report to (dead letters).
|
|
44
|
+
open: Without an authorizer, allow it anyway (local development only).
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
def __init__(self, manager: Any, activity: Any = None, *, open: bool = False) -> None:
|
|
48
|
+
self.manager = manager
|
|
49
|
+
self.activity = activity
|
|
50
|
+
self.open = open
|
|
51
|
+
|
|
52
|
+
def _outbox(self, uow: Any) -> InspectableOutbox:
|
|
53
|
+
outbox = uow.outbox() if hasattr(uow, "outbox") else None
|
|
54
|
+
if not isinstance(outbox, InspectableOutbox):
|
|
55
|
+
raise ConfigurationError(
|
|
56
|
+
"This unit of work's outbox can't be inspected",
|
|
57
|
+
hint="Use the SQLAlchemy or in-memory outbox (InspectableOutbox).",
|
|
58
|
+
doc="docs/explorer.md#outbox-and-dead-letters",
|
|
59
|
+
)
|
|
60
|
+
return outbox
|
|
61
|
+
|
|
62
|
+
async def outbox(self, *, actor: Any = None, limit: int = 50) -> list[OutboxRecord]:
|
|
63
|
+
"""Messages not sent yet, oldest first."""
|
|
64
|
+
await require(self.manager, actor, EVENTS_READ.name, open=self.open)
|
|
65
|
+
async with self.manager.uow_factory() as uow:
|
|
66
|
+
return await self._outbox(uow).unpublished(limit)
|
|
67
|
+
|
|
68
|
+
async def dead_letters(self, *, actor: Any = None, limit: int = 50) -> list[DeadLetter]:
|
|
69
|
+
"""Messages consumers gave up on, newest first."""
|
|
70
|
+
await require(self.manager, actor, EVENTS_READ.name, open=self.open)
|
|
71
|
+
if self.activity is None:
|
|
72
|
+
return []
|
|
73
|
+
records = await self.activity.dead_letters(limit)
|
|
74
|
+
out = []
|
|
75
|
+
async with self.manager.uow_factory() as uow:
|
|
76
|
+
outbox = self._outbox(uow)
|
|
77
|
+
for record in records:
|
|
78
|
+
kept = await outbox.get(record.message_id)
|
|
79
|
+
out.append(
|
|
80
|
+
DeadLetter(
|
|
81
|
+
record.message_id,
|
|
82
|
+
record.event_type,
|
|
83
|
+
record.consumer,
|
|
84
|
+
record.error,
|
|
85
|
+
record.at,
|
|
86
|
+
kept is not None,
|
|
87
|
+
)
|
|
88
|
+
)
|
|
89
|
+
return out
|
|
90
|
+
|
|
91
|
+
async def send_again(self, message_id: str, *, actor: Any = None) -> OutboxRecord:
|
|
92
|
+
"""Put an outbox message back in the queue (audited)."""
|
|
93
|
+
await require(self.manager, actor, EVENTS_REDRIVE.name, open=self.open)
|
|
94
|
+
async with self.manager.transaction() as tx:
|
|
95
|
+
outbox = self._outbox(tx.uow)
|
|
96
|
+
record = await outbox.get(message_id)
|
|
97
|
+
if record is None:
|
|
98
|
+
raise EntityNotFound(
|
|
99
|
+
f"The outbox has no message {message_id!r}",
|
|
100
|
+
hint="Published messages are deleted after their retention "
|
|
101
|
+
"(MessagingJanitor); a message from a broker can only be redriven there.",
|
|
102
|
+
)
|
|
103
|
+
await outbox.requeue([message_id])
|
|
104
|
+
await self.manager.audit_event(
|
|
105
|
+
actor,
|
|
106
|
+
EVENTS_REDRIVE.name,
|
|
107
|
+
details={"message": message_id, "event": record.envelope.type},
|
|
108
|
+
uow=tx.uow,
|
|
109
|
+
)
|
|
110
|
+
return record
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
__all__ = ["DeadLetter", "MessagingInspector"]
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""Retention for the messaging tables: inbox marks and published outbox records
|
|
2
|
+
grow with every message. Run ``MessagingJanitor.run_once()`` periodically (cron,
|
|
3
|
+
worker loop), or ``run_forever`` next to the relay.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
import contextlib
|
|
10
|
+
import logging
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from datetime import UTC, datetime, timedelta
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from resource_engine.errors import ConfigurationError
|
|
17
|
+
from resource_engine.ports.messaging import SupportsInbox, SupportsOutbox
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger("resource_engine.messaging.janitor")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class MessagingJanitorStats:
|
|
24
|
+
"""How many inbox, outbox and activity records one janitor run deleted."""
|
|
25
|
+
|
|
26
|
+
inbox: int = 0
|
|
27
|
+
outbox: int = 0
|
|
28
|
+
activity: int = 0
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class MessagingJanitor:
|
|
32
|
+
"""Deletes inbox marks and published outbox records past their retention.
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
uow_factory: Units of work with ``inbox()`` and/or ``outbox()``.
|
|
36
|
+
inbox_retention: How long a consumer keeps the ids it processed. Must
|
|
37
|
+
exceed the broker's longest redelivery window (message retention,
|
|
38
|
+
dead-letter redrive): a message redelivered after its mark is gone
|
|
39
|
+
runs again. ``None`` keeps the inbox untouched.
|
|
40
|
+
outbox_retention: How long published records stay (for inspection and
|
|
41
|
+
replays). Unpublished records are never deleted. ``None`` keeps them.
|
|
42
|
+
activity / activity_retention: An ``ActivityLog`` and how long its
|
|
43
|
+
records stay.
|
|
44
|
+
batch_size: Rows deleted per transaction; ``run_once`` repeats until a
|
|
45
|
+
batch comes back short.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
def __init__(
|
|
49
|
+
self,
|
|
50
|
+
uow_factory: Callable[[], Any],
|
|
51
|
+
*,
|
|
52
|
+
inbox_retention: timedelta | None = timedelta(days=14),
|
|
53
|
+
outbox_retention: timedelta | None = timedelta(days=7),
|
|
54
|
+
batch_size: int = 1000,
|
|
55
|
+
activity: Any = None,
|
|
56
|
+
activity_retention: timedelta = timedelta(days=7),
|
|
57
|
+
) -> None:
|
|
58
|
+
if batch_size < 1:
|
|
59
|
+
raise ConfigurationError("batch_size must be at least 1")
|
|
60
|
+
for name, value in (("inbox", inbox_retention), ("outbox", outbox_retention)):
|
|
61
|
+
if value is not None and value <= timedelta(0):
|
|
62
|
+
raise ConfigurationError(f"{name}_retention must be positive or None")
|
|
63
|
+
self.uow_factory = uow_factory
|
|
64
|
+
self.inbox_retention = inbox_retention
|
|
65
|
+
self.outbox_retention = outbox_retention
|
|
66
|
+
self.batch_size = batch_size
|
|
67
|
+
#: An ``ActivityLog`` purged after ``activity_retention`` (docs/explorer.md).
|
|
68
|
+
self.activity = activity
|
|
69
|
+
self.activity_retention = activity_retention
|
|
70
|
+
|
|
71
|
+
async def run_once(self, now: datetime | None = None) -> MessagingJanitorStats:
|
|
72
|
+
"""Delete the inbox marks, outbox records and activity past their retention; returns the
|
|
73
|
+
counts."""
|
|
74
|
+
now = now or datetime.now(UTC)
|
|
75
|
+
stats = MessagingJanitorStats()
|
|
76
|
+
if self.inbox_retention is not None:
|
|
77
|
+
before = now - self.inbox_retention
|
|
78
|
+
stats.inbox = await self._drain(lambda uow: _inbox(uow).purge(before, self.batch_size))
|
|
79
|
+
if self.outbox_retention is not None:
|
|
80
|
+
before = now - self.outbox_retention
|
|
81
|
+
stats.outbox = await self._drain(
|
|
82
|
+
lambda uow: _outbox(uow).purge_published(before, self.batch_size)
|
|
83
|
+
)
|
|
84
|
+
if self.activity is not None:
|
|
85
|
+
before = now - self.activity_retention
|
|
86
|
+
while True:
|
|
87
|
+
deleted = await self.activity.purge(before, self.batch_size)
|
|
88
|
+
stats.activity += deleted
|
|
89
|
+
if deleted < self.batch_size:
|
|
90
|
+
break
|
|
91
|
+
if stats.inbox or stats.outbox:
|
|
92
|
+
logger.info("Purged %d inbox marks, %d outbox records", stats.inbox, stats.outbox)
|
|
93
|
+
return stats
|
|
94
|
+
|
|
95
|
+
async def _drain(self, step: Callable[[Any], Any]) -> int:
|
|
96
|
+
total = 0
|
|
97
|
+
while True:
|
|
98
|
+
async with self.uow_factory() as uow:
|
|
99
|
+
deleted: int = await step(uow)
|
|
100
|
+
await uow.commit()
|
|
101
|
+
total += deleted
|
|
102
|
+
if deleted < self.batch_size:
|
|
103
|
+
return total
|
|
104
|
+
|
|
105
|
+
async def run_forever(
|
|
106
|
+
self, *, interval: float = 3600.0, stop: asyncio.Event | None = None
|
|
107
|
+
) -> None:
|
|
108
|
+
"""Run every ``interval`` seconds until ``stop`` is set; failures are logged."""
|
|
109
|
+
stop = stop or asyncio.Event()
|
|
110
|
+
while not stop.is_set():
|
|
111
|
+
try:
|
|
112
|
+
await self.run_once()
|
|
113
|
+
except Exception:
|
|
114
|
+
logger.exception("Messaging janitor run failed")
|
|
115
|
+
with contextlib.suppress(TimeoutError):
|
|
116
|
+
await asyncio.wait_for(stop.wait(), timeout=interval)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _inbox(uow: Any) -> Any:
|
|
120
|
+
if not isinstance(uow, SupportsInbox):
|
|
121
|
+
raise ConfigurationError(
|
|
122
|
+
f"{type(uow).__name__} has no inbox()",
|
|
123
|
+
hint="Pass inbox_retention=None, or a unit of work with an inbox table.",
|
|
124
|
+
doc="docs/messaging.md#retention",
|
|
125
|
+
)
|
|
126
|
+
return uow.inbox()
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _outbox(uow: Any) -> Any:
|
|
130
|
+
if not isinstance(uow, SupportsOutbox):
|
|
131
|
+
raise ConfigurationError(
|
|
132
|
+
f"{type(uow).__name__} has no outbox()",
|
|
133
|
+
hint="Pass outbox_retention=None, or a unit of work with an outbox table.",
|
|
134
|
+
doc="docs/messaging.md#retention",
|
|
135
|
+
)
|
|
136
|
+
return uow.outbox()
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""Committed events, live, filtered to what each subscriber may see.
|
|
2
|
+
|
|
3
|
+
``LiveEvents`` is what the GraphQL subscriptions and the explorer's event
|
|
4
|
+
stream share. It reads an ``EventHub`` and applies the visibility rules:
|
|
5
|
+
|
|
6
|
+
- **Events about a record** (``resource`` and ``entity_id``) reach a
|
|
7
|
+
subscriber only if the record can be read by them now. It is read with
|
|
8
|
+
``manager.get`` as them, so the permission, the row filter and the tenant
|
|
9
|
+
apply, and the subscriber gets the record as they may see it (hidden fields
|
|
10
|
+
left out).
|
|
11
|
+
- **Deletions** reach only subscribers who already got that record in this
|
|
12
|
+
stream: a stream never reveals ids it didn't show.
|
|
13
|
+
- **The payload** goes only to subscribers holding ``events:read``, since it
|
|
14
|
+
may carry fields hidden from others. They see every committed event: those
|
|
15
|
+
about no record (processes, engine events), and those about records they
|
|
16
|
+
can't read now (without the record). Everyone else sees the record instead.
|
|
17
|
+
|
|
18
|
+
```python
|
|
19
|
+
live = LiveEvents(manager, hub)
|
|
20
|
+
async for event in live.stream(actor, resource="invoices", types={"InvoiceApproved"}):
|
|
21
|
+
event.envelope, event.record, event.payload_visible
|
|
22
|
+
```
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
from collections.abc import AsyncIterator, Collection
|
|
28
|
+
from dataclasses import dataclass
|
|
29
|
+
from typing import Any
|
|
30
|
+
|
|
31
|
+
from pydantic import TypeAdapter
|
|
32
|
+
|
|
33
|
+
from resource_engine.errors import (
|
|
34
|
+
EntityNotFound,
|
|
35
|
+
OperationNotEnabled,
|
|
36
|
+
PermissionDenied,
|
|
37
|
+
ResourceNotRegistered,
|
|
38
|
+
TenantMismatch,
|
|
39
|
+
TenantRequired,
|
|
40
|
+
)
|
|
41
|
+
from resource_engine.messaging.envelope import EventEnvelope
|
|
42
|
+
|
|
43
|
+
#: Errors meaning "not visible to this subscriber": the event is skipped.
|
|
44
|
+
HIDDEN = (
|
|
45
|
+
EntityNotFound,
|
|
46
|
+
PermissionDenied,
|
|
47
|
+
TenantRequired,
|
|
48
|
+
TenantMismatch,
|
|
49
|
+
OperationNotEnabled,
|
|
50
|
+
ResourceNotRegistered,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
DELETED = "ResourceDeleted"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class LiveEvent:
|
|
58
|
+
"""One event as a subscriber may see it.
|
|
59
|
+
|
|
60
|
+
Attributes:
|
|
61
|
+
envelope: The envelope. Its payload is only for ``payload_visible``.
|
|
62
|
+
resource / entity_id: The record it is about (``None``: no record).
|
|
63
|
+
record: The record as the subscriber reads it now (``None`` for
|
|
64
|
+
deletions and events about no record).
|
|
65
|
+
payload_visible: Whether the subscriber may see ``envelope.payload``.
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
envelope: EventEnvelope
|
|
69
|
+
resource: str | None
|
|
70
|
+
entity_id: Any
|
|
71
|
+
record: Any
|
|
72
|
+
payload_visible: bool
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class LiveEvents:
|
|
76
|
+
"""Committed events from ``hub``, through the visibility rules above."""
|
|
77
|
+
|
|
78
|
+
def __init__(self, manager: Any, hub: Any) -> None:
|
|
79
|
+
self.manager = manager
|
|
80
|
+
self.hub = hub
|
|
81
|
+
|
|
82
|
+
def about(self, envelope: EventEnvelope) -> tuple[str | None, Any]:
|
|
83
|
+
"""The record an event is about: ``(resource, id)``, typed by the
|
|
84
|
+
resource's id type (``(None, None)`` when it is about no record)."""
|
|
85
|
+
payload = envelope.payload or {}
|
|
86
|
+
resource = payload.get("resource") or envelope.resource
|
|
87
|
+
value = payload.get("entity_id")
|
|
88
|
+
if not resource or value is None or resource not in self.manager.registry:
|
|
89
|
+
return None, None
|
|
90
|
+
id_type = self.manager.registry.get(resource).id_type
|
|
91
|
+
try:
|
|
92
|
+
return resource, TypeAdapter(id_type).validate_python(value)
|
|
93
|
+
except Exception:
|
|
94
|
+
return None, None
|
|
95
|
+
|
|
96
|
+
async def stream(
|
|
97
|
+
self,
|
|
98
|
+
actor: Any,
|
|
99
|
+
*,
|
|
100
|
+
tenant: str | None = None,
|
|
101
|
+
resource: str | None = None,
|
|
102
|
+
entity_id: Any = None,
|
|
103
|
+
types: Collection[str] = (),
|
|
104
|
+
versions: Collection[str] = (),
|
|
105
|
+
everything: bool = False,
|
|
106
|
+
) -> AsyncIterator[LiveEvent]:
|
|
107
|
+
"""Events ``actor`` may see, as they are committed.
|
|
108
|
+
|
|
109
|
+
Args:
|
|
110
|
+
resource / entity_id: Only events about that resource (that record).
|
|
111
|
+
types / versions: Only these event types / schema versions.
|
|
112
|
+
everything: The subscriber holds ``events:read``: payloads, and
|
|
113
|
+
events about no record.
|
|
114
|
+
"""
|
|
115
|
+
types, versions = set(types), {str(v) for v in versions}
|
|
116
|
+
if entity_id is not None and resource is not None:
|
|
117
|
+
entity_id = TypeAdapter(self.manager.registry.get(resource).id_type).validate_python(
|
|
118
|
+
entity_id
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
def matches(envelope: EventEnvelope) -> bool:
|
|
122
|
+
if types and envelope.type not in types:
|
|
123
|
+
return False
|
|
124
|
+
if versions and str(envelope.schema_version) not in versions:
|
|
125
|
+
return False
|
|
126
|
+
about, about_id = self.about(envelope)
|
|
127
|
+
# the channel: the resource it is about, else the one that published it
|
|
128
|
+
channel = about or (envelope.payload or {}).get("resource") or envelope.resource
|
|
129
|
+
if resource is not None and channel != resource:
|
|
130
|
+
return False
|
|
131
|
+
if entity_id is not None and about_id != entity_id:
|
|
132
|
+
return False
|
|
133
|
+
return about is not None or everything
|
|
134
|
+
|
|
135
|
+
subscription = self.hub.subscribe(matches)
|
|
136
|
+
shown: set[tuple[str, Any]] = set()
|
|
137
|
+
try:
|
|
138
|
+
async for envelope in subscription:
|
|
139
|
+
event = await self.visible(envelope, actor, tenant=tenant, shown=shown,
|
|
140
|
+
everything=everything) # fmt: skip
|
|
141
|
+
if event is not None:
|
|
142
|
+
yield event
|
|
143
|
+
finally:
|
|
144
|
+
subscription.close()
|
|
145
|
+
|
|
146
|
+
async def visible(
|
|
147
|
+
self,
|
|
148
|
+
envelope: EventEnvelope,
|
|
149
|
+
actor: Any,
|
|
150
|
+
*,
|
|
151
|
+
tenant: str | None = None,
|
|
152
|
+
shown: set[tuple[str, Any]] | None = None,
|
|
153
|
+
everything: bool = False,
|
|
154
|
+
) -> LiveEvent | None:
|
|
155
|
+
"""``envelope`` as ``actor`` may see it, or ``None``. ``shown`` holds the
|
|
156
|
+
records this subscriber already got (deletions need them)."""
|
|
157
|
+
shown = shown if shown is not None else set()
|
|
158
|
+
resource, entity_id = self.about(envelope)
|
|
159
|
+
if resource is None:
|
|
160
|
+
if not everything:
|
|
161
|
+
return None
|
|
162
|
+
return LiveEvent(envelope, None, None, None, True)
|
|
163
|
+
if envelope.type == DELETED:
|
|
164
|
+
if (resource, entity_id) not in shown:
|
|
165
|
+
return None # never reveal the id of a record this stream didn't show
|
|
166
|
+
shown.discard((resource, entity_id))
|
|
167
|
+
return LiveEvent(envelope, resource, entity_id, None, everything)
|
|
168
|
+
try:
|
|
169
|
+
record = await self.manager.get(resource, entity_id, actor=actor, tenant=tenant)
|
|
170
|
+
except HIDDEN:
|
|
171
|
+
if not everything:
|
|
172
|
+
return None
|
|
173
|
+
# events:read sees every committed event; the record only if readable
|
|
174
|
+
return LiveEvent(envelope, resource, entity_id, None, True)
|
|
175
|
+
shown.add((resource, entity_id))
|
|
176
|
+
return LiveEvent(envelope, resource, entity_id, record, everything)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
__all__ = ["HIDDEN", "LiveEvent", "LiveEvents"]
|