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,124 @@
|
|
|
1
|
+
"""Event declaration lint (``resource-engine check``): RE-C006.
|
|
2
|
+
|
|
3
|
+
Hooks and action ``execute`` methods that record a domain event the resource
|
|
4
|
+
does not declare in ``Resource.events``. Undeclared events are still
|
|
5
|
+
published, but they are missing from the generated docs and the AsyncAPI
|
|
6
|
+
document, so consumers cannot know about them.
|
|
7
|
+
|
|
8
|
+
The lint reads ``record_event(EventClass(...))`` calls and resolves the class
|
|
9
|
+
through the function's globals and closure. The engine's own events (created,
|
|
10
|
+
updated, transitions, documents) need no declaration. Helpers defined in the
|
|
11
|
+
application are followed, a few calls deep.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import ast
|
|
17
|
+
import inspect
|
|
18
|
+
import types
|
|
19
|
+
from collections.abc import Callable, Iterator
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from resource_engine import ResourceDefinition, ResourceEvent, ResourceRegistry
|
|
23
|
+
from resource_engine.domain import DomainEvent
|
|
24
|
+
|
|
25
|
+
from resource_engine_devtools.check import Violation
|
|
26
|
+
from resource_engine_devtools.hooks_check import (
|
|
27
|
+
_UNRESOLVED,
|
|
28
|
+
MAX_DEPTH,
|
|
29
|
+
_is_application,
|
|
30
|
+
_name,
|
|
31
|
+
_parse,
|
|
32
|
+
_resolve,
|
|
33
|
+
_scope,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
_ENGINE_EVENT_MODULES = (
|
|
37
|
+
"resource_engine.application.events",
|
|
38
|
+
"resource_engine.documents.events",
|
|
39
|
+
"resource_engine.email",
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def check_events(registry: ResourceRegistry) -> list[Violation]:
|
|
44
|
+
"""RE-C006: domain events recorded by hooks or actions that the resource doesn't declare."""
|
|
45
|
+
violations: list[Violation] = []
|
|
46
|
+
for definition in registry:
|
|
47
|
+
if definition.resource_cls.__module__.startswith("resource_engine."):
|
|
48
|
+
continue # the engine's built-in resources
|
|
49
|
+
declared = set(definition.events)
|
|
50
|
+
seen: set[tuple[str, int]] = set()
|
|
51
|
+
for fn, extra, where in _code(definition):
|
|
52
|
+
for path, line, event, chain in _recorded(fn, depth=0, visited=set(), extra=extra):
|
|
53
|
+
if event in declared or _is_engine_event(event) or (path, line) in seen:
|
|
54
|
+
continue
|
|
55
|
+
seen.add((path, line))
|
|
56
|
+
via = f" (via {' → '.join(chain)})" if chain else ""
|
|
57
|
+
violations.append(
|
|
58
|
+
Violation(
|
|
59
|
+
code="RE-C006",
|
|
60
|
+
path=path,
|
|
61
|
+
line=line,
|
|
62
|
+
message=f"{_name(fn)} ({where}) records {event.__name__}, which "
|
|
63
|
+
f"{definition.name} does not declare{via}",
|
|
64
|
+
hint=f"Add {event.__name__} to {definition.resource_cls.__name__}.events "
|
|
65
|
+
"so the docs and the AsyncAPI document list it.",
|
|
66
|
+
)
|
|
67
|
+
)
|
|
68
|
+
return violations
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _code(
|
|
72
|
+
definition: ResourceDefinition,
|
|
73
|
+
) -> Iterator[tuple[Callable[..., Any], dict[str, Any] | None, str]]:
|
|
74
|
+
for key, hooks in definition.hooks.items():
|
|
75
|
+
for hook in hooks:
|
|
76
|
+
yield hook, None, f"{definition.name} {key}"
|
|
77
|
+
for action in definition.actions.values():
|
|
78
|
+
execute = getattr(action.action_cls, "execute", None)
|
|
79
|
+
if execute is not None:
|
|
80
|
+
yield (
|
|
81
|
+
execute,
|
|
82
|
+
{"self": action.action_cls},
|
|
83
|
+
f"{definition.name} action {action.name}",
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _is_engine_event(event: type) -> bool:
|
|
88
|
+
return event.__module__ in _ENGINE_EVENT_MODULES or (
|
|
89
|
+
issubclass(event, ResourceEvent) and event.__module__.startswith("resource_engine.")
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _recorded(
|
|
94
|
+
fn: Callable[..., Any], *, depth: int, visited: set[int], extra: dict[str, Any] | None
|
|
95
|
+
) -> Iterator[tuple[str, int, type, list[str]]]:
|
|
96
|
+
fn = inspect.unwrap(fn)
|
|
97
|
+
if id(fn) in visited or depth > MAX_DEPTH:
|
|
98
|
+
return
|
|
99
|
+
visited.add(id(fn))
|
|
100
|
+
parsed = _parse(fn)
|
|
101
|
+
if parsed is None:
|
|
102
|
+
return
|
|
103
|
+
tree, path, first_line = parsed
|
|
104
|
+
scope = _scope(fn) | (extra or {})
|
|
105
|
+
for node in ast.walk(tree):
|
|
106
|
+
if not isinstance(node, ast.Call):
|
|
107
|
+
continue
|
|
108
|
+
line = first_line + node.lineno - 1
|
|
109
|
+
if isinstance(node.func, ast.Attribute) and node.func.attr == "record_event":
|
|
110
|
+
for arg in node.args[:1]:
|
|
111
|
+
if isinstance(arg, ast.Call):
|
|
112
|
+
event = _resolve(arg.func, scope)
|
|
113
|
+
if isinstance(event, type) and issubclass(event, DomainEvent):
|
|
114
|
+
yield path, line, event, []
|
|
115
|
+
continue
|
|
116
|
+
target = _resolve(node.func, scope)
|
|
117
|
+
if target is _UNRESOLVED:
|
|
118
|
+
continue
|
|
119
|
+
if isinstance(target, types.FunctionType | types.MethodType) and _is_application(target):
|
|
120
|
+
inner = {"self": extra["self"]} if extra and "self" in extra else None
|
|
121
|
+
for inner_path, inner_line, event, chain in _recorded(
|
|
122
|
+
target, depth=depth + 1, visited=visited, extra=inner
|
|
123
|
+
):
|
|
124
|
+
yield inner_path, inner_line, event, [_name(target), *chain]
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""Gate lints (``resource-engine check``): RE-C004 and RE-C005.
|
|
2
|
+
|
|
3
|
+
- **RE-C004**: an enabled operation of the application (CRUD, transition,
|
|
4
|
+
action, document) that only a catch-all system role can perform. No other
|
|
5
|
+
system role and no policy of the seed grants it, so in practice only
|
|
6
|
+
``admin`` can use it. The seed is the list of policies the application
|
|
7
|
+
creates (``[tool.resource-engine] policies = "pkg.authz:SEED_POLICIES"``);
|
|
8
|
+
without it the rule is skipped. Conditions are ignored: a conditional grant
|
|
9
|
+
is still a gate.
|
|
10
|
+
- **RE-C005**: the registry could not be loaded because the engine refused a
|
|
11
|
+
declaration (a state field in a create schema, a bad hook point...). It is
|
|
12
|
+
reported with the engine's code and hint, at the line of the application code
|
|
13
|
+
that triggered it.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import importlib
|
|
19
|
+
import inspect
|
|
20
|
+
import traceback
|
|
21
|
+
from collections.abc import Iterable, Mapping
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from resource_engine import ResourceRegistry
|
|
26
|
+
from resource_engine.authz import Catalog, action_matches
|
|
27
|
+
from resource_engine.errors import ResourceEngineError
|
|
28
|
+
from resource_engine.integration import FIELD_KINDS
|
|
29
|
+
|
|
30
|
+
from resource_engine_devtools.check import Violation
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def load_policies(spec: str | Iterable[str]) -> list[Mapping[str, Any]]:
|
|
34
|
+
"""``module:attribute`` (or several) naming lists of policies: dicts as
|
|
35
|
+
sent to ``authz_policies``, or ``Policy`` objects."""
|
|
36
|
+
specs = [spec] if isinstance(spec, str) else list(spec)
|
|
37
|
+
policies: list[Mapping[str, Any]] = []
|
|
38
|
+
for item in specs:
|
|
39
|
+
module_name, _, attr = str(item).partition(":")
|
|
40
|
+
value = getattr(importlib.import_module(module_name), attr or "SEED_POLICIES")
|
|
41
|
+
for policy in value:
|
|
42
|
+
policies.append(policy if isinstance(policy, Mapping) else vars(policy))
|
|
43
|
+
return policies
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def check_gates(
|
|
47
|
+
registry: ResourceRegistry, authz: Any, policies: list[Mapping[str, Any]]
|
|
48
|
+
) -> list[Violation]:
|
|
49
|
+
"""RE-C004: enabled operations that only a catch-all system role can perform."""
|
|
50
|
+
catalog = Catalog.from_registry(registry)
|
|
51
|
+
roles = list(getattr(authz, "system_roles", ()) or ())
|
|
52
|
+
catch_all = {r.name for r in roles if "*" in r.grants}
|
|
53
|
+
gates = [r for r in roles if r.name not in catch_all]
|
|
54
|
+
allows = [p for p in policies if p.get("effect") == "allow" and p.get("enabled", True)]
|
|
55
|
+
violations: list[Violation] = []
|
|
56
|
+
for info in catalog.actions.values():
|
|
57
|
+
if info.kind in FIELD_KINDS or info.resource not in registry:
|
|
58
|
+
continue
|
|
59
|
+
definition = registry.get(info.resource)
|
|
60
|
+
if definition.resource_cls.__module__.startswith("resource_engine."):
|
|
61
|
+
continue # built-in resources (authz_*, audit_log, documents)
|
|
62
|
+
operation = info.name.split(":", 1)[1]
|
|
63
|
+
if info.kind == "crud" and operation in definition.internal_operations:
|
|
64
|
+
continue # run by code (processes, jobs), not by callers
|
|
65
|
+
if info.kind == "transition" and not definition.expose_transitions:
|
|
66
|
+
continue
|
|
67
|
+
granted = any(
|
|
68
|
+
action_matches(
|
|
69
|
+
g,
|
|
70
|
+
info.name,
|
|
71
|
+
wildcards=info.wildcards or role.include_sensitive,
|
|
72
|
+
exact=info.exact,
|
|
73
|
+
)
|
|
74
|
+
for role in gates
|
|
75
|
+
for g in role.grants
|
|
76
|
+
) or any(
|
|
77
|
+
action_matches(pattern, info.name, wildcards=info.wildcards, exact=info.exact)
|
|
78
|
+
for policy in allows
|
|
79
|
+
for pattern in policy.get("actions", ())
|
|
80
|
+
)
|
|
81
|
+
if granted:
|
|
82
|
+
continue
|
|
83
|
+
path, line = _location(definition.resource_cls)
|
|
84
|
+
only = ", ".join(sorted(catch_all)) or "nobody"
|
|
85
|
+
violations.append(
|
|
86
|
+
Violation(
|
|
87
|
+
code="RE-C004",
|
|
88
|
+
path=path,
|
|
89
|
+
line=line,
|
|
90
|
+
message=f"{info.name} is enabled but only {only} can perform it: no other "
|
|
91
|
+
"system role and no seed policy grants it",
|
|
92
|
+
hint="Add a policy to the seed, grant it to a system role, or remove the "
|
|
93
|
+
"operation (operations, transitions, actions or document slots).",
|
|
94
|
+
)
|
|
95
|
+
)
|
|
96
|
+
return violations
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def load_error(exc: ResourceEngineError) -> Violation:
|
|
100
|
+
"""RE-C005: a refused declaration, reported at the line of the application's code."""
|
|
101
|
+
path, line = _user_frame(exc)
|
|
102
|
+
return Violation(
|
|
103
|
+
code="RE-C005",
|
|
104
|
+
path=path,
|
|
105
|
+
line=line,
|
|
106
|
+
message=f"the registry could not be loaded: {exc.code} {exc.message}",
|
|
107
|
+
hint=exc.hint or f"See {exc.doc}",
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _location(cls: type) -> tuple[str, int]:
|
|
112
|
+
try:
|
|
113
|
+
return inspect.getsourcefile(cls) or "?", inspect.getsourcelines(cls)[1]
|
|
114
|
+
except (OSError, TypeError):
|
|
115
|
+
return "?", 0
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _user_frame(exc: BaseException) -> tuple[str, int]:
|
|
119
|
+
"""The innermost frame of the application (not the engine, not installed
|
|
120
|
+
packages, not the import machinery)."""
|
|
121
|
+
found = ("?", 0)
|
|
122
|
+
for frame in traceback.extract_tb(exc.__traceback__):
|
|
123
|
+
name = Path(frame.filename).as_posix()
|
|
124
|
+
if (
|
|
125
|
+
"/resource_engine/" in name
|
|
126
|
+
or "/resource_engine_devtools/" in name
|
|
127
|
+
or "site-packages" in name
|
|
128
|
+
or name.startswith("<")
|
|
129
|
+
or "importlib" in name
|
|
130
|
+
):
|
|
131
|
+
continue
|
|
132
|
+
found = (frame.filename, frame.lineno or 0)
|
|
133
|
+
return found
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
"""Hook/effect lints (``resource-engine check``): RE-C002 and RE-C003.
|
|
2
|
+
|
|
3
|
+
- **RE-C002**: code that runs inside the transaction (hooks before
|
|
4
|
+
``after_commit``, action ``execute`` methods) reaches an external effect:
|
|
5
|
+
a function marked ``@external_effect``, or a network, e-mail or cloud client
|
|
6
|
+
(``httpx``, ``requests``, ``smtplib``, ``boto3``...). The effect happens even
|
|
7
|
+
if the operation then rolls back. Helpers defined in the application are
|
|
8
|
+
followed, a few calls deep.
|
|
9
|
+
- **RE-C003**: an ``after_commit`` hook does work that needs the transaction,
|
|
10
|
+
which has already ended: recording events (the outbox has been written),
|
|
11
|
+
using ``ctx.repository()`` / ``ctx.uow``, registering ``on_rollback``, or
|
|
12
|
+
changing ``ctx.entity`` (the change is never saved).
|
|
13
|
+
|
|
14
|
+
The analysis reads source code and resolves names through the function's
|
|
15
|
+
globals and closure. Calls through objects it cannot resolve (``ctx.services``,
|
|
16
|
+
parameters) are not followed.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import ast
|
|
22
|
+
import inspect
|
|
23
|
+
import sysconfig
|
|
24
|
+
import textwrap
|
|
25
|
+
import types
|
|
26
|
+
from collections.abc import Callable, Iterator
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from typing import Any, TypeGuard
|
|
29
|
+
|
|
30
|
+
from resource_engine import HookPoint, ResourceRegistry
|
|
31
|
+
from resource_engine.integration import has_external_effect
|
|
32
|
+
|
|
33
|
+
from resource_engine_devtools.check import Violation
|
|
34
|
+
|
|
35
|
+
#: Modules whose use inside a transaction is an external effect.
|
|
36
|
+
IO_MODULES = (
|
|
37
|
+
"httpx",
|
|
38
|
+
"requests",
|
|
39
|
+
"aiohttp",
|
|
40
|
+
"urllib.request",
|
|
41
|
+
"urllib3",
|
|
42
|
+
"smtplib",
|
|
43
|
+
"aiosmtplib",
|
|
44
|
+
"boto3",
|
|
45
|
+
"botocore",
|
|
46
|
+
"aiobotocore",
|
|
47
|
+
"aioboto3",
|
|
48
|
+
"google.cloud",
|
|
49
|
+
"azure",
|
|
50
|
+
"aio_pika",
|
|
51
|
+
"pika",
|
|
52
|
+
"kafka",
|
|
53
|
+
"aiokafka",
|
|
54
|
+
"grpc",
|
|
55
|
+
"paramiko",
|
|
56
|
+
"ftplib",
|
|
57
|
+
"socket",
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
MAX_DEPTH = 3
|
|
61
|
+
|
|
62
|
+
_STDLIB = (Path(sysconfig.get_paths()["stdlib"]).resolve(),)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def check_hooks(registry: ResourceRegistry) -> list[Violation]:
|
|
66
|
+
"""RE-C002 and RE-C003: external effects inside the transaction, and after-commit hooks that
|
|
67
|
+
write."""
|
|
68
|
+
violations: list[Violation] = []
|
|
69
|
+
for definition in registry:
|
|
70
|
+
for key, hooks in definition.hooks.items():
|
|
71
|
+
for hook in hooks:
|
|
72
|
+
where = f"{definition.name} {key}"
|
|
73
|
+
if key.point is HookPoint.AFTER_COMMIT:
|
|
74
|
+
violations += _after_commit(hook, where)
|
|
75
|
+
else:
|
|
76
|
+
violations += _in_transaction(hook, where)
|
|
77
|
+
for action in definition.actions.values():
|
|
78
|
+
execute = getattr(action.action_cls, "execute", None)
|
|
79
|
+
if execute is not None:
|
|
80
|
+
where = f"{definition.name} action {action.name}"
|
|
81
|
+
violations += _in_transaction(execute, where, {"self": action.action_cls})
|
|
82
|
+
return violations
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
# ------------------------------------------------------------------ RE-C002
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _in_transaction(
|
|
89
|
+
fn: Callable[..., Any], where: str, extra: dict[str, Any] | None = None
|
|
90
|
+
) -> list[Violation]:
|
|
91
|
+
found = next(_effects(fn, depth=0, seen=set(), extra=extra), None)
|
|
92
|
+
if found is None:
|
|
93
|
+
return []
|
|
94
|
+
path, line, effect, chain = found
|
|
95
|
+
via = f" (via {' → '.join(chain)})" if chain else ""
|
|
96
|
+
return [
|
|
97
|
+
Violation(
|
|
98
|
+
code="RE-C002",
|
|
99
|
+
path=path,
|
|
100
|
+
line=line,
|
|
101
|
+
message=f"{_name(fn)} runs inside the transaction ({where}) and {effect}{via}",
|
|
102
|
+
hint="Move the effect to an after_commit hook or a consumer of a domain event, "
|
|
103
|
+
"or stage it with ctx.on_rollback if it can be undone.",
|
|
104
|
+
)
|
|
105
|
+
]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _effects(
|
|
109
|
+
fn: Callable[..., Any], *, depth: int, seen: set[int], extra: dict[str, Any] | None = None
|
|
110
|
+
) -> Iterator[tuple[str, int, str, list[str]]]:
|
|
111
|
+
fn = inspect.unwrap(fn)
|
|
112
|
+
if id(fn) in seen or depth > MAX_DEPTH:
|
|
113
|
+
return
|
|
114
|
+
seen.add(id(fn))
|
|
115
|
+
parsed = _parse(fn)
|
|
116
|
+
if parsed is None:
|
|
117
|
+
return
|
|
118
|
+
tree, path, first_line = parsed
|
|
119
|
+
scope = _scope(fn) | (extra or {})
|
|
120
|
+
for node in ast.walk(tree):
|
|
121
|
+
if not isinstance(node, ast.Call):
|
|
122
|
+
continue
|
|
123
|
+
target = _resolve(node.func, scope)
|
|
124
|
+
if target is _UNRESOLVED:
|
|
125
|
+
continue
|
|
126
|
+
line = first_line + node.lineno - 1
|
|
127
|
+
if callable(target) and has_external_effect(target):
|
|
128
|
+
yield path, line, f"calls {_name(target)}, marked @external_effect", []
|
|
129
|
+
continue
|
|
130
|
+
module = _module_of(target)
|
|
131
|
+
if module and _is_io(module):
|
|
132
|
+
yield path, line, f"uses {module} ({ast.unparse(node.func)})", []
|
|
133
|
+
continue
|
|
134
|
+
if isinstance(target, types.FunctionType | types.MethodType) and _is_application(target):
|
|
135
|
+
inner_extra = {"self": extra["self"]} if extra and "self" in extra else None
|
|
136
|
+
for inner_path, inner_line, effect, chain in _effects(
|
|
137
|
+
target, depth=depth + 1, seen=seen, extra=inner_extra
|
|
138
|
+
):
|
|
139
|
+
yield inner_path, inner_line, effect, [_name(target), *chain]
|
|
140
|
+
return
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
# ------------------------------------------------------------------ RE-C003
|
|
144
|
+
|
|
145
|
+
_NEEDS_TRANSACTION = {
|
|
146
|
+
"record_event": "records an event after the outbox was written",
|
|
147
|
+
"repository": "uses ctx.repository() after the transaction ended",
|
|
148
|
+
"on_rollback": "registers a compensation that can no longer run",
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _after_commit(fn: Callable[..., Any], where: str) -> list[Violation]:
|
|
153
|
+
fn = inspect.unwrap(fn)
|
|
154
|
+
parsed = _parse(fn)
|
|
155
|
+
if parsed is None:
|
|
156
|
+
return []
|
|
157
|
+
tree, path, first_line = parsed
|
|
158
|
+
func = next(
|
|
159
|
+
(n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef | ast.AsyncFunctionDef)),
|
|
160
|
+
None,
|
|
161
|
+
)
|
|
162
|
+
if func is None or not func.args.args:
|
|
163
|
+
return []
|
|
164
|
+
params = [a.arg for a in func.args.args]
|
|
165
|
+
ctx = params[1] if params[0] in ("self", "cls") and len(params) > 1 else params[0]
|
|
166
|
+
violations = []
|
|
167
|
+
for node in ast.walk(func):
|
|
168
|
+
problem = None
|
|
169
|
+
if isinstance(node, ast.Call) and _is_attr_of(node.func, ctx):
|
|
170
|
+
problem = _NEEDS_TRANSACTION.get(node.func.attr)
|
|
171
|
+
elif isinstance(node, ast.Attribute) and _is_attr_of(node, ctx) and node.attr == "uow":
|
|
172
|
+
problem = "uses ctx.uow after the transaction ended"
|
|
173
|
+
elif isinstance(node, ast.Assign | ast.AugAssign | ast.AnnAssign):
|
|
174
|
+
targets = node.targets if isinstance(node, ast.Assign) else [node.target]
|
|
175
|
+
if any(_changes_entity(t, ctx) for t in targets):
|
|
176
|
+
problem = "changes ctx.entity, which is never saved after commit"
|
|
177
|
+
if problem:
|
|
178
|
+
violations.append(
|
|
179
|
+
Violation(
|
|
180
|
+
code="RE-C003",
|
|
181
|
+
path=path,
|
|
182
|
+
line=first_line + getattr(node, "lineno", 1) - 1,
|
|
183
|
+
message=f"{_name(fn)} ({where}) {problem}",
|
|
184
|
+
hint="Do this in a hook before commit (after_create, after_update, "
|
|
185
|
+
"after_transition...), or start a new operation through the manager.",
|
|
186
|
+
)
|
|
187
|
+
)
|
|
188
|
+
return violations
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _is_attr_of(node: ast.AST, name: str) -> TypeGuard[ast.Attribute]:
|
|
192
|
+
return (
|
|
193
|
+
isinstance(node, ast.Attribute)
|
|
194
|
+
and isinstance(node.value, ast.Name)
|
|
195
|
+
and node.value.id == name
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _changes_entity(target: ast.AST, ctx: str) -> bool:
|
|
200
|
+
return (
|
|
201
|
+
isinstance(target, ast.Attribute | ast.Subscript)
|
|
202
|
+
and _is_attr_of(target.value, ctx)
|
|
203
|
+
and (target.value.attr == "entity")
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
# ------------------------------------------------------------------ helpers
|
|
208
|
+
|
|
209
|
+
_UNRESOLVED = object()
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _parse(fn: Callable[..., Any]) -> tuple[ast.AST, str, int] | None:
|
|
213
|
+
try:
|
|
214
|
+
lines, first_line = inspect.getsourcelines(fn)
|
|
215
|
+
path = inspect.getsourcefile(fn) or "?"
|
|
216
|
+
except (OSError, TypeError):
|
|
217
|
+
return None
|
|
218
|
+
try:
|
|
219
|
+
return ast.parse(textwrap.dedent("".join(lines))), path, first_line
|
|
220
|
+
except SyntaxError: # e.g. a lambda in the middle of an expression
|
|
221
|
+
return None
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _scope(fn: Callable[..., Any]) -> dict[str, Any]:
|
|
225
|
+
scope = dict(getattr(fn, "__globals__", {}))
|
|
226
|
+
try:
|
|
227
|
+
closure = inspect.getclosurevars(fn)
|
|
228
|
+
except (TypeError, ValueError):
|
|
229
|
+
return scope
|
|
230
|
+
scope.update(closure.nonlocals)
|
|
231
|
+
return scope
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _resolve(node: ast.AST, scope: dict[str, Any]) -> Any:
|
|
235
|
+
"""The object a dotted name refers to, rooted at globals/closure."""
|
|
236
|
+
parts: list[str] = []
|
|
237
|
+
while isinstance(node, ast.Attribute):
|
|
238
|
+
parts.append(node.attr)
|
|
239
|
+
node = node.value
|
|
240
|
+
if isinstance(node, ast.Call): # httpx.AsyncClient().post → the constructor call
|
|
241
|
+
return _UNRESOLVED
|
|
242
|
+
if not isinstance(node, ast.Name) or node.id not in scope:
|
|
243
|
+
return _UNRESOLVED
|
|
244
|
+
value = scope[node.id]
|
|
245
|
+
for part in reversed(parts):
|
|
246
|
+
try:
|
|
247
|
+
value = inspect.getattr_static(value, part)
|
|
248
|
+
except AttributeError:
|
|
249
|
+
try:
|
|
250
|
+
value = getattr(value, part)
|
|
251
|
+
except Exception:
|
|
252
|
+
return _UNRESOLVED
|
|
253
|
+
if isinstance(value, staticmethod | classmethod):
|
|
254
|
+
value = value.__func__
|
|
255
|
+
return value
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _module_of(value: Any) -> str | None:
|
|
259
|
+
if isinstance(value, types.ModuleType):
|
|
260
|
+
return value.__name__
|
|
261
|
+
module = getattr(value, "__module__", None)
|
|
262
|
+
if isinstance(module, str):
|
|
263
|
+
return module
|
|
264
|
+
return type(value).__module__
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _is_io(module: str) -> bool:
|
|
268
|
+
return any(module == m or module.startswith(f"{m}.") for m in IO_MODULES)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _is_application(fn: Callable[..., Any]) -> bool:
|
|
272
|
+
"""Defined in the application: not the engine, the standard library or an
|
|
273
|
+
installed package."""
|
|
274
|
+
if (getattr(fn, "__module__", "") or "").startswith("resource_engine"):
|
|
275
|
+
return False
|
|
276
|
+
try:
|
|
277
|
+
path = Path(inspect.getsourcefile(fn) or "").resolve()
|
|
278
|
+
except (OSError, TypeError):
|
|
279
|
+
return False
|
|
280
|
+
text = str(path)
|
|
281
|
+
if "site-packages" in text or "dist-packages" in text:
|
|
282
|
+
return False
|
|
283
|
+
return not any(path.is_relative_to(root) for root in _STDLIB)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _name(fn: Any) -> str:
|
|
287
|
+
return getattr(fn, "__qualname__", None) or getattr(fn, "__name__", None) or repr(fn)
|