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,715 @@
|
|
|
1
|
+
"""``resource-engine scaffold consumer``: a typed consumer from a provider's AsyncAPI.
|
|
2
|
+
|
|
3
|
+
Reads an AsyncAPI 3.0 or 2.x document (JSON, or YAML with PyYAML installed),
|
|
4
|
+
picks the messages the provider sends, and writes:
|
|
5
|
+
|
|
6
|
+
- ``<package>/consumers/<name>.py``: a Pydantic model per message payload
|
|
7
|
+
(from its JSON Schema) and ``build_router(manager)``, an ``EventRouter`` with
|
|
8
|
+
one typed handler stub per message;
|
|
9
|
+
- ``<package>/tests/contracts/<name>.asyncapi.json``: the provider's document
|
|
10
|
+
as JSON, the contract the consumer was written against;
|
|
11
|
+
- ``<package>/tests/test_<name>_consumer.py``: the router keeps the contract
|
|
12
|
+
(``assert_consumer_contract``; ``<NAME>_ASYNCAPI`` points it at a newer
|
|
13
|
+
document), each sample payload parses, and each handler is still a stub.
|
|
14
|
+
|
|
15
|
+
Messages in the engine's envelope or in CloudEvents are unwrapped to their
|
|
16
|
+
payload (``payload`` / ``data``). Other bodies are modelled whole, and the
|
|
17
|
+
next steps say a decoder is needed. Handlers raise ``NotImplementedError``
|
|
18
|
+
until they are written, so messages are retried and dead-lettered instead of
|
|
19
|
+
silently acknowledged. Existing files are never overwritten without ``force``.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import contextlib
|
|
25
|
+
import json
|
|
26
|
+
import keyword
|
|
27
|
+
import re
|
|
28
|
+
import subprocess
|
|
29
|
+
import sys
|
|
30
|
+
import textwrap
|
|
31
|
+
from collections.abc import Mapping, Sequence
|
|
32
|
+
from dataclasses import dataclass, field
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
from typing import Any
|
|
35
|
+
|
|
36
|
+
from resource_engine_devtools.scaffold import (
|
|
37
|
+
Result,
|
|
38
|
+
ScaffoldError,
|
|
39
|
+
_identifier,
|
|
40
|
+
_write,
|
|
41
|
+
package_dir,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
# ------------------------------------------------------------------ reading
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def load_document(path: Path) -> dict[str, Any]:
|
|
48
|
+
"""An AsyncAPI document from a JSON or YAML file."""
|
|
49
|
+
if not path.is_file():
|
|
50
|
+
raise ScaffoldError(f"No AsyncAPI document at {path}")
|
|
51
|
+
text = path.read_text(encoding="utf-8")
|
|
52
|
+
if path.suffix.lower() in (".yaml", ".yml"):
|
|
53
|
+
try:
|
|
54
|
+
import yaml
|
|
55
|
+
except ImportError:
|
|
56
|
+
raise ScaffoldError(
|
|
57
|
+
"Reading YAML needs PyYAML: pip install pyyaml (or pass the JSON document)"
|
|
58
|
+
) from None
|
|
59
|
+
data = yaml.safe_load(text)
|
|
60
|
+
else:
|
|
61
|
+
try:
|
|
62
|
+
data = json.loads(text)
|
|
63
|
+
except ValueError as exc:
|
|
64
|
+
raise ScaffoldError(f"{path} is not JSON: {exc}") from exc
|
|
65
|
+
if not isinstance(data, dict) or "asyncapi" not in data:
|
|
66
|
+
raise ScaffoldError(f"{path} is not an AsyncAPI document (no 'asyncapi' key)")
|
|
67
|
+
major = str(data["asyncapi"]).split(".")[0]
|
|
68
|
+
if major not in ("2", "3"):
|
|
69
|
+
raise ScaffoldError(f"AsyncAPI {data['asyncapi']} is not supported (2.x and 3.x are)")
|
|
70
|
+
return data
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass
|
|
74
|
+
class Message:
|
|
75
|
+
"""A message the provider sends, unwrapped to its payload."""
|
|
76
|
+
|
|
77
|
+
event_type: str
|
|
78
|
+
channel: str
|
|
79
|
+
summary: str | None
|
|
80
|
+
payload: dict[str, Any]
|
|
81
|
+
wire: str # envelope | cloudevents | raw
|
|
82
|
+
examples: list[Any] = field(default_factory=list)
|
|
83
|
+
#: The payload version (``schema_version``; ``"1"`` when the document has none).
|
|
84
|
+
schema_version: str = "1"
|
|
85
|
+
#: The message's ``x-deprecation`` (``since``, ``sunset``, ``link``, ``reason``).
|
|
86
|
+
deprecation: Mapping[str, Any] | None = None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class _Resolver:
|
|
90
|
+
def __init__(self, document: Mapping[str, Any]) -> None:
|
|
91
|
+
self.document = document
|
|
92
|
+
|
|
93
|
+
def resolve(self, node: Any, depth: int = 0) -> Any:
|
|
94
|
+
"""``node`` with a top-level ``$ref`` (inside the document) followed."""
|
|
95
|
+
while isinstance(node, Mapping) and isinstance(node.get("$ref"), str) and depth < 20:
|
|
96
|
+
node = self.pointer(node["$ref"])
|
|
97
|
+
depth += 1
|
|
98
|
+
return node
|
|
99
|
+
|
|
100
|
+
def pointer(self, ref: str) -> Any:
|
|
101
|
+
if not ref.startswith("#/"):
|
|
102
|
+
raise ScaffoldError(f"Only references inside the document are supported, not {ref!r}")
|
|
103
|
+
node: Any = self.document
|
|
104
|
+
for part in ref[2:].split("/"):
|
|
105
|
+
part = part.replace("~1", "/").replace("~0", "~")
|
|
106
|
+
if not isinstance(node, Mapping) or part not in node:
|
|
107
|
+
raise ScaffoldError(f"Dangling reference {ref!r}")
|
|
108
|
+
node = node[part]
|
|
109
|
+
return node
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def provider_messages(
|
|
113
|
+
document: Mapping[str, Any],
|
|
114
|
+
*,
|
|
115
|
+
channels: Sequence[str] = (),
|
|
116
|
+
messages: Sequence[str] = (),
|
|
117
|
+
type_prefix: str = "",
|
|
118
|
+
unique: bool = True,
|
|
119
|
+
) -> list[Message]:
|
|
120
|
+
"""The messages the provider sends (3.0 ``send`` operations, 2.x
|
|
121
|
+
``subscribe`` operations; every channel message when none is marked),
|
|
122
|
+
optionally limited to some channels or message names. ``unique``: the
|
|
123
|
+
first message of each event type only (types repeat across channels)."""
|
|
124
|
+
resolver = _Resolver(document)
|
|
125
|
+
found: list[tuple[str, Any]] = []
|
|
126
|
+
if str(document["asyncapi"]).startswith("3"):
|
|
127
|
+
operations = document.get("operations") or {}
|
|
128
|
+
sends = [op for op in operations.values() if resolver.resolve(op).get("action") == "send"]
|
|
129
|
+
if sends:
|
|
130
|
+
for op in sends:
|
|
131
|
+
op = resolver.resolve(op)
|
|
132
|
+
channel_ref = (op.get("channel") or {}).get("$ref", "")
|
|
133
|
+
channel = channel_ref.rsplit("/", 1)[-1]
|
|
134
|
+
refs = op.get("messages") or list(
|
|
135
|
+
(resolver.resolve(op.get("channel") or {}).get("messages") or {}).values()
|
|
136
|
+
)
|
|
137
|
+
found += [(channel, m) for m in refs]
|
|
138
|
+
else:
|
|
139
|
+
for name, ch in (document.get("channels") or {}).items():
|
|
140
|
+
found += [(name, m) for m in (resolver.resolve(ch).get("messages") or {}).values()]
|
|
141
|
+
else:
|
|
142
|
+
for name, ch in (document.get("channels") or {}).items():
|
|
143
|
+
ch = resolver.resolve(ch)
|
|
144
|
+
op = ch.get("subscribe") or ch.get("publish")
|
|
145
|
+
if op is None:
|
|
146
|
+
continue
|
|
147
|
+
message = op.get("message") or {}
|
|
148
|
+
parts = message.get("oneOf") if isinstance(message, Mapping) else None
|
|
149
|
+
found += [(name, m) for m in (parts or [message])]
|
|
150
|
+
out: list[Message] = []
|
|
151
|
+
seen: set[str] = set()
|
|
152
|
+
for channel, ref in found:
|
|
153
|
+
if channels and channel not in channels:
|
|
154
|
+
continue
|
|
155
|
+
message = resolver.resolve(ref)
|
|
156
|
+
unwrapped = _unwrap(resolver, message, type_prefix)
|
|
157
|
+
if unwrapped is None:
|
|
158
|
+
continue
|
|
159
|
+
event_type, payload, wire = unwrapped
|
|
160
|
+
if messages and event_type not in messages:
|
|
161
|
+
continue
|
|
162
|
+
version = _version(resolver, message)
|
|
163
|
+
key = event_type if unique else f"{channel}\x00{event_type}\x00{version}"
|
|
164
|
+
if key in seen:
|
|
165
|
+
continue
|
|
166
|
+
seen.add(key)
|
|
167
|
+
examples = [
|
|
168
|
+
e.get("payload") if isinstance(e, Mapping) and "payload" in e else e
|
|
169
|
+
for e in message.get("examples") or []
|
|
170
|
+
]
|
|
171
|
+
out.append(
|
|
172
|
+
Message(
|
|
173
|
+
event_type=event_type,
|
|
174
|
+
channel=channel,
|
|
175
|
+
summary=message.get("summary")
|
|
176
|
+
or message.get("title")
|
|
177
|
+
or message.get("description"),
|
|
178
|
+
payload=payload,
|
|
179
|
+
wire=wire,
|
|
180
|
+
examples=[_inner(e, wire) for e in examples if e is not None],
|
|
181
|
+
schema_version=version,
|
|
182
|
+
deprecation=message.get("x-deprecation"),
|
|
183
|
+
)
|
|
184
|
+
)
|
|
185
|
+
if not out:
|
|
186
|
+
raise ScaffoldError(
|
|
187
|
+
"No messages to consume in the document"
|
|
188
|
+
+ (f" for channels {list(channels)}" if channels else "")
|
|
189
|
+
+ (f" named {list(messages)}" if messages else "")
|
|
190
|
+
)
|
|
191
|
+
return out
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _version(resolver: _Resolver, message: Mapping[str, Any]) -> str:
|
|
195
|
+
"""The message's ``schema_version`` const (envelope or CloudEvents)."""
|
|
196
|
+
schema = resolver.resolve(message.get("payload") or {})
|
|
197
|
+
props = schema.get("properties") or {} if isinstance(schema, Mapping) else {}
|
|
198
|
+
for name in ("schema_version", "schemaversion"):
|
|
199
|
+
const = (resolver.resolve(props.get(name) or {}) or {}).get("const")
|
|
200
|
+
if const is not None:
|
|
201
|
+
return str(const)
|
|
202
|
+
return "1"
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _inner(example: Any, wire: str) -> Any:
|
|
206
|
+
if isinstance(example, Mapping):
|
|
207
|
+
if wire == "envelope" and "payload" in example:
|
|
208
|
+
return example["payload"]
|
|
209
|
+
if wire == "cloudevents" and "data" in example:
|
|
210
|
+
return example["data"]
|
|
211
|
+
return example
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _unwrap(
|
|
215
|
+
resolver: _Resolver, message: Mapping[str, Any], type_prefix: str
|
|
216
|
+
) -> tuple[str, dict[str, Any], str] | None:
|
|
217
|
+
schema = resolver.resolve(message.get("payload") or {})
|
|
218
|
+
if isinstance(schema, Mapping) and "schema" in schema and "schemaFormat" in schema:
|
|
219
|
+
schema = resolver.resolve(schema["schema"]) # multi-format schema object
|
|
220
|
+
if not isinstance(schema, Mapping):
|
|
221
|
+
return None
|
|
222
|
+
props = schema.get("properties") or {}
|
|
223
|
+
name = message.get("name") or message.get("title") or message.get("messageId")
|
|
224
|
+
if "specversion" in props and "data" in props:
|
|
225
|
+
event_type = (props.get("type") or {}).get("const") or name
|
|
226
|
+
if event_type and type_prefix and event_type.startswith(type_prefix):
|
|
227
|
+
event_type = event_type[len(type_prefix) :]
|
|
228
|
+
if not event_type:
|
|
229
|
+
return None
|
|
230
|
+
return event_type, dict(resolver.resolve(props["data"])), "cloudevents"
|
|
231
|
+
if "payload" in props and "type" in props:
|
|
232
|
+
event_type = (props.get("type") or {}).get("const") or name
|
|
233
|
+
if not event_type:
|
|
234
|
+
return None
|
|
235
|
+
return event_type, dict(resolver.resolve(props["payload"])), "envelope"
|
|
236
|
+
if not name:
|
|
237
|
+
return None
|
|
238
|
+
return str(name), dict(schema), "raw"
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
# ------------------------------------------------------------- generation
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
_SCALARS = {"string": "str", "integer": "int", "number": "float", "boolean": "bool"}
|
|
245
|
+
_FORMATS = {
|
|
246
|
+
"date-time": ("datetime", "from datetime import datetime"),
|
|
247
|
+
"date": ("date", "from datetime import date"),
|
|
248
|
+
"time": ("time", "from datetime import time"),
|
|
249
|
+
"uuid": ("UUID", "from uuid import UUID"),
|
|
250
|
+
"decimal": ("Decimal", "from decimal import Decimal"),
|
|
251
|
+
}
|
|
252
|
+
_SAMPLE_FORMATS = {
|
|
253
|
+
"date-time": "2026-01-31T10:00:00+00:00",
|
|
254
|
+
"date": "2026-01-31",
|
|
255
|
+
"time": "10:00:00",
|
|
256
|
+
"uuid": "00000000-0000-0000-0000-000000000001",
|
|
257
|
+
"email": "someone@example.com",
|
|
258
|
+
"uri": "https://example.com",
|
|
259
|
+
"decimal": "10.00",
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def snake(name: str) -> str:
|
|
264
|
+
"""A name as a Python ``snake_case`` identifier."""
|
|
265
|
+
text = re.sub(r"[^0-9A-Za-z]+", "_", name)
|
|
266
|
+
text = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", text).strip("_").lower()
|
|
267
|
+
if not text or text[0].isdigit():
|
|
268
|
+
text = f"field_{text}"
|
|
269
|
+
return f"{text}_" if keyword.iskeyword(text) else text
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def class_name(name: str) -> str:
|
|
273
|
+
"""A name as a Python class name (``PascalCase``)."""
|
|
274
|
+
parts = re.split(r"[^0-9A-Za-z]+", name)
|
|
275
|
+
text = "".join(p[:1].upper() + p[1:] for p in parts if p)
|
|
276
|
+
if not text or text[0].isdigit():
|
|
277
|
+
text = f"Model{text}"
|
|
278
|
+
return text
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
class _Models:
|
|
282
|
+
"""JSON Schema → Pydantic model source (classes in dependency order)."""
|
|
283
|
+
|
|
284
|
+
def __init__(self, resolver: _Resolver) -> None:
|
|
285
|
+
self.resolver = resolver
|
|
286
|
+
self.classes: dict[str, str] = {}
|
|
287
|
+
self.by_ref: dict[str, str] = {}
|
|
288
|
+
self.imports: set[str] = set()
|
|
289
|
+
self.uses_any = False
|
|
290
|
+
self.uses_literal = False
|
|
291
|
+
|
|
292
|
+
def model(self, name: str, schema: Mapping[str, Any], doc: str | None = None) -> str:
|
|
293
|
+
name = self._unique(class_name(name))
|
|
294
|
+
self.classes[name] = "" # reserve the name (recursion)
|
|
295
|
+
schema = self._merged(schema)
|
|
296
|
+
required = set(schema.get("required") or ())
|
|
297
|
+
lines = [f"class {name}(BaseModel):"]
|
|
298
|
+
text = doc or schema.get("description")
|
|
299
|
+
lines.append(f' """{_docstring(text) if text else "TODO: what this payload is."}"""')
|
|
300
|
+
lines += ["", ' model_config = ConfigDict(extra="ignore", populate_by_name=True)']
|
|
301
|
+
properties = schema.get("properties") or {}
|
|
302
|
+
if properties:
|
|
303
|
+
lines.append("")
|
|
304
|
+
for prop, sub in properties.items():
|
|
305
|
+
sub = sub if isinstance(sub, Mapping) else {}
|
|
306
|
+
annotation = self.annotation(sub, f"{name}_{prop}")
|
|
307
|
+
optional = prop not in required
|
|
308
|
+
if optional and not annotation.endswith("| None") and annotation != "Any":
|
|
309
|
+
annotation = f"{annotation} | None"
|
|
310
|
+
attr = snake(prop)
|
|
311
|
+
args = []
|
|
312
|
+
if optional:
|
|
313
|
+
default = self.resolver.resolve(sub).get("default") if sub else None
|
|
314
|
+
args.append(f"default={_py(default)}" if _literal(default) else "default=None")
|
|
315
|
+
if attr != prop:
|
|
316
|
+
args.append(f"alias={_py(prop)}")
|
|
317
|
+
description = self.resolver.resolve(sub).get("description") if sub else None
|
|
318
|
+
if description:
|
|
319
|
+
args.append(f"description={_py(_one_line(description))}")
|
|
320
|
+
if args:
|
|
321
|
+
lines.append(f" {attr}: {annotation} = Field({', '.join(args)})")
|
|
322
|
+
else:
|
|
323
|
+
lines.append(f" {attr}: {annotation}")
|
|
324
|
+
if not properties:
|
|
325
|
+
lines += ["", ' model_config = ConfigDict(extra="allow")']
|
|
326
|
+
lines = [line for line in lines if "populate_by_name" not in line]
|
|
327
|
+
self.classes[name] = "\n".join(lines)
|
|
328
|
+
return name
|
|
329
|
+
|
|
330
|
+
def _unique(self, name: str) -> str:
|
|
331
|
+
candidate, n = name, 2
|
|
332
|
+
while candidate in self.classes:
|
|
333
|
+
candidate, n = f"{name}{n}", n + 1
|
|
334
|
+
return candidate
|
|
335
|
+
|
|
336
|
+
def _merged(self, schema: Mapping[str, Any]) -> dict[str, Any]:
|
|
337
|
+
schema = dict(self.resolver.resolve(schema))
|
|
338
|
+
for part in schema.pop("allOf", None) or []:
|
|
339
|
+
part = self._merged(part)
|
|
340
|
+
schema["properties"] = {
|
|
341
|
+
**(part.get("properties") or {}),
|
|
342
|
+
**(schema.get("properties") or {}),
|
|
343
|
+
}
|
|
344
|
+
schema["required"] = [*(part.get("required") or []), *(schema.get("required") or [])]
|
|
345
|
+
if "type" not in schema and "type" in part:
|
|
346
|
+
schema["type"] = part["type"]
|
|
347
|
+
return schema
|
|
348
|
+
|
|
349
|
+
def annotation(self, schema: Mapping[str, Any], hint: str) -> str:
|
|
350
|
+
ref = schema.get("$ref") if isinstance(schema, Mapping) else None
|
|
351
|
+
if isinstance(ref, str):
|
|
352
|
+
if ref in self.by_ref:
|
|
353
|
+
return self.by_ref[ref]
|
|
354
|
+
target = self.resolver.pointer(ref)
|
|
355
|
+
if self._is_object(target):
|
|
356
|
+
name = class_name(target.get("title") or ref.rsplit("/", 1)[-1])
|
|
357
|
+
self.by_ref[ref] = self._unique(name)
|
|
358
|
+
self.by_ref[ref] = self.model(self.by_ref[ref], target)
|
|
359
|
+
return self.by_ref[ref]
|
|
360
|
+
return self.annotation(target, hint)
|
|
361
|
+
schema = self._merged(schema)
|
|
362
|
+
if "const" in schema:
|
|
363
|
+
self.uses_literal = True
|
|
364
|
+
return f"Literal[{_py(schema['const'])}]"
|
|
365
|
+
if "enum" in schema and all(_literal(v) for v in schema["enum"]):
|
|
366
|
+
self.uses_literal = True
|
|
367
|
+
values = [v for v in schema["enum"] if v is not None]
|
|
368
|
+
literal = f"Literal[{', '.join(_py(v) for v in values)}]"
|
|
369
|
+
return f"{literal} | None" if None in schema["enum"] else literal
|
|
370
|
+
for key in ("anyOf", "oneOf"):
|
|
371
|
+
if key in schema:
|
|
372
|
+
parts = [self.annotation(s, hint) for s in schema[key]]
|
|
373
|
+
return _union(parts)
|
|
374
|
+
kind = schema.get("type")
|
|
375
|
+
if isinstance(kind, list):
|
|
376
|
+
parts = [self.annotation({**schema, "type": k}, hint) for k in kind]
|
|
377
|
+
return _union(parts)
|
|
378
|
+
if kind == "null":
|
|
379
|
+
return "None"
|
|
380
|
+
if kind in _SCALARS:
|
|
381
|
+
fmt = schema.get("format")
|
|
382
|
+
if kind == "string" and fmt in _FORMATS:
|
|
383
|
+
annotation, line = _FORMATS[fmt]
|
|
384
|
+
self.imports.add(line)
|
|
385
|
+
return annotation
|
|
386
|
+
return _SCALARS[kind]
|
|
387
|
+
if kind == "array":
|
|
388
|
+
items = schema.get("items")
|
|
389
|
+
if not isinstance(items, Mapping) or not items:
|
|
390
|
+
self.uses_any = True
|
|
391
|
+
return "list[Any]"
|
|
392
|
+
return f"list[{self.annotation(items, hint)}]"
|
|
393
|
+
if self._is_object(schema):
|
|
394
|
+
if schema.get("properties"):
|
|
395
|
+
return self.model(schema.get("title") or hint, schema)
|
|
396
|
+
extra = schema.get("additionalProperties")
|
|
397
|
+
if isinstance(extra, Mapping) and extra:
|
|
398
|
+
return f"dict[str, {self.annotation(extra, hint)}]"
|
|
399
|
+
self.uses_any = True
|
|
400
|
+
return "dict[str, Any]"
|
|
401
|
+
self.uses_any = True
|
|
402
|
+
return "Any"
|
|
403
|
+
|
|
404
|
+
@staticmethod
|
|
405
|
+
def _is_object(schema: Any) -> bool:
|
|
406
|
+
return isinstance(schema, Mapping) and (
|
|
407
|
+
schema.get("type") == "object" or "properties" in schema or "allOf" in schema
|
|
408
|
+
)
|
|
409
|
+
|
|
410
|
+
def sample(self, schema: Any, depth: int = 0) -> Any:
|
|
411
|
+
"""A value valid for ``schema``, for the generated tests."""
|
|
412
|
+
schema = self._merged(schema) if isinstance(schema, Mapping) else {}
|
|
413
|
+
for key in ("examples",):
|
|
414
|
+
if schema.get(key):
|
|
415
|
+
return schema[key][0]
|
|
416
|
+
for key in ("example", "default", "const"):
|
|
417
|
+
if key in schema:
|
|
418
|
+
return schema[key]
|
|
419
|
+
if schema.get("enum"):
|
|
420
|
+
return next((v for v in schema["enum"] if v is not None), None)
|
|
421
|
+
for key in ("anyOf", "oneOf"):
|
|
422
|
+
if schema.get(key):
|
|
423
|
+
options = [s for s in schema[key] if self.resolver.resolve(s).get("type") != "null"]
|
|
424
|
+
return self.sample(options[0] if options else schema[key][0], depth)
|
|
425
|
+
kind = schema.get("type")
|
|
426
|
+
if isinstance(kind, list):
|
|
427
|
+
kind = next((k for k in kind if k != "null"), "null")
|
|
428
|
+
if kind == "string":
|
|
429
|
+
return _SAMPLE_FORMATS.get(schema.get("format"), "sample")
|
|
430
|
+
if kind == "integer":
|
|
431
|
+
return max(1, int(schema.get("minimum", 1)))
|
|
432
|
+
if kind == "number":
|
|
433
|
+
return float(schema.get("minimum", 1))
|
|
434
|
+
if kind == "boolean":
|
|
435
|
+
return True
|
|
436
|
+
if kind == "null":
|
|
437
|
+
return None
|
|
438
|
+
if kind == "array":
|
|
439
|
+
return [self.sample(schema.get("items") or {}, depth + 1)] if depth < 4 else []
|
|
440
|
+
if self._is_object(schema) and depth < 4:
|
|
441
|
+
return {
|
|
442
|
+
p: self.sample(s, depth + 1)
|
|
443
|
+
for p, s in (schema.get("properties") or {}).items()
|
|
444
|
+
if p in set(schema.get("required") or ())
|
|
445
|
+
}
|
|
446
|
+
return {}
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def _union(parts: list[str]) -> str:
|
|
450
|
+
unique: list[str] = []
|
|
451
|
+
for part in parts:
|
|
452
|
+
for piece in part.split(" | "):
|
|
453
|
+
if piece not in unique:
|
|
454
|
+
unique.append(piece)
|
|
455
|
+
if "None" in unique:
|
|
456
|
+
unique = [p for p in unique if p != "None"] + ["None"]
|
|
457
|
+
return " | ".join(unique) if unique else "Any"
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def _py(value: Any) -> str:
|
|
461
|
+
"""A Python literal, with double-quoted strings (as ruff formats them)."""
|
|
462
|
+
if isinstance(value, str):
|
|
463
|
+
return json.dumps(value, ensure_ascii=False)
|
|
464
|
+
return repr(value)
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
def _literal(value: Any) -> bool:
|
|
468
|
+
return value is None or isinstance(value, bool | int | float | str)
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def _one_line(text: str) -> str:
|
|
472
|
+
return " ".join(str(text).split())
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
def _docstring(text: str) -> str:
|
|
476
|
+
line = _one_line(text).replace('"""', "'''").replace("\\", "\\\\")
|
|
477
|
+
return line if len(line) <= 80 else line[:77].rstrip() + "..."
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
# ---------------------------------------------------------------- scaffold
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def consumer(
|
|
484
|
+
root: Path,
|
|
485
|
+
package: str,
|
|
486
|
+
name: str,
|
|
487
|
+
document_path: Path,
|
|
488
|
+
*,
|
|
489
|
+
channels: Sequence[str] = (),
|
|
490
|
+
messages: Sequence[str] = (),
|
|
491
|
+
type_prefix: str = "",
|
|
492
|
+
force: bool = False,
|
|
493
|
+
dry_run: bool = False,
|
|
494
|
+
) -> Result:
|
|
495
|
+
"""Write a consumer for the events an AsyncAPI document describes: payload models and a
|
|
496
|
+
router."""
|
|
497
|
+
_identifier(name, "consumer")
|
|
498
|
+
document = load_document(document_path)
|
|
499
|
+
found = provider_messages(
|
|
500
|
+
document, channels=channels, messages=messages, type_prefix=type_prefix
|
|
501
|
+
)
|
|
502
|
+
resolver = _Resolver(document)
|
|
503
|
+
models = _Models(resolver)
|
|
504
|
+
handlers: list[tuple[Message, str]] = []
|
|
505
|
+
for message in found:
|
|
506
|
+
if not message.event_type.replace(".", "").replace("-", "").replace("_", "").isalnum():
|
|
507
|
+
raise ScaffoldError(f"Cannot name a model after event type {message.event_type!r}")
|
|
508
|
+
payload_cls = models.model(message.event_type, message.payload, message.summary)
|
|
509
|
+
handlers.append((message, payload_cls))
|
|
510
|
+
|
|
511
|
+
info = document.get("info") or {}
|
|
512
|
+
source = f"{info.get('title', document_path.name)} {info.get('version', '')}".strip()
|
|
513
|
+
consumer_name = name.replace("_", "-")
|
|
514
|
+
base = package_dir(root, package)
|
|
515
|
+
module = f"{package}.consumers.{name}"
|
|
516
|
+
result = Result()
|
|
517
|
+
_write(
|
|
518
|
+
base / "consumers" / "__init__.py",
|
|
519
|
+
'"""Consumers of other services\' events."""\n',
|
|
520
|
+
result,
|
|
521
|
+
force=False,
|
|
522
|
+
dry_run=dry_run,
|
|
523
|
+
)
|
|
524
|
+
if str(base / "consumers" / "__init__.py") in result.skipped:
|
|
525
|
+
result.skipped.remove(str(base / "consumers" / "__init__.py"))
|
|
526
|
+
_write(
|
|
527
|
+
base / "consumers" / f"{name}.py",
|
|
528
|
+
_module_source(name, consumer_name, source, document, models, handlers),
|
|
529
|
+
result,
|
|
530
|
+
force=force,
|
|
531
|
+
dry_run=dry_run,
|
|
532
|
+
)
|
|
533
|
+
_write(
|
|
534
|
+
base / "tests" / "contracts" / f"{name}.asyncapi.json",
|
|
535
|
+
json.dumps(document, indent=2, ensure_ascii=False, default=str) + "\n",
|
|
536
|
+
result,
|
|
537
|
+
force=force,
|
|
538
|
+
dry_run=dry_run,
|
|
539
|
+
)
|
|
540
|
+
_write(
|
|
541
|
+
base / "tests" / f"test_{name}_consumer.py",
|
|
542
|
+
_test_source(module, name, type_prefix, models, handlers),
|
|
543
|
+
result,
|
|
544
|
+
force=force,
|
|
545
|
+
dry_run=dry_run,
|
|
546
|
+
)
|
|
547
|
+
if not dry_run:
|
|
548
|
+
_format([p for p in result.written if p.endswith(".py")])
|
|
549
|
+
result.next_steps = [
|
|
550
|
+
"Write each handler: call the manager (an action, a transition) with a service "
|
|
551
|
+
"principal as actor, and replace the TODO docstrings",
|
|
552
|
+
f"Run it: MessageProcessor({module.rsplit('.', 1)[-1]}.build_router(manager), "
|
|
553
|
+
f'name="{consumer_name}", manager=manager) with the broker\'s MessageSource '
|
|
554
|
+
"(see docs/messaging.md#consumers)",
|
|
555
|
+
f'Document it: add "{module}:build_router" to [tool.resource-engine] consumers, '
|
|
556
|
+
"so resource-engine docs asyncapi lists what this service receives",
|
|
557
|
+
]
|
|
558
|
+
raw = [m.event_type for m, _ in handlers if m.wire == "raw"]
|
|
559
|
+
if raw:
|
|
560
|
+
result.next_steps.append(
|
|
561
|
+
f"{', '.join(raw)} {'is' if len(raw) == 1 else 'are'} neither an engine envelope nor "
|
|
562
|
+
"a CloudEvent: write a decoder that builds an EventEnvelope "
|
|
563
|
+
"(build_event_receiver(decode=...) or your MessageSource)"
|
|
564
|
+
)
|
|
565
|
+
return result
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def _format(paths: list[str]) -> None:
|
|
569
|
+
"""``ruff format`` the generated files when ruff is installed (long lines)."""
|
|
570
|
+
if not paths:
|
|
571
|
+
return
|
|
572
|
+
with contextlib.suppress(OSError, subprocess.SubprocessError):
|
|
573
|
+
subprocess.run( # noqa: S603 - ruff, with fixed arguments
|
|
574
|
+
[sys.executable, "-m", "ruff", "format", "--quiet", "--line-length", "100", *paths],
|
|
575
|
+
check=False,
|
|
576
|
+
capture_output=True,
|
|
577
|
+
timeout=60,
|
|
578
|
+
)
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def _module_source(
|
|
582
|
+
name: str,
|
|
583
|
+
consumer_name: str,
|
|
584
|
+
source: str,
|
|
585
|
+
document: Mapping[str, Any],
|
|
586
|
+
models: _Models,
|
|
587
|
+
handlers: list[tuple[Message, str]],
|
|
588
|
+
) -> str:
|
|
589
|
+
imports = ["from __future__ import annotations", ""]
|
|
590
|
+
stdlib = sorted(models.imports)
|
|
591
|
+
typing_names = [
|
|
592
|
+
n for n, used in (("Any", models.uses_any), ("Literal", models.uses_literal)) if used
|
|
593
|
+
]
|
|
594
|
+
if typing_names:
|
|
595
|
+
stdlib.append(f"from typing import {', '.join(typing_names)}")
|
|
596
|
+
stdlib.sort(key=lambda line: line.split()[1])
|
|
597
|
+
imports += stdlib
|
|
598
|
+
if stdlib:
|
|
599
|
+
imports.append("")
|
|
600
|
+
imports += [
|
|
601
|
+
"from pydantic import BaseModel, ConfigDict, Field",
|
|
602
|
+
"from resource_engine import ResourceManager",
|
|
603
|
+
"from resource_engine.messaging import EventEnvelope, EventRouter",
|
|
604
|
+
]
|
|
605
|
+
if not any("Field(" in c for c in models.classes.values()):
|
|
606
|
+
imports[imports.index("from pydantic import BaseModel, ConfigDict, Field")] = (
|
|
607
|
+
"from pydantic import BaseModel, ConfigDict"
|
|
608
|
+
)
|
|
609
|
+
about = textwrap.fill(
|
|
610
|
+
f"TODO: what this service does with the events of {_one_line(source)}.",
|
|
611
|
+
width=88,
|
|
612
|
+
subsequent_indent="",
|
|
613
|
+
)
|
|
614
|
+
header = (
|
|
615
|
+
f'"""{about}\n\n'
|
|
616
|
+
"Generated by ``resource-engine scaffold consumer`` from AsyncAPI "
|
|
617
|
+
f"{document.get('asyncapi')};\nthe models follow the provider's schemas.\n"
|
|
618
|
+
'"""'
|
|
619
|
+
)
|
|
620
|
+
body = [header, "", *imports, "", ""]
|
|
621
|
+
body.append("\n\n\n".join(models.classes.values()))
|
|
622
|
+
body += ["", "", ""]
|
|
623
|
+
body.append(
|
|
624
|
+
"def build_router(manager: ResourceManager | None = None) -> EventRouter:\n"
|
|
625
|
+
f' """Handlers for the ``{consumer_name}`` consumer. ``manager`` is ``None`` when\n'
|
|
626
|
+
' tools only describe the router (resource-engine docs asyncapi)."""\n'
|
|
627
|
+
f" router = EventRouter(\n"
|
|
628
|
+
f' name="{consumer_name}",\n'
|
|
629
|
+
' description="TODO: what this consumer does with these events.",\n'
|
|
630
|
+
" )\n"
|
|
631
|
+
)
|
|
632
|
+
for message, cls in handlers:
|
|
633
|
+
fn = f"on_{snake(message.event_type)}"
|
|
634
|
+
provider = (
|
|
635
|
+
textwrap.indent(
|
|
636
|
+
textwrap.fill(f"Provider: {_one_line(message.summary)}", width=80), " " * 8
|
|
637
|
+
)
|
|
638
|
+
if message.summary
|
|
639
|
+
else ""
|
|
640
|
+
)
|
|
641
|
+
doc = f"TODO: what receiving {message.event_type} does."
|
|
642
|
+
doc = f"{doc}\n\n{provider}\n " if provider else doc
|
|
643
|
+
body.append(
|
|
644
|
+
f' @router.on("{message.event_type}", payload={cls})\n'
|
|
645
|
+
f" async def {fn}(envelope: EventEnvelope, event: {cls}) -> None:\n"
|
|
646
|
+
f' """{doc}"""\n'
|
|
647
|
+
f' raise NotImplementedError("{fn} is not written yet") # TODO\n'
|
|
648
|
+
)
|
|
649
|
+
body.append(" return router\n")
|
|
650
|
+
return "\n".join(body).rstrip("\n") + "\n"
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
def _test_source(
|
|
654
|
+
module: str, name: str, type_prefix: str, models: _Models, handlers: list[tuple[Message, str]]
|
|
655
|
+
) -> str:
|
|
656
|
+
cases = []
|
|
657
|
+
for message, _cls in handlers:
|
|
658
|
+
sample = message.examples[0] if message.examples else models.sample(message.payload)
|
|
659
|
+
cases.append((message.event_type, sample))
|
|
660
|
+
rendered = ",\n".join(f" ({t!r}, {json.dumps(s, ensure_ascii=False)})" for t, s in cases)
|
|
661
|
+
rendered = re.sub(
|
|
662
|
+
r"\btrue\b", "True", re.sub(r"\bfalse\b", "False", re.sub(r"\bnull\b", "None", rendered))
|
|
663
|
+
)
|
|
664
|
+
variable = f"{name.upper()}_ASYNCAPI"
|
|
665
|
+
channels = sorted({m.channel for m, _ in handlers})
|
|
666
|
+
prefix = f", channels={json.dumps(channels)}"
|
|
667
|
+
prefix += f", type_prefix={_py(type_prefix)}" if type_prefix else ""
|
|
668
|
+
return f'''"""Contract tests for {module}.
|
|
669
|
+
|
|
670
|
+
The router matches the provider's AsyncAPI document, the provider's sample
|
|
671
|
+
payloads parse, and handlers are still stubs. Point {variable} at the
|
|
672
|
+
provider's latest document (a file) to check it instead of the snapshot.
|
|
673
|
+
"""
|
|
674
|
+
|
|
675
|
+
from __future__ import annotations
|
|
676
|
+
|
|
677
|
+
import os
|
|
678
|
+
from datetime import UTC, datetime
|
|
679
|
+
from pathlib import Path
|
|
680
|
+
|
|
681
|
+
import pytest
|
|
682
|
+
from resource_engine.messaging import EventEnvelope
|
|
683
|
+
from resource_engine_devtools.contracts import assert_consumer_contract
|
|
684
|
+
|
|
685
|
+
from {module} import build_router
|
|
686
|
+
|
|
687
|
+
CONTRACT = Path(__file__).parent / "contracts" / "{name}.asyncapi.json"
|
|
688
|
+
|
|
689
|
+
SAMPLES = [
|
|
690
|
+
{rendered},
|
|
691
|
+
]
|
|
692
|
+
|
|
693
|
+
|
|
694
|
+
def test_contract():
|
|
695
|
+
document = os.environ.get("{variable}") or CONTRACT
|
|
696
|
+
assert_consumer_contract(build_router(), document{prefix})
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
def _envelope(event_type, payload):
|
|
700
|
+
return EventEnvelope(type=event_type, payload=payload, occurred_at=datetime.now(UTC))
|
|
701
|
+
|
|
702
|
+
|
|
703
|
+
@pytest.mark.parametrize(("event_type", "payload"), SAMPLES)
|
|
704
|
+
def test_samples_parse(event_type, payload):
|
|
705
|
+
router = build_router()
|
|
706
|
+
parsed = router.parse(_envelope(event_type, payload))
|
|
707
|
+
assert isinstance(parsed, router.payload_type(event_type))
|
|
708
|
+
|
|
709
|
+
|
|
710
|
+
@pytest.mark.parametrize(("event_type", "payload"), SAMPLES)
|
|
711
|
+
async def test_handlers_are_written(event_type, payload):
|
|
712
|
+
router = build_router()
|
|
713
|
+
with pytest.raises(NotImplementedError): # TODO: replace with the handler's effect
|
|
714
|
+
await router.dispatch(_envelope(event_type, payload))
|
|
715
|
+
'''
|