|
| 1 | +"""FastAPI filter-allowlist codegen — one ``<entity_snake>_filter_allowlist.py`` |
| 2 | +per writable entity (``source.rdb`` with ``@kind="table"``). |
| 3 | +
|
| 4 | +FR-009 §3.5 (cross-port). Emits a per-entity static allowlist: |
| 5 | +
|
| 6 | +* ``<ENTITY>_FILTER_FIELDS: frozenset[str]`` — the field names that are |
| 7 | + filterable (gate against ``invalid_filter_field``). |
| 8 | +* ``<ENTITY>_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]]`` — the |
| 9 | + per-field operator vocabulary (gate against ``invalid_filter_op``). |
| 10 | +
|
| 11 | +Authoring contract: only fields with ``@filterable: true`` appear in the |
| 12 | +allowlist. If no field is marked filterable, the file is still emitted (with |
| 13 | +empty frozensets) so the generated router can unconditionally delegate to |
| 14 | +it without conditional codegen branching. |
| 15 | +
|
| 16 | +Operators-per-subtype mapping (FR-009 §5, identical across ports): |
| 17 | +
|
| 18 | +* ``string`` / ``enum`` → ``eq, ne, in, like, isNull`` |
| 19 | +* ``int / long / float / double / decimal / currency / date / timestamp / time`` |
| 20 | + → ``eq, ne, gt, gte, lt, lte, in, isNull`` |
| 21 | +* ``boolean`` → ``eq, isNull`` |
| 22 | +
|
| 23 | +``object`` fields are skipped — they have no SQL column surface that filters |
| 24 | +can target. |
| 25 | +
|
| 26 | +Mirrors the Java ``SpringFilterAllowlistGenerator`` + Kotlin |
| 27 | +``KotlinFilterAllowlistGenerator`` + C# allowlist emission. View kinds |
| 28 | +(``view`` / ``materializedView`` / ``storedProc`` / ``tableFunction``) get |
| 29 | +no allowlist — they share the "no router emitted" gate with |
| 30 | +``router_generator``. |
| 31 | +""" |
| 32 | +from __future__ import annotations |
| 33 | + |
| 34 | +from metaobjects.codegen.constants import generated_header |
| 35 | +from metaobjects.codegen.format import ruff_format |
| 36 | +from metaobjects.codegen.generator import EmittedFile, GenContext, Generator, per_entity |
| 37 | +from metaobjects.meta.core.field import field_constants as fc |
| 38 | +from metaobjects.meta.core.field.meta_field import MetaField |
| 39 | +from metaobjects.meta.core.object.meta_object import MetaObject |
| 40 | +from metaobjects.meta.persistence.source.meta_source import MetaSource |
| 41 | +from metaobjects.meta.persistence.source.source_constants import SOURCE_KIND_TABLE |
| 42 | +from metaobjects.shared.base_types import TYPE_SOURCE |
| 43 | +from metaobjects.shared.separators import PACKAGE_SEP |
| 44 | + |
| 45 | + |
| 46 | +# Operator sets — preserve insertion order (Python dict order == spec order). |
| 47 | +_OPS_STRING: tuple[str, ...] = ("eq", "ne", "in", "like", "isNull") |
| 48 | +_OPS_NUMERIC: tuple[str, ...] = ("eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull") |
| 49 | +_OPS_BOOLEAN: tuple[str, ...] = ("eq", "isNull") |
| 50 | + |
| 51 | + |
| 52 | +def _effective_fqn(entity: MetaObject) -> str: |
| 53 | + """``package::name``, resolving package from the nearest ancestor that carries |
| 54 | + one. Mirror of the router generator's helper of the same name.""" |
| 55 | + pkg = entity.package |
| 56 | + parent = entity.parent |
| 57 | + while pkg is None and parent is not None: |
| 58 | + pkg = parent.package |
| 59 | + parent = parent.parent |
| 60 | + return f"{pkg}{PACKAGE_SEP}{entity.name}" if pkg else entity.name |
| 61 | + |
| 62 | + |
| 63 | +def _snake_case(name: str) -> str: |
| 64 | + """``Author`` → ``author``; ``AuthorBrief`` → ``author_brief``. Mirror of |
| 65 | + the router generator's helper of the same name.""" |
| 66 | + out: list[str] = [] |
| 67 | + for i, ch in enumerate(name): |
| 68 | + if ch.isupper() and i > 0: |
| 69 | + out.append("_") |
| 70 | + out.append(ch.lower()) |
| 71 | + return "".join(out) |
| 72 | + |
| 73 | + |
| 74 | +def _primary_source_rdb(entity: MetaObject) -> MetaSource | None: |
| 75 | + """Return the entity's ``source.rdb`` child (own only), or ``None``.""" |
| 76 | + for c in entity.own_children(): |
| 77 | + if c.type == TYPE_SOURCE and isinstance(c, MetaSource): |
| 78 | + return c |
| 79 | + return None |
| 80 | + |
| 81 | + |
| 82 | +def _ops_for_subtype(sub_type: str | None) -> tuple[str, ...]: |
| 83 | + """Return the operator tuple for ``sub_type`` per the FR-009 §5 matrix. |
| 84 | +
|
| 85 | + Returns an empty tuple for subtypes outside the FR-009 vocabulary |
| 86 | + (defensive — the allowlist effectively becomes a "field is unknown" gate |
| 87 | + when the subtype is unrecognized). |
| 88 | + """ |
| 89 | + if sub_type is None: |
| 90 | + return () |
| 91 | + if sub_type in (fc.FIELD_SUBTYPE_STRING, fc.FIELD_SUBTYPE_ENUM): |
| 92 | + return _OPS_STRING |
| 93 | + if sub_type in ( |
| 94 | + fc.FIELD_SUBTYPE_INT, |
| 95 | + fc.FIELD_SUBTYPE_LONG, |
| 96 | + fc.FIELD_SUBTYPE_FLOAT, |
| 97 | + fc.FIELD_SUBTYPE_DOUBLE, |
| 98 | + fc.FIELD_SUBTYPE_DECIMAL, |
| 99 | + fc.FIELD_SUBTYPE_CURRENCY, |
| 100 | + fc.FIELD_SUBTYPE_DATE, |
| 101 | + fc.FIELD_SUBTYPE_TIMESTAMP, |
| 102 | + fc.FIELD_SUBTYPE_TIME, |
| 103 | + ): |
| 104 | + return _OPS_NUMERIC |
| 105 | + if sub_type == fc.FIELD_SUBTYPE_BOOLEAN: |
| 106 | + return _OPS_BOOLEAN |
| 107 | + return () |
| 108 | + |
| 109 | + |
| 110 | +def _is_filterable(field: MetaField) -> bool: |
| 111 | + """True iff ``field`` carries ``@filterable: true`` as a metadata attribute. |
| 112 | +
|
| 113 | + Accepts a real boolean ``True`` or the string ``"true"`` (case-insensitive), |
| 114 | + matching the Java/Kotlin/C# tolerance for either YAML-bool or raw-string |
| 115 | + value forms. |
| 116 | + """ |
| 117 | + raw = field.attr(fc.FIELD_ATTR_FILTERABLE) |
| 118 | + if raw is True: |
| 119 | + return True |
| 120 | + if isinstance(raw, str): |
| 121 | + return raw.lower() == "true" |
| 122 | + return False |
| 123 | + |
| 124 | + |
| 125 | +def _compute_filterable_ops(entity: MetaObject) -> dict[str, tuple[str, ...]]: |
| 126 | + """Build the ``{field_name: op_tuple}`` map for ``entity`` (own + inherited |
| 127 | + effective fields). Only fields with ``@filterable: true`` are included; |
| 128 | + object fields and subtypes outside the FR-009 vocabulary are skipped. |
| 129 | +
|
| 130 | + The returned dict preserves the entity's field declaration order so the |
| 131 | + emitted source is deterministic. |
| 132 | + """ |
| 133 | + out: dict[str, tuple[str, ...]] = {} |
| 134 | + for f in entity.fields(): |
| 135 | + if f.sub_type == fc.FIELD_SUBTYPE_OBJECT: |
| 136 | + continue |
| 137 | + if not _is_filterable(f): |
| 138 | + continue |
| 139 | + ops = _ops_for_subtype(f.sub_type) |
| 140 | + if not ops: |
| 141 | + continue |
| 142 | + out[f.name] = ops |
| 143 | + return out |
| 144 | + |
| 145 | + |
| 146 | +def render_filter_allowlist(entity: MetaObject) -> str | None: |
| 147 | + """Render the filter allowlist module for ``entity`` (or ``None`` to skip). |
| 148 | +
|
| 149 | + Returns ``None`` for entities without a ``source.rdb`` child and for |
| 150 | + read-only kinds (``view`` / ``materializedView`` / ``storedProc`` / |
| 151 | + ``tableFunction``) — these match the router generator's "no router" |
| 152 | + gate, so emitting an allowlist would be pure noise. |
| 153 | + """ |
| 154 | + src = _primary_source_rdb(entity) |
| 155 | + if src is None: |
| 156 | + return None |
| 157 | + if src.effective_kind() != SOURCE_KIND_TABLE: |
| 158 | + return None |
| 159 | + |
| 160 | + short_name = entity.name |
| 161 | + upper = short_name.upper() |
| 162 | + fields_const = f"{upper}_FILTER_FIELDS" |
| 163 | + ops_const = f"{upper}_FILTER_OPS_BY_FIELD" |
| 164 | + |
| 165 | + ops_by_field = _compute_filterable_ops(entity) |
| 166 | + |
| 167 | + parts: list[str] = [] |
| 168 | + parts.append( |
| 169 | + generated_header(short_name, _effective_fqn(entity)).rstrip() + "\n" |
| 170 | + + f'"""GENERATED — per-entity FR-009 filter allowlist for {short_name}.\n\n' |
| 171 | + f"{fields_const} lists the filterable field names; {ops_const}\n" |
| 172 | + f'constrains the operator vocabulary for each field by its subtype."""\n' |
| 173 | + ) |
| 174 | + parts.append("from __future__ import annotations") |
| 175 | + parts.append("") |
| 176 | + # FIELDS |
| 177 | + if not ops_by_field: |
| 178 | + parts.append(f"{fields_const}: frozenset[str] = frozenset()") |
| 179 | + parts.append("") |
| 180 | + parts.append(f"{ops_const}: dict[str, frozenset[str]] = {{}}") |
| 181 | + else: |
| 182 | + parts.append(f"{fields_const}: frozenset[str] = frozenset({{") |
| 183 | + for name in ops_by_field: |
| 184 | + parts.append(f' "{name}",') |
| 185 | + parts.append("})") |
| 186 | + parts.append("") |
| 187 | + parts.append(f"{ops_const}: dict[str, frozenset[str]] = {{") |
| 188 | + for name, ops in ops_by_field.items(): |
| 189 | + ops_literal = ", ".join(f'"{op}"' for op in ops) |
| 190 | + parts.append(f' "{name}": frozenset({{{ops_literal}}}),') |
| 191 | + parts.append("}") |
| 192 | + parts.append("") |
| 193 | + return "\n".join(parts) |
| 194 | + |
| 195 | + |
| 196 | +def filter_allowlist_generator() -> Generator: |
| 197 | + """Generator factory: ``object.entity`` + ``source.rdb @kind="table"`` → one |
| 198 | + ``<entity_snake>_filter_allowlist.py`` per writable entity. |
| 199 | +
|
| 200 | + Skips entities without a ``source.rdb`` child and read-only kinds |
| 201 | + (view / materializedView / storedProc / tableFunction) — same gate as |
| 202 | + ``router_generator``, so the two generators emit in lock-step. |
| 203 | + """ |
| 204 | + |
| 205 | + class _Gen: |
| 206 | + name = "filter-allowlist-generator" |
| 207 | + |
| 208 | + def generate(self, ctx: GenContext) -> list[EmittedFile]: |
| 209 | + def emit(entity: MetaObject, _c: GenContext) -> list[EmittedFile]: |
| 210 | + source = render_filter_allowlist(entity) |
| 211 | + if source is None: |
| 212 | + return [] |
| 213 | + snake = _snake_case(entity.name) |
| 214 | + return [ |
| 215 | + EmittedFile( |
| 216 | + path=f"{snake}_filter_allowlist.py", |
| 217 | + content=ruff_format(source), |
| 218 | + ) |
| 219 | + ] |
| 220 | + |
| 221 | + return per_entity(emit)(ctx) |
| 222 | + |
| 223 | + return _Gen() |
0 commit comments