Skip to content

Commit 21641a1

Browse files
committed
fix(python): api docs name only the routes a read-only object mounts (FR-044)
1 parent 48fe872 commit 21641a1

3 files changed

Lines changed: 175 additions & 20 deletions

File tree

‎server/python/src/metaobjects/apidocs/builder.py‎

Lines changed: 47 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,10 @@
4545
from metaobjects.codegen.generators.find_inbound import is_xml, response_shape
4646
from metaobjects.codegen.value_objects import is_field_required, pkg_of, resolve_payload_vo
4747
from metaobjects.codegen.generators.tph_plan import is_tph_subtype
48+
from metaobjects.codegen.generators.router_generator import is_read_only_routed
4849
from metaobjects.codegen.instance_artifacts import (
4950
emits_instance_artifacts,
51+
has_item_route,
5052
is_abstract,
5153
is_served_report,
5254
)
@@ -222,21 +224,21 @@ def _build_object_unit(
222224
)
223225
)
224226

227+
elif is_read_only_routed(obj):
228+
# A view-backed projection: the read-only router and its allowlist, no writes.
229+
symbols.extend(self._read_only_symbols(obj))
230+
225231
if not symbols:
226232
return None
227233
return ApiUnit(obj.name, _package_of(obj), unit_kind, symbols)
228234

229235
def _build_report_unit(self, obj: MetaObject, root: MetaData) -> ApiUnit:
230-
"""The unit for a SERVED report (FR-044 Table G): the row model, the repository
231-
seam (``list`` and ``count``), ``GET <served path>`` and the filter allowlist.
232-
Nothing else is generated for it: no item route, no write verb, no validation
233-
model. Built over the report's read model so the names are the generators'."""
236+
"""The unit for a SERVED report (FR-044 Table G): the row model plus the read-only
237+
surface its router mounts (:meth:`_read_only_symbols`). Nothing else is generated
238+
for it: no item route, no write verb, no validation model. Built over the
239+
report's read model so the names are the generators'."""
234240
model_obj = report_read_model(obj, root) # type: ignore[arg-type]
235241
model = naming.model_class_name(model_obj)
236-
router_module = naming.router_module_name(obj.name)
237-
base_path = "/api/" + naming.route_path(obj.name)
238-
repo = naming.repository_class_name(obj.name)
239-
fields_const = naming.filter_fields_const(obj.name)
240242
symbols = [
241243
ApiSymbol(
242244
name=model,
@@ -245,21 +247,47 @@ def _build_report_unit(self, obj: MetaObject, root: MetaData) -> ApiUnit:
245247
signature=f"class {model}(BaseModel)",
246248
usage="the Pydantic v2 report row model",
247249
),
250+
*self._read_only_symbols(model_obj),
251+
]
252+
return ApiUnit(obj.name, _package_of(obj), "report", symbols)
253+
254+
def _read_only_symbols(self, obj: MetaObject) -> list[ApiSymbol]:
255+
"""What the READ-ONLY router (``is_read_only_routed``) actually mounts and emits,
256+
and nothing more: the repository seam, ``GET`` list, ``GET`` by id ONLY when
257+
:func:`has_item_route`, and the filter allowlist. The collection ``POST`` and the
258+
item-verb refusals are 405s, not endpoints, so no write verb is documented;
259+
a keyless object has no item route and its seam no ``find_by_id``."""
260+
router_module = naming.router_module_name(obj.name)
261+
base_path = "/api/" + naming.route_path(obj.name)
262+
repo = naming.repository_class_name(obj.name)
263+
fields_const = naming.filter_fields_const(obj.name)
264+
item = has_item_route(obj)
265+
266+
def rest(verb_path: str, usage: str) -> ApiSymbol:
267+
return ApiSymbol(
268+
name=verb_path,
269+
kind=ApiSymbolKind.REST,
270+
module=f"# {router_module}.py — FastAPI APIRouter",
271+
signature=verb_path,
272+
usage=usage,
273+
)
274+
275+
symbols = [
248276
ApiSymbol(
249277
name=repo,
250278
kind=ApiSymbolKind.DATA_ACCESS,
251279
module=f"from .{router_module} import {repo}",
252280
signature=f"class {repo}(Protocol)",
253281
usage="data access — the read-only repository Protocol the consumer implements",
254-
returns="list / count",
255-
),
256-
ApiSymbol(
257-
name="GET " + base_path,
258-
kind=ApiSymbolKind.REST,
259-
module=f"# {router_module}.py — FastAPI APIRouter",
260-
signature="GET " + base_path,
261-
usage="list with pagination / sort / filters",
282+
returns="list / count / Optional" if item else "list / count",
262283
),
284+
rest("GET " + base_path, "list with pagination / sort / filters"),
285+
]
286+
if item:
287+
symbols.append(
288+
rest("GET " + base_path + "/{" + naming.pk_param(obj.name) + "}", "fetch one by id")
289+
)
290+
symbols.append(
263291
ApiSymbol(
264292
name=fields_const,
265293
kind=ApiSymbolKind.FILTER,
@@ -269,9 +297,9 @@ def _build_report_unit(self, obj: MetaObject, root: MetaData) -> ApiUnit:
269297
),
270298
signature=f"{fields_const}: frozenset[str]",
271299
usage="the filterable-field + filter-operator allowlist",
272-
),
273-
]
274-
return ApiUnit(obj.name, _package_of(obj), "report", symbols)
300+
)
301+
)
302+
return symbols
275303

