resource-engine-devtools 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_devtools/__init__.py +6 -0
- resource_engine_devtools/ai/__init__.py +1 -0
- resource_engine_devtools/ai/example.py +66 -0
- resource_engine_devtools/ai/installer.py +424 -0
- resource_engine_devtools/ai/skill/SKILL.md +130 -0
- resource_engine_devtools/ai/skill/examples/README.md +7 -0
- resource_engine_devtools/ai/skill/examples/invoices/__init__.py +0 -0
- resource_engine_devtools/ai/skill/examples/invoices/app.py +245 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/__init__.py +0 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/actions.py +61 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/balances.py +51 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/customers.py +35 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/hooks.py +61 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/processes.py +80 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/resource.py +112 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/schemas.py +164 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/tags.py +77 -0
- resource_engine_devtools/ai/skill/examples/invoices/authz.py +126 -0
- resource_engine_devtools/ai/skill/examples/invoices/bootstrap.py +80 -0
- resource_engine_devtools/ai/skill/examples/invoices/domain/__init__.py +0 -0
- resource_engine_devtools/ai/skill/examples/invoices/domain/entities.py +112 -0
- resource_engine_devtools/ai/skill/examples/invoices/domain/events.py +22 -0
- resource_engine_devtools/ai/skill/examples/invoices/domain/state_machine.py +88 -0
- resource_engine_devtools/ai/skill/examples/invoices/infrastructure/__init__.py +0 -0
- resource_engine_devtools/ai/skill/examples/invoices/infrastructure/persistence.py +121 -0
- resource_engine_devtools/ai/skill/examples/invoices/locale/en/LC_MESSAGES/messages.po +682 -0
- resource_engine_devtools/ai/skill/examples/invoices/locale/es/LC_MESSAGES/messages.po +685 -0
- resource_engine_devtools/ai/skill/examples/invoices/notifications.py +47 -0
- resource_engine_devtools/ai/skill/examples/invoices/templates/email/base.html +7 -0
- resource_engine_devtools/ai/skill/examples/invoices/templates/email/invoice_approved.html +5 -0
- resource_engine_devtools/ai/skill/examples/invoices/templates/email/invoice_approved.subject.txt +1 -0
- resource_engine_devtools/ai/skill/examples/invoices/templates/email/invoice_approved.txt +5 -0
- resource_engine_devtools/ai/skill/examples/invoices/tests/conftest.py +40 -0
- resource_engine_devtools/ai/skill/examples/invoices/tests/test_invoices_engine.py +241 -0
- resource_engine_devtools/ai/skill/examples/invoices/worker.py +53 -0
- resource_engine_devtools/ai/skill/llms.txt +25 -0
- resource_engine_devtools/ai/skill/references/anti-patterns.md +209 -0
- resource_engine_devtools/ai/skill/references/docstrings.md +97 -0
- resource_engine_devtools/ai/skill/references/errors.md +81 -0
- resource_engine_devtools/ai/skill/references/lifecycle.md +118 -0
- resource_engine_devtools/ai/skill/references/permissions.md +111 -0
- resource_engine_devtools/ai/skill/references/resource.md +301 -0
- resource_engine_devtools/ai/skill/references/state-machines.md +126 -0
- resource_engine_devtools/ai/skill/references/testing.md +80 -0
- resource_engine_devtools/ai/templates/agents_block.md +26 -0
- resource_engine_devtools/ai/templates/cursor_rule.mdc +7 -0
- resource_engine_devtools/check.py +67 -0
- resource_engine_devtools/cli.py +1112 -0
- resource_engine_devtools/consumer_scaffold.py +715 -0
- resource_engine_devtools/contracts.py +471 -0
- resource_engine_devtools/db.py +132 -0
- resource_engine_devtools/declarations_check.py +116 -0
- resource_engine_devtools/documentation/__init__.py +10 -0
- resource_engine_devtools/documentation/docstrings.py +72 -0
- resource_engine_devtools/documentation/generators/__init__.py +9 -0
- resource_engine_devtools/documentation/generators/ai_context.py +121 -0
- resource_engine_devtools/documentation/generators/api.py +63 -0
- resource_engine_devtools/documentation/generators/json.py +12 -0
- resource_engine_devtools/documentation/generators/markdown.py +687 -0
- resource_engine_devtools/documentation/generators/mermaid.py +22 -0
- resource_engine_devtools/documentation/generators/site.py +379 -0
- resource_engine_devtools/documentation/generators/site_assets/site.css +62 -0
- resource_engine_devtools/documentation/generators/site_assets/site.js +54 -0
- resource_engine_devtools/documentation/i18n.py +185 -0
- resource_engine_devtools/documentation/introspector.py +563 -0
- resource_engine_devtools/documentation/locale/ca/LC_MESSAGES/docs.po +628 -0
- resource_engine_devtools/documentation/locale/es/LC_MESSAGES/docs.po +627 -0
- resource_engine_devtools/documentation/model.py +311 -0
- resource_engine_devtools/documentation/validator.py +128 -0
- resource_engine_devtools/emails.py +172 -0
- resource_engine_devtools/events_check.py +124 -0
- resource_engine_devtools/gates_check.py +133 -0
- resource_engine_devtools/hooks_check.py +287 -0
- resource_engine_devtools/i18n.py +312 -0
- resource_engine_devtools/loader.py +93 -0
- resource_engine_devtools/logic_check.py +136 -0
- resource_engine_devtools/mcp_server.py +685 -0
- resource_engine_devtools/py.typed +0 -0
- resource_engine_devtools/scaffold.py +805 -0
- resource_engine_devtools/scaffold_parts.py +637 -0
- resource_engine_devtools/source_edit.py +424 -0
- resource_engine_devtools/templates_check.py +59 -0
- resource_engine_devtools/worker.py +68 -0
- resource_engine_devtools-0.1.0.dist-info/METADATA +38 -0
- resource_engine_devtools-0.1.0.dist-info/RECORD +88 -0
- resource_engine_devtools-0.1.0.dist-info/WHEEL +4 -0
- resource_engine_devtools-0.1.0.dist-info/entry_points.txt +2 -0
- resource_engine_devtools-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Emails of the example: Jinja templates shipped in the package
|
|
2
|
+
(``invoices/templates``), written in Catalan and translated to English and
|
|
3
|
+
Spanish by the catalogues in ``invoices/locale`` (``{% trans %}``); and SMTP.
|
|
4
|
+
|
|
5
|
+
Locally, Mailpit catches every message (``docker compose -f
|
|
6
|
+
compose.emulators.yaml up -d mailpit``; UI at http://127.0.0.1:8026). In
|
|
7
|
+
production set ``SMTP_HOST``, ``SMTP_PORT``, ``SMTP_USERNAME`` and
|
|
8
|
+
``SMTP_PASSWORD``; ``SMTP_TLS=0`` only for a local catcher.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from resource_engine.email import Mailer
|
|
17
|
+
from resource_engine.i18n import Translations
|
|
18
|
+
from resource_engine.ports.email import EmailSender
|
|
19
|
+
from resource_engine_jinja import JinjaTemplates
|
|
20
|
+
from resource_engine_smtp import SmtpEmailSender
|
|
21
|
+
|
|
22
|
+
#: The example's catalogues (``resource-engine i18n compile`` writes the .mo files).
|
|
23
|
+
translations = Translations(Path(__file__).parent / "locale", default_locale="ca")
|
|
24
|
+
templates = JinjaTemplates(
|
|
25
|
+
package="invoices", folder="templates", default_locale="ca", translations=translations
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def smtp_sender() -> SmtpEmailSender:
|
|
30
|
+
host = os.getenv("SMTP_HOST", "127.0.0.1")
|
|
31
|
+
return SmtpEmailSender(
|
|
32
|
+
host,
|
|
33
|
+
int(os.getenv("SMTP_PORT", "1026")),
|
|
34
|
+
username=os.getenv("SMTP_USERNAME") or None,
|
|
35
|
+
password=os.getenv("SMTP_PASSWORD") or None,
|
|
36
|
+
tls=os.getenv("SMTP_TLS", "0" if host in ("127.0.0.1", "localhost") else "1") == "1",
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def build_mailer(sender: EmailSender | None = None) -> Mailer:
|
|
41
|
+
return Mailer(
|
|
42
|
+
sender or smtp_sender(),
|
|
43
|
+
templates,
|
|
44
|
+
from_address=os.getenv("EMAIL_FROM", "Factures <factures@invoices.example>"),
|
|
45
|
+
default_locale="ca",
|
|
46
|
+
globals={"app_name": "Factures · exemple de Resource Engine"},
|
|
47
|
+
)
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
{% extends "email/base.html" %}
|
|
2
|
+
{% block body %}
|
|
3
|
+
<p>{% trans %}Hola, {{ customer }}:{% endtrans %}</p>
|
|
4
|
+
<p>{% trans number=number, amount=amount %}La factura <strong>{{ number }}</strong>, de <strong>{{ amount }} €</strong>, ha estat aprovada.{% endtrans %}</p>
|
|
5
|
+
{% endblock %}
|
resource_engine_devtools/ai/skill/examples/invoices/templates/email/invoice_approved.subject.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{{ _("Factura %(number)s aprovada", number=number) }}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
from invoices.bootstrap import registry
|
|
5
|
+
from resource_engine import ResourceManager
|
|
6
|
+
from resource_engine.testing import InMemoryBlobStore, InMemoryStore, RecordingEventPublisher
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class FakeNotifier:
|
|
10
|
+
def __init__(self) -> None:
|
|
11
|
+
self.sent: list[str] = []
|
|
12
|
+
|
|
13
|
+
async def send(self, message: str) -> None:
|
|
14
|
+
self.sent.append(message)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@pytest.fixture
|
|
18
|
+
def notifier() -> FakeNotifier:
|
|
19
|
+
return FakeNotifier()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@pytest.fixture
|
|
23
|
+
def publisher() -> RecordingEventPublisher:
|
|
24
|
+
return RecordingEventPublisher()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@pytest.fixture
|
|
28
|
+
def store() -> InMemoryStore:
|
|
29
|
+
return InMemoryStore.from_registry(registry)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@pytest.fixture
|
|
33
|
+
def manager(store, publisher, notifier) -> ResourceManager:
|
|
34
|
+
return ResourceManager(
|
|
35
|
+
registry,
|
|
36
|
+
store.unit_of_work,
|
|
37
|
+
event_publisher=publisher,
|
|
38
|
+
services={"notifier": notifier},
|
|
39
|
+
blob_store=InMemoryBlobStore(),
|
|
40
|
+
)
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
"""Lifecycle tests of the reference module against in-memory adapters."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from decimal import Decimal
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
from invoices.application.customers import CustomerResource
|
|
9
|
+
from invoices.application.resource import InvoiceResource
|
|
10
|
+
from resource_engine import ListQuery, OperationContext, ResourceManager, ResourceRegistry
|
|
11
|
+
from resource_engine.domain import DomainError
|
|
12
|
+
from resource_engine.errors import (
|
|
13
|
+
EntityNotFound,
|
|
14
|
+
InvalidQuery,
|
|
15
|
+
OperationNotEnabled,
|
|
16
|
+
RequiredDocumentMissing,
|
|
17
|
+
TransitionNotAllowed,
|
|
18
|
+
UnknownTransition,
|
|
19
|
+
ValidationFailed,
|
|
20
|
+
)
|
|
21
|
+
from resource_engine.testing import InMemoryBlobStore, InMemoryStore
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
async def test_create_sets_initial_state_and_publishes_after_commit(manager, publisher):
|
|
25
|
+
invoice = await manager.create("invoices", {"customer": "ACME", "amount": "100.00"})
|
|
26
|
+
assert invoice.id == 1
|
|
27
|
+
assert invoice.status == "draft"
|
|
28
|
+
assert publisher.names() == ["ResourceCreated"]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
async def test_validation_error_has_details(manager):
|
|
32
|
+
with pytest.raises(ValidationFailed) as info:
|
|
33
|
+
await manager.create("invoices", {"customer": "", "amount": "x"})
|
|
34
|
+
fields = {tuple(e["loc"]) for e in info.value.details}
|
|
35
|
+
assert ("customer",) in fields and ("amount",) in fields
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
async def test_domain_rule_in_hook_rolls_back(manager, store, publisher):
|
|
39
|
+
with pytest.raises(DomainError):
|
|
40
|
+
await manager.create("invoices", {"customer": "ACME", "amount": "-1"})
|
|
41
|
+
assert store.all("invoices") == []
|
|
42
|
+
assert publisher.events == []
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
async def test_update_only_sent_fields_and_reports_changes(manager, publisher):
|
|
46
|
+
created = await manager.create("invoices", {"customer": "ACME", "amount": "10", "notes": "a"})
|
|
47
|
+
updated = await manager.update("invoices", created.id, {"amount": "12"})
|
|
48
|
+
assert updated.amount == Decimal("12") and updated.notes == "a"
|
|
49
|
+
event = publisher.events[-1]
|
|
50
|
+
assert event.name == "ResourceUpdated"
|
|
51
|
+
assert event.changes == {"amount": (Decimal("10"), Decimal("12"))}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
async def test_after_hook_failure_rolls_back_update(manager, store):
|
|
55
|
+
created = await manager.create("invoices", {"customer": "ACME", "amount": "10"})
|
|
56
|
+
with pytest.raises(DomainError):
|
|
57
|
+
await manager.update("invoices", created.id, {"amount": "-5"})
|
|
58
|
+
assert store.all("invoices")[0].amount == Decimal("10")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
async def test_state_cannot_change_through_update(manager):
|
|
62
|
+
created = await manager.create("invoices", {"customer": "ACME", "amount": "10"})
|
|
63
|
+
updated = await manager.update("invoices", created.id, {"status": "paid", "notes": "x"})
|
|
64
|
+
assert updated.status == "draft"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
async def test_full_transition_flow(manager, publisher, notifier):
|
|
68
|
+
inv = await manager.create("invoices", {"customer": "ACME", "amount": "10"})
|
|
69
|
+
assert await manager.allowed_transitions("invoices", inv.id) == ["submit"]
|
|
70
|
+
inv = await manager.transition("invoices", inv.id, "submit")
|
|
71
|
+
assert inv.status == "pending"
|
|
72
|
+
with pytest.raises(RequiredDocumentMissing):
|
|
73
|
+
await manager.transition("invoices", inv.id, "approve")
|
|
74
|
+
await attach_signed(manager, inv.id)
|
|
75
|
+
inv = await manager.transition("invoices", inv.id, "approve")
|
|
76
|
+
assert inv.status == "approved"
|
|
77
|
+
assert notifier.sent == [f"Invoice {inv.id} approved"]
|
|
78
|
+
inv = await manager.transition("invoices", inv.id, "pay")
|
|
79
|
+
assert inv.status == "paid"
|
|
80
|
+
transitions = [(e.source, e.target) for e in publisher.events if e.name == "TransitionExecuted"]
|
|
81
|
+
assert transitions == [("draft", "pending"), ("pending", "approved"), ("approved", "paid")]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
async def test_invalid_transition_is_rejected_with_allowed_list(manager, store):
|
|
85
|
+
inv = await manager.create("invoices", {"customer": "ACME", "amount": "10"})
|
|
86
|
+
with pytest.raises(TransitionNotAllowed) as info:
|
|
87
|
+
await manager.transition("invoices", inv.id, "pay")
|
|
88
|
+
assert info.value.details == {"state": "draft", "allowed": ["submit"]}
|
|
89
|
+
assert store.all("invoices")[0].status == "draft"
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
async def test_unknown_transition(manager):
|
|
93
|
+
inv = await manager.create("invoices", {"customer": "ACME", "amount": "10"})
|
|
94
|
+
with pytest.raises(UnknownTransition):
|
|
95
|
+
await manager.transition("invoices", inv.id, "archive")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
async def test_transition_payload_reaches_state_machine(manager):
|
|
99
|
+
inv = await manager.create("invoices", {"customer": "ACME", "amount": "10"})
|
|
100
|
+
await manager.transition("invoices", inv.id, "submit")
|
|
101
|
+
with pytest.raises(ValidationFailed):
|
|
102
|
+
await manager.transition("invoices", inv.id, "reject", {})
|
|
103
|
+
inv = await manager.transition("invoices", inv.id, "reject", {"reason": "Wrong VAT"})
|
|
104
|
+
assert inv.status == "rejected" and inv.rejection_reason == "Wrong VAT"
|
|
105
|
+
inv = await manager.transition("invoices", inv.id, "reopen")
|
|
106
|
+
assert inv.status == "draft" and inv.rejection_reason is None
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
async def test_submitted_invoice_cannot_be_edited_or_deleted(manager):
|
|
110
|
+
inv = await manager.create("invoices", {"customer": "ACME", "amount": "10"})
|
|
111
|
+
await manager.transition("invoices", inv.id, "submit")
|
|
112
|
+
with pytest.raises(DomainError):
|
|
113
|
+
await manager.update("invoices", inv.id, {"notes": "late"})
|
|
114
|
+
with pytest.raises(DomainError):
|
|
115
|
+
await manager.delete("invoices", inv.id)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
async def test_delete_and_not_found(manager, publisher):
|
|
119
|
+
inv = await manager.create("invoices", {"customer": "ACME", "amount": "10"})
|
|
120
|
+
await manager.delete("invoices", inv.id)
|
|
121
|
+
assert publisher.names()[-1] == "ResourceDeleted"
|
|
122
|
+
with pytest.raises(EntityNotFound) as info:
|
|
123
|
+
await manager.get("invoices", inv.id)
|
|
124
|
+
assert info.value.code == "RE-E102"
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
async def test_list_filters_ordering_and_paging(manager):
|
|
128
|
+
for customer, amount in [("A", "30"), ("B", "10"), ("A", "20")]:
|
|
129
|
+
await manager.create("invoices", {"customer": customer, "amount": amount})
|
|
130
|
+
page = await manager.list(
|
|
131
|
+
"invoices", ListQuery(filters={"customer": "A"}, order_by=["amount"], limit=1)
|
|
132
|
+
)
|
|
133
|
+
assert page.total == 2
|
|
134
|
+
assert [i.amount for i in page.items] == [Decimal("20")]
|
|
135
|
+
with pytest.raises(InvalidQuery):
|
|
136
|
+
await manager.list("invoices", ListQuery(filters={"notes": "x"}))
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
async def test_action_runs_in_transaction_and_emits_events(manager, publisher):
|
|
140
|
+
inv = await manager.create("invoices", {"customer": "ACME", "amount": "200"})
|
|
141
|
+
result = await manager.run_action("invoices", inv.id, "recalculate_totals", {"percent": "15"})
|
|
142
|
+
assert result.amount == Decimal("170.00")
|
|
143
|
+
assert publisher.names()[-2:] == ["InvoiceTotalsRecalculated", "ActionExecuted"]
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
async def test_after_commit_failure_does_not_undo_operation(store, publisher, caplog):
|
|
147
|
+
class BrokenNotifier:
|
|
148
|
+
async def send(self, message):
|
|
149
|
+
raise RuntimeError("SMTP down")
|
|
150
|
+
|
|
151
|
+
from invoices.bootstrap import registry
|
|
152
|
+
|
|
153
|
+
manager = ResourceManager(
|
|
154
|
+
registry,
|
|
155
|
+
store.unit_of_work,
|
|
156
|
+
event_publisher=publisher,
|
|
157
|
+
services={"notifier": BrokenNotifier()},
|
|
158
|
+
blob_store=InMemoryBlobStore(),
|
|
159
|
+
)
|
|
160
|
+
inv = await manager.create("invoices", {"customer": "ACME", "amount": "10"})
|
|
161
|
+
await manager.transition("invoices", inv.id, "submit")
|
|
162
|
+
await attach_signed(manager, inv.id)
|
|
163
|
+
approved = await manager.transition("invoices", inv.id, "approve")
|
|
164
|
+
assert approved.status == "approved"
|
|
165
|
+
assert store.all("invoices")[0].status == "approved"
|
|
166
|
+
assert "after_commit hook" in caplog.text
|
|
167
|
+
assert publisher.names()[-1] == "TransitionExecuted"
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
async def test_hook_order_is_contractual():
|
|
171
|
+
calls: list[str] = []
|
|
172
|
+
|
|
173
|
+
def rec(name):
|
|
174
|
+
def hook(ctx: OperationContext):
|
|
175
|
+
calls.append(name)
|
|
176
|
+
|
|
177
|
+
hook.__qualname__ = name
|
|
178
|
+
return hook
|
|
179
|
+
|
|
180
|
+
class TracedInvoices(InvoiceResource):
|
|
181
|
+
name = "traced"
|
|
182
|
+
documents = []
|
|
183
|
+
hooks = {
|
|
184
|
+
point: [rec(point)]
|
|
185
|
+
for point in (
|
|
186
|
+
"before_validate",
|
|
187
|
+
"after_validate",
|
|
188
|
+
"before_create",
|
|
189
|
+
"after_create",
|
|
190
|
+
"after_commit",
|
|
191
|
+
)
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
registry = ResourceRegistry()
|
|
195
|
+
registry.register(CustomerResource) # invoices reference customers
|
|
196
|
+
registry.register(TracedInvoices)
|
|
197
|
+
manager = ResourceManager(registry, InMemoryStore.from_registry(registry).unit_of_work)
|
|
198
|
+
await manager.create("traced", {"customer": "ACME", "amount": "1"})
|
|
199
|
+
assert calls == [
|
|
200
|
+
"before_validate",
|
|
201
|
+
"after_validate",
|
|
202
|
+
"before_create",
|
|
203
|
+
"after_create",
|
|
204
|
+
"after_commit",
|
|
205
|
+
]
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
async def test_disabled_operation():
|
|
209
|
+
class ReadOnlyInvoices(InvoiceResource):
|
|
210
|
+
name = "readonly_invoices"
|
|
211
|
+
documents = []
|
|
212
|
+
operations = ["list", "get"]
|
|
213
|
+
|
|
214
|
+
registry = ResourceRegistry()
|
|
215
|
+
registry.register(CustomerResource) # invoices reference customers
|
|
216
|
+
registry.register(ReadOnlyInvoices)
|
|
217
|
+
manager = ResourceManager(registry, InMemoryStore.from_registry(registry).unit_of_work)
|
|
218
|
+
with pytest.raises(OperationNotEnabled):
|
|
219
|
+
await manager.create("readonly_invoices", {"customer": "ACME", "amount": "1"})
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
async def attach_signed(manager, invoice_id):
|
|
223
|
+
return await manager.documents.attach(
|
|
224
|
+
"invoices",
|
|
225
|
+
invoice_id,
|
|
226
|
+
"signed_pdf",
|
|
227
|
+
b"%PDF-1.7",
|
|
228
|
+
filename="signada.pdf",
|
|
229
|
+
content_type="application/pdf",
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
async def test_render_summary_replaces_the_previous_summary(manager):
|
|
234
|
+
inv = await manager.create("invoices", {"customer": "ACME", "amount": "10"})
|
|
235
|
+
await manager.run_action("invoices", inv.id, "render_summary")
|
|
236
|
+
await manager.update("invoices", inv.id, {"customer": "ACME SL"})
|
|
237
|
+
await manager.run_action("invoices", inv.id, "render_summary")
|
|
238
|
+
(summary,) = await manager.documents.list("invoices", inv.id, "summary")
|
|
239
|
+
_, stream = await manager.documents.open(summary.id)
|
|
240
|
+
text = b"".join([c async for c in stream]).decode()
|
|
241
|
+
assert "ACME SL" in text and summary.filename == f"factura-{inv.id}.md"
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""The example's worker: ``uv run resource-engine worker`` (``[tool.resource-engine]
|
|
2
|
+
worker``).
|
|
3
|
+
|
|
4
|
+
- ``processes``: feeds the outbox to the process managers (the invoice payment
|
|
5
|
+
process) and to the mailer (requested emails), exactly once through the inbox.
|
|
6
|
+
- ``timers``: due timed transitions (pending invoices after 30 days, overdue
|
|
7
|
+
payments after 15).
|
|
8
|
+
- ``exports``: background exports (``POST /invoices/exports``), written to the
|
|
9
|
+
documents' blob store.
|
|
10
|
+
|
|
11
|
+
Run it next to the app, on the same database (``DATABASE_URL``).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
from datetime import timedelta
|
|
18
|
+
|
|
19
|
+
from resource_engine import TimerJob
|
|
20
|
+
from resource_engine.jobs import JobRunner
|
|
21
|
+
from resource_engine.messaging import ActivityMessageObserver, MessageProcessor
|
|
22
|
+
from resource_engine.processes import ProcessFeed, ProcessRunner
|
|
23
|
+
from resource_engine_sqlalchemy import SqlAlchemyLocks
|
|
24
|
+
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
|
25
|
+
|
|
26
|
+
from invoices.app import _blob_store, activity_log, build_manager
|
|
27
|
+
from invoices.infrastructure.persistence import engine as engine_tables
|
|
28
|
+
from invoices.infrastructure.persistence import map_entities
|
|
29
|
+
from invoices.notifications import build_mailer
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def build(database_url: str | None = None) -> JobRunner:
|
|
33
|
+
map_entities()
|
|
34
|
+
engine = create_async_engine(
|
|
35
|
+
database_url or os.environ.get("DATABASE_URL") or "sqlite+aiosqlite:///invoices.db",
|
|
36
|
+
pool_pre_ping=True, # a database restart costs no failed run
|
|
37
|
+
)
|
|
38
|
+
sessions = async_sessionmaker(engine, expire_on_commit=False)
|
|
39
|
+
manager = build_manager(sessions, blob_store=_blob_store()[0])
|
|
40
|
+
router = ProcessRunner(manager).router().include(build_mailer().router())
|
|
41
|
+
activity = activity_log(sessions) # shown by the explorer: runs, run now, deliveries
|
|
42
|
+
processor = MessageProcessor(
|
|
43
|
+
router,
|
|
44
|
+
name="invoice-processes",
|
|
45
|
+
manager=manager,
|
|
46
|
+
observers=[ActivityMessageObserver(activity)],
|
|
47
|
+
)
|
|
48
|
+
runner = JobRunner(locks=SqlAlchemyLocks(sessions, engine_tables.locks), activity=activity)
|
|
49
|
+
runner.add("processes", ProcessFeed(manager.uow_factory, processor), every=1, single=True)
|
|
50
|
+
runner.add("timers", TimerJob(manager), every=timedelta(minutes=1), single=True)
|
|
51
|
+
if manager.exports is not None:
|
|
52
|
+
runner.add("exports", manager.exports, every=5, single=True)
|
|
53
|
+
return runner
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# Resource Engine
|
|
2
|
+
|
|
3
|
+
> Python framework for declarative business backends. A `Resource` declares an entity's schemas, CRUD operations, state machine, actions, hooks and document slots; the `ResourceManager` runs every operation through one lifecycle (validation, permissions, hooks, one transaction, audit, events after commit). Domain code is plain Python; FastAPI, SQLAlchemy and brokers are adapters.
|
|
4
|
+
|
|
5
|
+
Rules that must not be broken: no external effects before commit; state changes only through transitions; no framework imports in `domain/`; permissions in policies, not hooks; document every functional element. Verify with `resource-engine check --json`, `resource-engine docs validate --strict` and `pytest`.
|
|
6
|
+
|
|
7
|
+
## Skill
|
|
8
|
+
|
|
9
|
+
- [SKILL.md](SKILL.md): when to use the skill, workflow, rules, verification commands
|
|
10
|
+
- [Project catalogue](project.md): this project's resources, operations, transitions, actions and permissions (generated)
|
|
11
|
+
|
|
12
|
+
## References
|
|
13
|
+
|
|
14
|
+
- [Resources](references/resource.md): `Resource` attributes, schemas, actions, events, documents, wiring
|
|
15
|
+
- [Lifecycle](references/lifecycle.md): step order, hook points, `OperationContext`, external effects, transactions
|
|
16
|
+
- [State machines](references/state-machines.md): states, transitions, callbacks, guards
|
|
17
|
+
- [Permissions](references/permissions.md): action names, policies, conditions, fields, tenants
|
|
18
|
+
- [Docstrings](references/docstrings.md): functional sections and `docs validate` rules
|
|
19
|
+
- [Testing](references/testing.md): in-memory adapters and what to test
|
|
20
|
+
- [Errors](references/errors.md): every `RE-*` code and what to change
|
|
21
|
+
- [Anti-patterns](references/anti-patterns.md): common mistakes with the wrong and the right code
|
|
22
|
+
|
|
23
|
+
## Optional
|
|
24
|
+
|
|
25
|
+
- [Reference module](examples/invoices/application/resource.py): the complete `invoices` example (domain, application, infrastructure, tests)
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
# Anti-patterns
|
|
2
|
+
|
|
3
|
+
Each entry: what goes wrong, the wrong code, the fix. Check your change against
|
|
4
|
+
this list before finishing.
|
|
5
|
+
|
|
6
|
+
## 1. An e-mail or HTTP call inside the transaction
|
|
7
|
+
|
|
8
|
+
The call happens even if the operation then rolls back, and slows the
|
|
9
|
+
transaction down. `check` reports it (RE-C002).
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
# Wrong
|
|
13
|
+
@hook.after("create")
|
|
14
|
+
def notify(ctx):
|
|
15
|
+
httpx.post("https://crm.example/invoices", json={"id": ctx.entity.id})
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
```python
|
|
19
|
+
# Right: after commit, marked
|
|
20
|
+
@hook.after_commit
|
|
21
|
+
@external_effect
|
|
22
|
+
async def notify(ctx):
|
|
23
|
+
"""Avisa el CRM d'una factura nova.
|
|
24
|
+
|
|
25
|
+
Effects:
|
|
26
|
+
Crida l'API del CRM.
|
|
27
|
+
"""
|
|
28
|
+
await ctx.services["crm"].invoice_created(ctx.entity_id)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
# Right, with guaranteed delivery: an event handled by a consumer
|
|
32
|
+
def record(ctx):
|
|
33
|
+
ctx.record_event(InvoiceIssued(invoice_id=ctx.entity.id))
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## 2. Changing the state outside a transition
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
# Wrong
|
|
40
|
+
class InvoiceUpdate(BaseModel):
|
|
41
|
+
status: str | None = None # RE-E004 at registration
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def approve_big_ones(ctx):
|
|
45
|
+
ctx.entity.status = "approved" # bypasses permissions, hooks and events
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
# Right
|
|
50
|
+
await manager.transition("invoices", invoice_id, "approve", actor=user)
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## 3. Permission checks in hooks
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
# Wrong
|
|
57
|
+
def only_managers(ctx):
|
|
58
|
+
if "manager" not in ctx.actor.roles:
|
|
59
|
+
raise DomainError("forbidden")
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
# Right: a policy (data), or a system role in code
|
|
64
|
+
{"effect": "allow", "subjects": {"roles": ["manager"]}, "actions": ["invoices:transition:approve"]}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Policies are audited, explained (`/authz/explain`), turned into SQL filters
|
|
68
|
+
for `list`, and editable without a deploy. Hook checks are none of that.
|
|
69
|
+
|
|
70
|
+
## 4. Business rules in hooks instead of the domain
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
# Wrong
|
|
74
|
+
def check_amount(ctx):
|
|
75
|
+
if ctx.entity.amount < 0:
|
|
76
|
+
raise ValueError("negative")
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
# Right: the rule is a domain method; the hook only calls it
|
|
81
|
+
class Invoice:
|
|
82
|
+
def ensure_valid_amount(self) -> None:
|
|
83
|
+
if self.amount < 0:
|
|
84
|
+
raise InvoiceError("Invoice amount cannot be negative")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def validate_amount(ctx):
|
|
88
|
+
"""Rebutja factures amb import negatiu."""
|
|
89
|
+
ctx.entity.ensure_valid_amount()
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Raise a `DomainError` subclass (HTTP 422 with your code), not `ValueError`.
|
|
93
|
+
|
|
94
|
+
## 5. A business process written as a hook chain
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
# Wrong: approving creates a payment from inside a hook
|
|
98
|
+
@hook.after("transition:approve")
|
|
99
|
+
def create_payment(ctx):
|
|
100
|
+
ctx.repository("payments").add(Payment(invoice_id=ctx.entity.id))
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
# Right: a process reacting to the approval; its writes go through the manager
|
|
105
|
+
async def start_payment(step: ProcessStep) -> None:
|
|
106
|
+
"""Quan s'aprova una factura, comença a esperar-ne el cobrament."""
|
|
107
|
+
invoice = await step.manager.get("invoices", step.key, actor=step.actor)
|
|
108
|
+
await step.start({"amount": invoice.amount})
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class InvoicePaymentProcess(Process):
|
|
112
|
+
reacts = [
|
|
113
|
+
On(
|
|
114
|
+
"TransitionExecuted",
|
|
115
|
+
start_payment,
|
|
116
|
+
resource="invoices",
|
|
117
|
+
transition="approve",
|
|
118
|
+
start=True,
|
|
119
|
+
),
|
|
120
|
+
]
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
A write through `ctx.repository("payments")`, from a hook or an action, skips
|
|
124
|
+
the payments' permissions, validation, hooks and audit (`check` RE-C009). Go
|
|
125
|
+
through the manager instead: a process or a consumer of the event, or
|
|
126
|
+
application code calling the manager inside `manager.transaction()`.
|
|
127
|
+
|
|
128
|
+
## 6. Framework imports in the domain
|
|
129
|
+
|
|
130
|
+
```python
|
|
131
|
+
# Wrong (domain/entities.py)
|
|
132
|
+
from pydantic import BaseModel
|
|
133
|
+
from sqlalchemy.orm import Mapped
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
```python
|
|
137
|
+
# Right: plain dataclasses in domain/; Pydantic in application/schemas.py;
|
|
138
|
+
# SQLAlchemy imperative mapping in infrastructure/
|
|
139
|
+
@dataclass
|
|
140
|
+
class Invoice:
|
|
141
|
+
customer: str
|
|
142
|
+
amount: Decimal
|
|
143
|
+
status: str | None = None
|
|
144
|
+
id: int | None = None
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
`check` reports it (RE-C001).
|
|
148
|
+
|
|
149
|
+
## 7. Doing transaction work after commit
|
|
150
|
+
|
|
151
|
+
```python
|
|
152
|
+
# Wrong (after_commit)
|
|
153
|
+
def stamp(ctx):
|
|
154
|
+
ctx.entity.sent_at = datetime.now(UTC) # never saved
|
|
155
|
+
ctx.record_event(InvoiceSent(...)) # lost with the outbox
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
```python
|
|
159
|
+
# Right: before commit
|
|
160
|
+
@hook.after("transition:send")
|
|
161
|
+
def stamp(ctx):
|
|
162
|
+
ctx.entity.sent_at = datetime.now(UTC)
|
|
163
|
+
ctx.record_event(InvoiceSent(invoice_id=ctx.entity.id))
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
`check` reports it (RE-C003).
|
|
167
|
+
|
|
168
|
+
## 8. Writing the database directly
|
|
169
|
+
|
|
170
|
+
```python
|
|
171
|
+
# Wrong: skips validation, permissions, hooks, audit and events
|
|
172
|
+
async with session_factory() as session:
|
|
173
|
+
await session.execute(update(invoices_table).values(amount=0))
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
```python
|
|
177
|
+
# Right
|
|
178
|
+
await manager.update("invoices", invoice_id, {"amount": "0"}, actor=user)
|
|
179
|
+
# several operations together
|
|
180
|
+
async with manager.transaction():
|
|
181
|
+
...
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
Jobs and consumers use `system_principal("job-name")` as the actor.
|
|
185
|
+
|
|
186
|
+
## 9. Tenant filters by hand
|
|
187
|
+
|
|
188
|
+
```python
|
|
189
|
+
# Wrong
|
|
190
|
+
query = ListQuery(filters={"org": user.tenant})
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
```python
|
|
194
|
+
# Right: declare it once; the engine confines every operation
|
|
195
|
+
class LeadResource(Resource):
|
|
196
|
+
access = Access(tenant_field="org")
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
## 10. Undocumented elements
|
|
200
|
+
|
|
201
|
+
A resource, enabled operation, state, transition or action without a
|
|
202
|
+
docstring fails `resource-engine docs validate --strict`. Write the docstring
|
|
203
|
+
with the change, not afterwards ([docstrings.md](docstrings.md)).
|
|
204
|
+
|
|
205
|
+
## 11. Testing with mocks of the engine
|
|
206
|
+
|
|
207
|
+
Don't mock `ResourceManager`, repositories or hooks. Use the real manager on
|
|
208
|
+
`InMemoryStore` ([testing.md](testing.md)); it runs the whole lifecycle in
|
|
209
|
+
milliseconds.
|