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,637 @@
|
|
|
1
|
+
"""``resource-engine scaffold hook|event|slot|reference|policy``: the remaining
|
|
2
|
+
functional elements of an existing module, written and declared on the
|
|
3
|
+
resource in one step.
|
|
4
|
+
|
|
5
|
+
Each command writes its code (a hook function, an event class, a seed policy)
|
|
6
|
+
and edits the resource class so the element is registered: the module keeps
|
|
7
|
+
importing, registering and passing ``check``. Edits add lines and keep
|
|
8
|
+
comments (``source_edit``); names that already exist are refused.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import ast
|
|
14
|
+
import importlib
|
|
15
|
+
import re
|
|
16
|
+
import sys
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from resource_engine_devtools import source_edit as edit
|
|
20
|
+
from resource_engine_devtools.scaffold import (
|
|
21
|
+
TYPES,
|
|
22
|
+
Field,
|
|
23
|
+
Result,
|
|
24
|
+
ScaffoldError,
|
|
25
|
+
_existing,
|
|
26
|
+
_identifier,
|
|
27
|
+
_render,
|
|
28
|
+
pascal,
|
|
29
|
+
singular,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
HOOK_POINTS = (
|
|
33
|
+
"before_validate",
|
|
34
|
+
"after_validate",
|
|
35
|
+
"before_create",
|
|
36
|
+
"after_create",
|
|
37
|
+
"before_update",
|
|
38
|
+
"after_update",
|
|
39
|
+
"before_delete",
|
|
40
|
+
"after_delete",
|
|
41
|
+
"before_transition",
|
|
42
|
+
"after_transition",
|
|
43
|
+
"before_action",
|
|
44
|
+
"after_action",
|
|
45
|
+
"before_attach",
|
|
46
|
+
"after_attach",
|
|
47
|
+
"before_detach",
|
|
48
|
+
"after_detach",
|
|
49
|
+
"after_commit",
|
|
50
|
+
)
|
|
51
|
+
QUALIFIABLE = {
|
|
52
|
+
p for p in HOOK_POINTS if p.endswith(("_transition", "_action", "_attach", "_detach"))
|
|
53
|
+
}
|
|
54
|
+
ON_DELETE = ("restrict", "set_null", "cascade")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
# ----------------------------------------------------------- the resource
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class _ResourceFile:
|
|
61
|
+
"""The module file declaring a resource, edited in memory and written once."""
|
|
62
|
+
|
|
63
|
+
def __init__(self, base: Path, package: str, resource: str) -> None:
|
|
64
|
+
self.package = package
|
|
65
|
+
self.resource = resource
|
|
66
|
+
found = []
|
|
67
|
+
for path in sorted((base / "application").glob("*.py")):
|
|
68
|
+
source = path.read_text(encoding="utf-8")
|
|
69
|
+
for cls in ast.parse(source).body:
|
|
70
|
+
if isinstance(cls, ast.ClassDef) and _declares(cls, resource):
|
|
71
|
+
found.append((path, cls.name, source))
|
|
72
|
+
if not found:
|
|
73
|
+
raise ScaffoldError(
|
|
74
|
+
f"No Resource for {resource!r} in {base / 'application'} "
|
|
75
|
+
"(a class with name = ... or the default name)"
|
|
76
|
+
)
|
|
77
|
+
self.path, self.class_name, self.source = found[0]
|
|
78
|
+
self.module = f"{package}.application.{self.path.stem}"
|
|
79
|
+
|
|
80
|
+
def attribute(self, attr: str) -> ast.expr | None:
|
|
81
|
+
return edit.attribute_value(self.source, self.class_name, attr)
|
|
82
|
+
|
|
83
|
+
def hooks_style(self) -> str:
|
|
84
|
+
"""How the resource lists hooks: ``dict`` (points to functions), ``module``
|
|
85
|
+
(``hooks = [hooks]``: every marked function), or ``list`` (each function)."""
|
|
86
|
+
value = self.attribute("hooks")
|
|
87
|
+
if isinstance(value, ast.Dict):
|
|
88
|
+
return "dict"
|
|
89
|
+
if isinstance(value, ast.List | ast.Tuple) and any(
|
|
90
|
+
isinstance(e, ast.Name) and e.id == "hooks" for e in value.elts
|
|
91
|
+
):
|
|
92
|
+
return "module"
|
|
93
|
+
return "list"
|
|
94
|
+
|
|
95
|
+
def apply(self, change) -> None: # type: ignore[no-untyped-def]
|
|
96
|
+
try:
|
|
97
|
+
self.source = change(self.source)
|
|
98
|
+
except edit.EditError as exc:
|
|
99
|
+
raise ScaffoldError(f"{self.path}: {exc}") from None
|
|
100
|
+
|
|
101
|
+
def write(self, result: Result, *, dry_run: bool) -> None:
|
|
102
|
+
_save(self.path, self.source, result, dry_run=dry_run)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _declares(cls: ast.ClassDef, resource: str) -> bool:
|
|
106
|
+
if not any(_base_name(b).endswith("Resource") for b in cls.bases):
|
|
107
|
+
return False
|
|
108
|
+
attr = edit.class_attribute(cls, "name")
|
|
109
|
+
if attr is not None and isinstance(attr.value, ast.Constant):
|
|
110
|
+
return attr.value.value == resource
|
|
111
|
+
base = cls.name.removesuffix("Resource") or cls.name
|
|
112
|
+
snake = re.sub(r"(?<!^)(?=[A-Z])", "_", base).lower()
|
|
113
|
+
return (snake if snake.endswith("s") else f"{snake}s") == resource
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _base_name(node: ast.expr) -> str:
|
|
117
|
+
if isinstance(node, ast.Name):
|
|
118
|
+
return node.id
|
|
119
|
+
if isinstance(node, ast.Attribute):
|
|
120
|
+
return node.attr
|
|
121
|
+
return ""
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _save(path: Path, content: str, result: Result, *, dry_run: bool) -> None:
|
|
125
|
+
result.written.append(str(path))
|
|
126
|
+
if not dry_run:
|
|
127
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
128
|
+
path.write_text(content, encoding="utf-8")
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _read(path: Path, default: str) -> str:
|
|
132
|
+
return path.read_text(encoding="utf-8") if path.exists() else default
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _string(value: str) -> str:
|
|
136
|
+
return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
# ------------------------------------------------------------------- hook
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def hook(
|
|
143
|
+
root: Path,
|
|
144
|
+
package: str,
|
|
145
|
+
resource: str,
|
|
146
|
+
function: str,
|
|
147
|
+
points: list[str],
|
|
148
|
+
*,
|
|
149
|
+
effect: bool = False,
|
|
150
|
+
dry_run: bool = False,
|
|
151
|
+
) -> Result:
|
|
152
|
+
"""A hook function in ``application/hooks.py``, run at ``points``."""
|
|
153
|
+
_identifier(function, "hook function")
|
|
154
|
+
if not points:
|
|
155
|
+
raise ScaffoldError("Name at least one point with --on (before_create, after_commit...)")
|
|
156
|
+
for point in points:
|
|
157
|
+
base_point, _, qualifier = point.partition(":")
|
|
158
|
+
if base_point not in HOOK_POINTS:
|
|
159
|
+
raise ScaffoldError(
|
|
160
|
+
f"Unknown hook point {point!r}; use one of: {', '.join(HOOK_POINTS)}"
|
|
161
|
+
)
|
|
162
|
+
if qualifier and base_point not in QUALIFIABLE:
|
|
163
|
+
raise ScaffoldError(f"{base_point} takes no qualifier")
|
|
164
|
+
if effect and base_point != "after_commit":
|
|
165
|
+
raise ScaffoldError(
|
|
166
|
+
"External effects run after the commit: use --on after_commit with --effect "
|
|
167
|
+
"(an effect inside the transaction is RE-C002)"
|
|
168
|
+
)
|
|
169
|
+
base = _existing(root, package)
|
|
170
|
+
target = _ResourceFile(base, package, resource)
|
|
171
|
+
path = base / "application/hooks.py"
|
|
172
|
+
source = _read(
|
|
173
|
+
path,
|
|
174
|
+
'"""Hooks: the rules that run around the resource\'s operations."""\n\n'
|
|
175
|
+
"from __future__ import annotations\n\nfrom resource_engine import OperationContext\n",
|
|
176
|
+
)
|
|
177
|
+
if edit.defines(source, function):
|
|
178
|
+
raise ScaffoldError(f"{path} already defines {function}")
|
|
179
|
+
source = edit.add_import(source, "resource_engine", "OperationContext")
|
|
180
|
+
marked = target.hooks_style() != "dict"
|
|
181
|
+
if marked:
|
|
182
|
+
source = edit.add_import(source, "resource_engine", "hook")
|
|
183
|
+
asynchronous = effect or any(p.startswith("after_commit") for p in points)
|
|
184
|
+
if effect:
|
|
185
|
+
source = edit.add_import(source, "resource_engine", "external_effect")
|
|
186
|
+
when = ", ".join(points)
|
|
187
|
+
if effect:
|
|
188
|
+
docstring = (
|
|
189
|
+
f'"""TODO: say what happens outside the system after {when}.\n\n'
|
|
190
|
+
' Effects:\n TODO: the external system and what it receives.\n """'
|
|
191
|
+
)
|
|
192
|
+
else:
|
|
193
|
+
docstring = f'"""TODO: say what this checks or changes ({when})."""'
|
|
194
|
+
body = _render(
|
|
195
|
+
"""
|
|
196
|
+
$decorator${prefix}def $function(ctx: OperationContext) -> None:
|
|
197
|
+
$docstring
|
|
198
|
+
""",
|
|
199
|
+
decorator=(_hook_decorators(points) if marked else "")
|
|
200
|
+
+ ("@external_effect\n" if effect else ""),
|
|
201
|
+
prefix="async " if asynchronous else "",
|
|
202
|
+
function=function,
|
|
203
|
+
docstring=docstring,
|
|
204
|
+
)
|
|
205
|
+
source = source.rstrip("\n") + "\n\n\n" + body
|
|
206
|
+
result = Result()
|
|
207
|
+
_save(path, source, result, dry_run=dry_run)
|
|
208
|
+
target.apply(lambda s: edit.add_import(s, f"{package}.application", "hooks"))
|
|
209
|
+
if not marked:
|
|
210
|
+
for point in points:
|
|
211
|
+
target.apply(
|
|
212
|
+
lambda s, p=point: edit.add_to_dict_list(
|
|
213
|
+
s, target.class_name, "hooks", p, f"hooks.{function}"
|
|
214
|
+
)
|
|
215
|
+
)
|
|
216
|
+
elif target.hooks_style() != "module":
|
|
217
|
+
target.apply(
|
|
218
|
+
lambda s: edit.append_to_list(s, target.class_name, "hooks", f"hooks.{function}")
|
|
219
|
+
)
|
|
220
|
+
target.write(result, dry_run=dry_run)
|
|
221
|
+
result.next_steps = [
|
|
222
|
+
f"Implement {function} in {path} and replace its TODO docstring",
|
|
223
|
+
"Hooks before the commit run inside the transaction: raise a DomainError to refuse"
|
|
224
|
+
+ (
|
|
225
|
+
"; external calls belong in after_commit hooks marked @external_effect"
|
|
226
|
+
if not effect
|
|
227
|
+
else ""
|
|
228
|
+
),
|
|
229
|
+
]
|
|
230
|
+
return result
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _hook_decorators(points: list[str]) -> str:
|
|
234
|
+
"""``@hook.before("create", "update")`` lines for hook points, as written."""
|
|
235
|
+
lines: list[str] = []
|
|
236
|
+
grouped: dict[str, list[str]] = {"before": [], "after": []}
|
|
237
|
+
for point in points:
|
|
238
|
+
if point == "after_commit":
|
|
239
|
+
continue
|
|
240
|
+
prefix, _, target = point.partition("_")
|
|
241
|
+
grouped[prefix].append(f'"{target}"')
|
|
242
|
+
for prefix, targets in grouped.items():
|
|
243
|
+
if targets:
|
|
244
|
+
lines.append(f"@hook.{prefix}({', '.join(targets)})\n")
|
|
245
|
+
if "after_commit" in points:
|
|
246
|
+
lines.append("@hook.after_commit\n")
|
|
247
|
+
return "".join(lines)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
# ------------------------------------------------------------------ event
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def event(
|
|
254
|
+
root: Path,
|
|
255
|
+
package: str,
|
|
256
|
+
resource: str,
|
|
257
|
+
class_name: str,
|
|
258
|
+
fields: list[Field],
|
|
259
|
+
*,
|
|
260
|
+
dry_run: bool = False,
|
|
261
|
+
) -> Result:
|
|
262
|
+
"""A domain event in ``domain/events.py``, declared in ``Resource.events``."""
|
|
263
|
+
if not re.fullmatch(r"[A-Z][A-Za-z0-9]*", class_name):
|
|
264
|
+
raise ScaffoldError(f"Invalid event class name {class_name!r}: use PascalCase")
|
|
265
|
+
base = _existing(root, package)
|
|
266
|
+
target = _ResourceFile(base, package, resource)
|
|
267
|
+
path = base / "domain/events.py"
|
|
268
|
+
source = _read(
|
|
269
|
+
path,
|
|
270
|
+
'"""The module\'s domain events."""\n\n'
|
|
271
|
+
"from __future__ import annotations\n\nfrom dataclasses import dataclass\n\n"
|
|
272
|
+
"from resource_engine.domain import DomainEvent\n",
|
|
273
|
+
)
|
|
274
|
+
if edit.defines(source, class_name):
|
|
275
|
+
raise ScaffoldError(f"{path} already defines {class_name}")
|
|
276
|
+
source = edit.add_import(source, "dataclasses", "dataclass")
|
|
277
|
+
source = edit.add_import(source, "resource_engine.domain", "DomainEvent")
|
|
278
|
+
for module, name in sorted({i for f in fields if (i := _type_import(f))}):
|
|
279
|
+
source = edit.add_import(source, module, name)
|
|
280
|
+
entity_id = f"{singular(resource)}_id"
|
|
281
|
+
lines = [f" {entity_id}: int"] + [
|
|
282
|
+
f" {f.name}: {f.annotation}" + (" = None" if f.optional else "")
|
|
283
|
+
for f in fields
|
|
284
|
+
if f.name != entity_id
|
|
285
|
+
]
|
|
286
|
+
body = _render(
|
|
287
|
+
'''
|
|
288
|
+
@dataclass(frozen=True, kw_only=True)
|
|
289
|
+
class $cls(DomainEvent):
|
|
290
|
+
"""TODO: say what happened, in the past tense."""
|
|
291
|
+
|
|
292
|
+
$fields
|
|
293
|
+
''',
|
|
294
|
+
cls=class_name,
|
|
295
|
+
fields="\n".join(lines),
|
|
296
|
+
)
|
|
297
|
+
source = source.rstrip("\n") + "\n\n\n" + body
|
|
298
|
+
result = Result()
|
|
299
|
+
_save(path, source, result, dry_run=dry_run)
|
|
300
|
+
target.apply(lambda s: edit.add_import(s, f"{package}.domain.events", class_name))
|
|
301
|
+
target.apply(lambda s: edit.append_to_list(s, target.class_name, "events", class_name))
|
|
302
|
+
target.write(result, dry_run=dry_run)
|
|
303
|
+
result.next_steps = [
|
|
304
|
+
f"Record it where it happens (an action or a hook): ctx.record_event({class_name}("
|
|
305
|
+
f"{entity_id}=ctx.entity.id, ...))",
|
|
306
|
+
"It is published after the commit with the engine's events and listed in the "
|
|
307
|
+
"AsyncAPI document (resource-engine docs asyncapi)",
|
|
308
|
+
"Replace the TODO docstring: the generated docs and AsyncAPI show it",
|
|
309
|
+
]
|
|
310
|
+
return result
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def _type_import(f: Field) -> tuple[str, str] | None:
|
|
314
|
+
statement = TYPES[f.type][2]
|
|
315
|
+
if statement is None:
|
|
316
|
+
return None
|
|
317
|
+
module, _, name = statement.removeprefix("from ").partition(" import ")
|
|
318
|
+
return module, name
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
# ------------------------------------------------------------------- slot
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def slot(
|
|
325
|
+
root: Path,
|
|
326
|
+
package: str,
|
|
327
|
+
resource: str,
|
|
328
|
+
name: str,
|
|
329
|
+
*,
|
|
330
|
+
content_types: list[str] | None = None,
|
|
331
|
+
max_mb: int | None = None,
|
|
332
|
+
multiple: bool = False,
|
|
333
|
+
upload: str | None = None,
|
|
334
|
+
required_for: list[str] | None = None,
|
|
335
|
+
processing: bool = False,
|
|
336
|
+
dry_run: bool = False,
|
|
337
|
+
) -> Result:
|
|
338
|
+
"""A ``DocumentSlot`` in ``Resource.documents``."""
|
|
339
|
+
_identifier(name, "slot")
|
|
340
|
+
if upload not in (None, "api", "presigned", "any"):
|
|
341
|
+
raise ScaffoldError("--upload must be api, presigned or any")
|
|
342
|
+
base = _existing(root, package)
|
|
343
|
+
target = _ResourceFile(base, package, resource)
|
|
344
|
+
if name in edit.list_call_names(target.attribute("documents"), "DocumentSlot"):
|
|
345
|
+
raise ScaffoldError(f"{resource} already has a {name!r} slot")
|
|
346
|
+
arguments = [_string(name)]
|
|
347
|
+
if content_types:
|
|
348
|
+
arguments.append("content_types=[" + ", ".join(_string(t) for t in content_types) + "]")
|
|
349
|
+
if max_mb:
|
|
350
|
+
arguments.append(f"max_bytes={max_mb} * 1024 * 1024")
|
|
351
|
+
if multiple:
|
|
352
|
+
arguments.append("multiple=True")
|
|
353
|
+
if upload:
|
|
354
|
+
arguments.append(f"upload={_string(upload)}")
|
|
355
|
+
if required_for:
|
|
356
|
+
arguments.append("required_for=[" + ", ".join(_string(t) for t in required_for) + "]")
|
|
357
|
+
if processing:
|
|
358
|
+
arguments.append("processing=True")
|
|
359
|
+
arguments.append('description="TODO: say what goes in this slot."')
|
|
360
|
+
one_line = "DocumentSlot(" + ", ".join(arguments) + ")"
|
|
361
|
+
call = (
|
|
362
|
+
one_line
|
|
363
|
+
if len(one_line) <= 72
|
|
364
|
+
else "DocumentSlot(\n" + "".join(f" {a},\n" for a in arguments) + ")"
|
|
365
|
+
)
|
|
366
|
+
target.apply(lambda s: edit.add_import(s, "resource_engine", "DocumentSlot"))
|
|
367
|
+
target.apply(lambda s: edit.append_to_list(s, target.class_name, "documents", call))
|
|
368
|
+
result = Result()
|
|
369
|
+
target.write(result, dry_run=dry_run)
|
|
370
|
+
result.next_steps = [
|
|
371
|
+
"Give the manager a blob store: ResourceManager(..., blob_store=S3BlobStore(...)) "
|
|
372
|
+
"(InMemoryBlobStore in tests, the module's own included), and register the "
|
|
373
|
+
"documents resource (registry.register_documents())",
|
|
374
|
+
f"Grant it: {resource}:attach:{name}, {resource}:detach:{name}, "
|
|
375
|
+
f"{resource}:download:{name} in a seed policy or a system role",
|
|
376
|
+
f"HTTP: POST /{resource}/{{id}}/documents/{name}, GET /{resource}/{{id}}/documents",
|
|
377
|
+
"Replace the TODO description: the generated docs show it",
|
|
378
|
+
]
|
|
379
|
+
return result
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
# -------------------------------------------------------------- reference
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def reference(
|
|
386
|
+
root: Path,
|
|
387
|
+
package: str,
|
|
388
|
+
resource: str,
|
|
389
|
+
field_name: str,
|
|
390
|
+
to: str,
|
|
391
|
+
*,
|
|
392
|
+
relation: str | None = None,
|
|
393
|
+
on_delete: str = "restrict",
|
|
394
|
+
required: bool = False,
|
|
395
|
+
related_name: str | None = None,
|
|
396
|
+
dry_run: bool = False,
|
|
397
|
+
) -> Result:
|
|
398
|
+
"""A ``Reference`` in ``Resource.references``; the field is added to the
|
|
399
|
+
entity, the schemas and the table when the module doesn't have it."""
|
|
400
|
+
_identifier(field_name, "field")
|
|
401
|
+
_identifier(to, "resource")
|
|
402
|
+
if relation:
|
|
403
|
+
_identifier(relation, "relation")
|
|
404
|
+
if related_name:
|
|
405
|
+
_identifier(related_name, "relation")
|
|
406
|
+
if on_delete not in ON_DELETE:
|
|
407
|
+
raise ScaffoldError(f"--on-delete must be one of: {', '.join(ON_DELETE)}")
|
|
408
|
+
if on_delete == "set_null" and required:
|
|
409
|
+
raise ScaffoldError("set_null needs an optional field (drop --required)")
|
|
410
|
+
base = _existing(root, package)
|
|
411
|
+
target = _ResourceFile(base, package, resource)
|
|
412
|
+
current = target.attribute("references")
|
|
413
|
+
if isinstance(current, ast.Dict) and field_name in edit.dict_keys(current):
|
|
414
|
+
raise ScaffoldError(f"{resource} already references through {field_name!r}")
|
|
415
|
+
result = Result()
|
|
416
|
+
renamed = None
|
|
417
|
+
if relation is None and field_name.removesuffix("_id") in _entity_fields(base, target):
|
|
418
|
+
relation = renamed = field_name.removesuffix("_id") + "_record"
|
|
419
|
+
entity = _added_field(base, package, target, field_name, required, result, dry_run=dry_run)
|
|
420
|
+
arguments = [_string(to)]
|
|
421
|
+
if relation:
|
|
422
|
+
arguments.append(f"name={_string(relation)}")
|
|
423
|
+
if on_delete != "restrict":
|
|
424
|
+
arguments.append(f"on_delete={_string(on_delete)}")
|
|
425
|
+
if related_name:
|
|
426
|
+
arguments.append(f"related_name={_string(related_name)}")
|
|
427
|
+
label = field_name.removesuffix("_id").replace("_", " ")
|
|
428
|
+
arguments.append(f'description="TODO: say what the {label} is to this record."')
|
|
429
|
+
call = "Reference(\n" + "".join(f" {a},\n" for a in arguments) + ")"
|
|
430
|
+
target.apply(lambda s: edit.add_import(s, "resource_engine", "Reference"))
|
|
431
|
+
target.apply(lambda s: edit.add_to_dict(s, target.class_name, "references", field_name, call))
|
|
432
|
+
target.write(result, dry_run=dry_run)
|
|
433
|
+
name = relation or field_name.removesuffix("_id")
|
|
434
|
+
result.next_steps = [
|
|
435
|
+
f"{to!r} must be registered in the same registry, the module's tests included "
|
|
436
|
+
f"(tests/test_{resource}.py registers only {resource})",
|
|
437
|
+
f"Writes check that {field_name} exists in {to} (RE-E108); deleting a referenced "
|
|
438
|
+
f"{singular(to)} is "
|
|
439
|
+
+ {
|
|
440
|
+
"restrict": "refused (RE-E109)",
|
|
441
|
+
"set_null": "allowed and clears the field",
|
|
442
|
+
"cascade": "allowed and deletes these records",
|
|
443
|
+
}[on_delete],
|
|
444
|
+
f"Reads: expand={name}, filters {name}.<field>=...; reverse: GET /{to}/{{id}}/"
|
|
445
|
+
f"{related_name or resource}",
|
|
446
|
+
(f"Add the {field_name} column to your migrations" if entity else "")
|
|
447
|
+
+ ("; update the generated tests, which create records without it" if required else ""),
|
|
448
|
+
"Replace the TODO description: the generated docs show it",
|
|
449
|
+
]
|
|
450
|
+
if renamed:
|
|
451
|
+
result.next_steps.insert(
|
|
452
|
+
0,
|
|
453
|
+
f"The relation is named {renamed!r}: the entity already has a "
|
|
454
|
+
f"{field_name.removesuffix('_id')!r} field (pass --relation to choose another)",
|
|
455
|
+
)
|
|
456
|
+
result.next_steps = [s for s in result.next_steps if s]
|
|
457
|
+
return result
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def _entity_fields(base: Path, target: _ResourceFile) -> list[str]:
|
|
461
|
+
entity = _entity_class(target)
|
|
462
|
+
path = base / "domain/entities.py"
|
|
463
|
+
if entity is None or not path.exists():
|
|
464
|
+
return []
|
|
465
|
+
try:
|
|
466
|
+
return edit.class_fields(path.read_text(encoding="utf-8"), entity)
|
|
467
|
+
except edit.EditError:
|
|
468
|
+
return []
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def _added_field(
|
|
472
|
+
base: Path,
|
|
473
|
+
package: str,
|
|
474
|
+
target: _ResourceFile,
|
|
475
|
+
field_name: str,
|
|
476
|
+
required: bool,
|
|
477
|
+
result: Result,
|
|
478
|
+
*,
|
|
479
|
+
dry_run: bool,
|
|
480
|
+
) -> bool:
|
|
481
|
+
"""Add ``field_name: int`` to the entity, the schemas and the table when
|
|
482
|
+
the scaffolded files are there and lack it. Whether it was added."""
|
|
483
|
+
entities = base / "domain/entities.py"
|
|
484
|
+
schemas = base / "application/schemas.py"
|
|
485
|
+
persistence = base / "infrastructure/persistence.py"
|
|
486
|
+
entity = _entity_class(target)
|
|
487
|
+
if entity is None or not entities.exists():
|
|
488
|
+
return False
|
|
489
|
+
source = entities.read_text(encoding="utf-8")
|
|
490
|
+
try:
|
|
491
|
+
if field_name in edit.class_fields(source, entity):
|
|
492
|
+
return False
|
|
493
|
+
except edit.EditError:
|
|
494
|
+
return False
|
|
495
|
+
annotation = "int" if required else "int | None"
|
|
496
|
+
default = "" if required else " = None"
|
|
497
|
+
source = edit.add_field(
|
|
498
|
+
source,
|
|
499
|
+
entity,
|
|
500
|
+
f"{field_name}: {annotation}{default}",
|
|
501
|
+
required=required,
|
|
502
|
+
before=("status", "version", "id"),
|
|
503
|
+
)
|
|
504
|
+
_save(entities, source, result, dry_run=dry_run)
|
|
505
|
+
if schemas.exists():
|
|
506
|
+
text = schemas.read_text(encoding="utf-8")
|
|
507
|
+
for cls, line in (
|
|
508
|
+
(f"{entity}Create", f"{field_name}: {annotation}{default}"),
|
|
509
|
+
(f"{entity}Update", f"{field_name}: int | None = None"),
|
|
510
|
+
(f"{entity}Read", f"{field_name}: {annotation}"),
|
|
511
|
+
):
|
|
512
|
+
try:
|
|
513
|
+
if field_name not in edit.class_fields(text, cls):
|
|
514
|
+
text = edit.add_field(text, cls, line, required=False)
|
|
515
|
+
except edit.EditError:
|
|
516
|
+
continue
|
|
517
|
+
_save(schemas, text, result, dry_run=dry_run)
|
|
518
|
+
if persistence.exists():
|
|
519
|
+
text = persistence.read_text(encoding="utf-8")
|
|
520
|
+
table = f"{target.resource}_table"
|
|
521
|
+
try:
|
|
522
|
+
text = edit.add_call_argument(
|
|
523
|
+
text, table, f'Column("{field_name}", Integer, nullable={not required})'
|
|
524
|
+
)
|
|
525
|
+
text = edit.add_import(text, "sqlalchemy", "Integer")
|
|
526
|
+
except edit.EditError:
|
|
527
|
+
pass
|
|
528
|
+
else:
|
|
529
|
+
_save(persistence, text, result, dry_run=dry_run)
|
|
530
|
+
return True
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
def _entity_class(target: _ResourceFile) -> str | None:
|
|
534
|
+
model = target.attribute("model")
|
|
535
|
+
return model.id if isinstance(model, ast.Name) else None
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
# ----------------------------------------------------------------- policy
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def policy(
|
|
542
|
+
root: Path,
|
|
543
|
+
package: str,
|
|
544
|
+
resource: str,
|
|
545
|
+
role: str,
|
|
546
|
+
*,
|
|
547
|
+
read_only: bool = False,
|
|
548
|
+
name: str | None = None,
|
|
549
|
+
variable: str = "SEED_POLICIES",
|
|
550
|
+
dry_run: bool = False,
|
|
551
|
+
) -> Result:
|
|
552
|
+
"""A seed policy granting ``role`` the resource's operations, appended to
|
|
553
|
+
``<package>/authz.py``. The actions come from the registered resource."""
|
|
554
|
+
if not re.fullmatch(r"[A-Za-z0-9_.:-]+", role):
|
|
555
|
+
raise ScaffoldError(f"Invalid role {role!r}")
|
|
556
|
+
if not variable.isidentifier():
|
|
557
|
+
raise ScaffoldError(f"Invalid variable name {variable!r}")
|
|
558
|
+
base = _existing(root, package)
|
|
559
|
+
target = _ResourceFile(base, package, resource)
|
|
560
|
+
actions = _actions(root, target, read_only=read_only)
|
|
561
|
+
name = name or (
|
|
562
|
+
f"{pascal(role)} reads {resource}" if read_only else f"{pascal(role)} manages {resource}"
|
|
563
|
+
)
|
|
564
|
+
path = base / "authz.py"
|
|
565
|
+
source = _read(
|
|
566
|
+
path,
|
|
567
|
+
'"""Seed policies: created at start-up and checked by resource-engine check."""\n\n'
|
|
568
|
+
"from __future__ import annotations\n\nfrom typing import Any\n",
|
|
569
|
+
)
|
|
570
|
+
node = edit.module_variable(source, variable)
|
|
571
|
+
if node is None:
|
|
572
|
+
source = source.rstrip("\n") + f"\n\n{variable}: list[dict[str, Any]] = []\n"
|
|
573
|
+
source = edit.add_import(source, "typing", "Any")
|
|
574
|
+
node = edit.module_variable(source, variable)
|
|
575
|
+
if not isinstance(node.value, ast.List): # type: ignore[union-attr]
|
|
576
|
+
raise ScaffoldError(
|
|
577
|
+
f"{path}: {variable} is not a list literal; pass --variable to add a new list"
|
|
578
|
+
)
|
|
579
|
+
existing = [
|
|
580
|
+
e.values[edit.dict_keys(e).index("name")].value # type: ignore[attr-defined]
|
|
581
|
+
for e in node.value.elts # type: ignore[union-attr]
|
|
582
|
+
if isinstance(e, ast.Dict) and "name" in edit.dict_keys(e)
|
|
583
|
+
]
|
|
584
|
+
if name in existing:
|
|
585
|
+
raise ScaffoldError(f"{path} already has a policy named {name!r}")
|
|
586
|
+
entry = (
|
|
587
|
+
"{\n"
|
|
588
|
+
f' "name": {_string(name)},\n'
|
|
589
|
+
' "effect": "allow",\n'
|
|
590
|
+
f' "subjects": {{"roles": [{_string(role)}]}},\n'
|
|
591
|
+
' "actions": [\n' + "".join(f" {_string(a)},\n" for a in actions) + " ],\n"
|
|
592
|
+
"}"
|
|
593
|
+
)
|
|
594
|
+
try:
|
|
595
|
+
source = edit.append_to_module_list(source, variable, entry)
|
|
596
|
+
except edit.EditError as exc:
|
|
597
|
+
raise ScaffoldError(f"{path}: {exc}") from None
|
|
598
|
+
result = Result()
|
|
599
|
+
_save(path, source, result, dry_run=dry_run)
|
|
600
|
+
result.next_steps = [
|
|
601
|
+
f'Point check at the seed: [tool.resource-engine] policies = "{package}.authz:{variable}"',
|
|
602
|
+
"Create the seed at start-up (manager.create('authz_policies', policy) for the ones "
|
|
603
|
+
"missing), as the example's bootstrap does",
|
|
604
|
+
"Narrow it with a condition when the role should only see some records "
|
|
605
|
+
'("condition": {"eq": [{"attr": "resource.status"}, "draft"]})',
|
|
606
|
+
]
|
|
607
|
+
return result
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def _actions(root: Path, target: _ResourceFile, *, read_only: bool) -> list[str]:
|
|
611
|
+
from resource_engine import ResourceRegistry
|
|
612
|
+
from resource_engine.authz import Catalog
|
|
613
|
+
|
|
614
|
+
if str(root) not in sys.path:
|
|
615
|
+
sys.path.insert(0, str(root))
|
|
616
|
+
importlib.invalidate_caches()
|
|
617
|
+
for module in [
|
|
618
|
+
m for m in sys.modules if m == target.package or m.startswith(target.package + ".")
|
|
619
|
+
]:
|
|
620
|
+
del sys.modules[module]
|
|
621
|
+
try:
|
|
622
|
+
cls = getattr(importlib.import_module(target.module), target.class_name)
|
|
623
|
+
registry = ResourceRegistry()
|
|
624
|
+
registry.register(cls)
|
|
625
|
+
except Exception as exc:
|
|
626
|
+
raise ScaffoldError(f"Cannot load {target.module}.{target.class_name}: {exc}") from None
|
|
627
|
+
reading = {"list", "get", "download"}
|
|
628
|
+
kinds = {"crud", "transition", "action", "attach", "detach", "download"}
|
|
629
|
+
names = []
|
|
630
|
+
for info in Catalog._actions(next(iter(registry))):
|
|
631
|
+
if info.kind not in kinds:
|
|
632
|
+
continue
|
|
633
|
+
operation = info.name.split(":")[1]
|
|
634
|
+
if read_only and operation not in reading:
|
|
635
|
+
continue
|
|
636
|
+
names.append(info.name)
|
|
637
|
+
return names
|