276304
def _add_rest_symbols(
277305
self,

‎server/python/src/metaobjects/codegen/generators/router_generator.py‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -445,6 +445,19 @@ def emits_router(entity: MetaObject) -> bool:
445445
)
446446

447447

448+
def is_read_only_routed(entity: MetaObject) -> bool:
449+
"""Whether :meth:`RouterGenerator.render_router` chooses the READ-ONLY router for
450+
this object (a view / materialized-view source that is not write-through): GET list,
451+
GET by id when it has an item route, and the 405 refusals, with no write surface.
452+
453+
THE predicate behind that choice, shared with the API-docs builder so a page can never
454+
present write verbs for an object whose router refuses them."""
455+
if not emits_router(entity) or entity.is_write_through():
456+
return False
457+
src = primary_rdb_source(entity)
458+
return src is not None and src.effective_kind() in _READ_ONLY_ROUTED_KINDS
459+
460+
448461
def _sort_type_and_tables_lines(sort_field_nodes: list[MetaField]) -> list[str]:
449462
"""The `_SortClause` model + the two sort lookup tables.
450463
@@ -1257,7 +1270,7 @@ def render_router(
12571270
# READ-ONLY router instead: GET list + GET by id, every write verb
12581271
# answering the cross-port 405 envelope. Gated by
12591272
# fixtures/api-contract-conformance/projection/.
1260-
if src.effective_kind() in _READ_ONLY_ROUTED_KINDS:
1273+
if is_read_only_routed(entity):
12611274
return self._render_readonly_router(entity, column_naming)
12621275
return None
12631276

‎server/python/tests/test_api_docs_accuracy.py‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,5 +260,119 @@ def test_output_template_documents_render_and_its_payload_only() -> None:
260260
assert kinds == {ApiSymbolKind.RENDER, ApiSymbolKind.PAYLOAD}
261261

262262

263+
# ---------------------------------------------------------------------------
264+
# FR-044: a read-only object's unit documents EXACTLY the routes its router mounts.
265+
# ---------------------------------------------------------------------------
266+
267+
_READ_ONLY_MODEL = """
268+
{ "metadata.root": { "package": "acme::sales", "children": [
269+
{ "object.entity": { "name": "Invoice", "children": [
270+
{ "source.rdb": { "@table": "invoices" } },
271+
{ "field.long": { "name": "id" } },
272+
{ "field.string": { "name": "status", "@required": true, "@maxLength": 20 } },
273+
{ "field.long": { "name": "amountCents", "@required": true } },
274+
{ "identity.primary": { "name": "pk", "@fields": "id", "@generation": "increment" } },
275+
{ "dimension.attribute": { "name": "status", "@of": "Invoice.status" } },
276+
{ "measure.aggregate": { "name": "invoices", "@agg": "count", "@of": "Invoice.id" } }
277+
]}},
278+
{ "object.projection": { "name": "KeyedSummary", "children": [
279+
{ "source.rdb": { "@kind": "view", "@view": "v_keyed_summary" } },
280+
{ "field.long": { "name": "id", "extends": "Invoice.id", "@filterable": true } },
281+
{ "field.string": { "name": "status", "extends": "Invoice.status", "@filterable": true } },
282+
{ "identity.primary": { "name": "pk", "extends": "Invoice.pk" } }
283+
]}},
284+
{ "object.projection": { "name": "KeylessSummary", "children": [
285+
{ "source.rdb": { "@kind": "view", "@view": "v_keyless_summary" } },
286+
{ "field.string": { "name": "status", "extends": "Invoice.status", "@filterable": true } },
287+
{ "field.long": { "name": "amountCents", "extends": "Invoice.amountCents", "@filterable": true } }
288+
]}},
289+
{ "object.report": { "name": "StatusTotals", "@from": "Invoice",
290+
"@dimensions": ["status"], "@measures": ["invoices"],
291+
"children": [ { "source.rdb": { "@kind": "view", "@view": "v_status_totals" } } ]
292+
}}
293+
]}}
294+
"""
295+
296+
_WRITE_VERBS = {"POST", "PATCH", "PUT", "DELETE"}
297+
298+
299+
def _generated_routers_and_docs():
300+
"""Run the real orchestrator (`run_gen`, the path `metaobjects gen` takes) and the real
301+
docs builder over the read-only model; return ``(docs units by node, router source by
302+
snake name)``."""
303+
from metaobjects.codegen.generator_registry import GeneratorBuildContext, list_generators
304+
from metaobjects.codegen.runner import run_gen
305+
306+
with tempfile.TemporaryDirectory() as d:
307+
(Path(d) / "meta.json").write_text(_READ_ONLY_MODEL, encoding="utf-8")
308+
loaded = MetaDataLoader.from_directory(d)
309+
assert not loaded.errors, loaded.errors
310+
out = Path(tempfile.mkdtemp(prefix="py-apidocs-ro-"))
311+
templates = out / "t"
312+
templates.mkdir()
313+
gens = [
314+
e.factory(GeneratorBuildContext(template_root=str(templates)))
315+
for e in list_generators()
316+
if e.name in {"entity", "routes", "filter-allowlist"}
317+
]
318+
run_gen(GenConfig(out_dir=str(out / "o")), loaded.root, generators=gens)
319+
routers = {p.stem: p.read_text(encoding="utf-8") for p in (out / "o").glob("*_router.py")}
320+
model = PythonApiModelBuilder().build(loaded.root, "apidocs-ro")
321+
return {u.node: u for u in model.units}, routers
322+
323+
324+
def _mounted_routes(router_src: str, prefix: str) -> set[str]:
325+
"""``"VERB /api/path"`` for every route the router mounts as a WORKING endpoint: a
326+
handler that answers 405 ``method_not_allowed`` is a refusal, not an endpoint."""
327+
import ast
328+
329+
mounted: set[str] = set()
330+
for node in ast.walk(ast.parse(router_src)):
331+
if not isinstance(node, ast.FunctionDef):
332+
continue
333+
refusal = "method_not_allowed" in ast.get_source_segment(router_src, node)
334+
for dec in node.decorator_list:
335+
if (
336+
isinstance(dec, ast.Call)
337+
and isinstance(dec.func, ast.Attribute)
338+
and isinstance(dec.func.value, ast.Name)
339+
and dec.func.value.id == "router"
340+
and not refusal
341+
):
342+
mounted.add(f"{dec.func.attr.upper()} {prefix}{dec.args[0].value}")
343+
return mounted
344+
345+
346+
def _documented_routes(unit) -> set[str]:
347+
return {s.name for s in unit.symbols if s.kind == ApiSymbolKind.REST}
348+
349+
350+
@pytest.mark.parametrize(
351+
"node,snake,prefix,has_item",
352+
[
353+
("KeyedSummary", "keyed_summary", "/api/keyed_summaries", True),
354+
("KeylessSummary", "keyless_summary", "/api/keyless_summaries", False),
355+
("StatusTotals", "status_totals", "/api/status_totals", False),
356+
],
357+
)
358+
def test_read_only_unit_documents_exactly_the_routes_its_router_mounts(
359+
node: str, snake: str, prefix: str, has_item: bool
360+
) -> None:
361+
units, routers = _generated_routers_and_docs()
362+
router = routers[f"{snake}_router"]
363+
documented = _documented_routes(units[node])
364+
mounted = _mounted_routes(router, prefix)
365+
assert documented == mounted
366+
# Concretely: GET list always; GET by id only with an item route; never a write verb.
367+
assert ("GET " + prefix) in documented
368+
assert any(r.startswith("GET " + prefix + "/{") for r in documented) is has_item
369+
assert not {r.split(" ")[0] for r in documented} & _WRITE_VERBS
370+
# The seam: `find_by_id` exists iff the by-id route does, and the docs agree.
371+
assert ("def find_by_id(" in router) is has_item
372+
repo = next(s for s in units[node].symbols if s.kind == ApiSymbolKind.DATA_ACCESS)
373+
assert ("Optional" in (repo.returns or "")) is has_item
374+
assert _contains_identifier(router, repo.name)
375+
376+
263377
if __name__ == "__main__": # pragma: no cover
264378
raise SystemExit(pytest.main([__file__, "-q"]))

0 commit comments

Comments
 (0)