The IR called them react-message and django-message, so a FastAPI channel had to declare a DjangoMessage. They are client-message and server-message now, and the direction words hold wherever a channel is declared: Params / ClientMessage / ServerMessage, with mizan-core deriving <Pascal>Params and friends so no backend names a type itself. Django's ReactChannel and FastAPI's ReactChannel are both Channel. mizan-fastapi never registered a channels extension, so build_ir() emitted no channel at all and every payload type was invisible to codegen. It registers one now. RegistryExtension is an ABC requiring all(), which is what the IR reads — an extension that cannot enumerate its registrations no longer exists. The gate that should have caught the rename could not: tests/afi registered no channel because mizan-rust had no channel registry to register one in, so a five-package rename of the wire contract passed byte-parity without a channel byte crossing it. mizan-rust grows ChannelSlotKind, a CHANNELS slice, a #[mizan::channel] macro, and KDL emission whose wire_to_pascal matches Python's split; the AFI fixture now carries a channel with every slot and one with a single slot, so all three backends prove the contract byte for byte. MizanChannel held three Option<String> beside three has_*() predicates and unwrapped them with defaults; it holds an ordered slot vector, so an absent slot is absent rather than defaulted. The channels target emitted a React hooks file that a stage1-only consumer could not compile — react emits that now. The codegen's parity tests byte-compared emitted source against baselines without ever compiling it: they compile the generated crate and run its tests, import the generated Python package and call every method, and typecheck each TypeScript target against a consumer. Also fixed at source: app_visitor printed its import diagnostic to stdout, the stream export_mizan_ir writes KDL to, so a failed import silently corrupted the IR; the apps root was hardcoded to "apps"; _default_literal crashed build_ir on any non-JSON-serializable field default; Django and mizan-core derived Pascal names two different ways, disagreeing on every dotted channel name. ir.py builds a document and renders templates/ir/document.kdl.j2 rather than appending KDL strings with hand-tracked indentation, and named types resolve to a fixed point — a model reachable only through a union branch was referenced by a ref that no type block ever defined. The rest is the write-gate's own classifiers run over the standing tree: relative imports, silent swallows, Protocol contracts that should be ABCs, emitters hand-rendering target source, catch-all arms over closed enums, and comments narrating the project rather than the code. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
228 lines
6.5 KiB
Python
228 lines
6.5 KiB
Python
"""FastAPI app exposing the mizan server functions the e2e harness calls.
|
|
|
|
`request.state.user` is never set here, so every auth-gated function below
|
|
resolves against an anonymous caller.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from fastapi import FastAPI
|
|
from fastapi.exceptions import RequestValidationError
|
|
from pydantic import BaseModel
|
|
|
|
from mizan_core.client.function import client
|
|
from mizan_core.registry import register
|
|
from mizan_fastapi import (
|
|
Forbidden,
|
|
MizanError,
|
|
mizan_exception_handler,
|
|
mizan_validation_handler,
|
|
router as mizan_router,
|
|
)
|
|
|
|
|
|
# ─── Output shapes ──────────────────────────────────────────────────────────
|
|
|
|
|
|
class EchoOutput(BaseModel):
|
|
message: str
|
|
|
|
|
|
class AddOutput(BaseModel):
|
|
result: int
|
|
|
|
|
|
class MultiplyOutput(BaseModel):
|
|
product: int
|
|
|
|
|
|
class DivideOutput(BaseModel):
|
|
quotient: float
|
|
|
|
|
|
class UserOutput(BaseModel):
|
|
email: str
|
|
authenticated: bool
|
|
is_staff: bool = False
|
|
|
|
|
|
class MessageOutput(BaseModel):
|
|
message: str
|
|
|
|
|
|
# ─── Morph state ────────────────────────────────────────────────────────────
|
|
|
|
|
|
class MorphGroupMeta(BaseModel):
|
|
"""Group summary. Its field set stays disjoint from MorphLayer's so the
|
|
server's return-type slot resolver can tell the two morphs slots apart."""
|
|
|
|
id: int
|
|
label: str
|
|
count: int
|
|
|
|
|
|
class MorphLayer(BaseModel):
|
|
id: int
|
|
group_id: int
|
|
label: str
|
|
value: float
|
|
|
|
|
|
_morph_groups: list[MorphGroupMeta] = [
|
|
MorphGroupMeta(id=1, label="face", count=2),
|
|
]
|
|
|
|
|
|
_morph_layers: list[MorphLayer] = [
|
|
MorphLayer(id=1, group_id=1, label="brow", value=0.0),
|
|
MorphLayer(id=2, group_id=1, label="jaw", value=0.0),
|
|
]
|
|
|
|
|
|
def _morph_layer(layer_id: int) -> MorphLayer:
|
|
for layer in _morph_layers:
|
|
if layer.id == layer_id:
|
|
return layer
|
|
raise ValueError(f"unknown morph layer id={layer_id}")
|
|
|
|
|
|
# ─── Server functions ───────────────────────────────────────────────────────
|
|
|
|
|
|
@client
|
|
def echo(request, text: str) -> EchoOutput:
|
|
"""Echoes the input text."""
|
|
return EchoOutput(message=text)
|
|
|
|
|
|
@client
|
|
def add(request, a: int, b: int) -> AddOutput:
|
|
"""Returns a + b."""
|
|
return AddOutput(result=a + b)
|
|
|
|
|
|
@client
|
|
def multiply(request, x: int, y: int) -> MultiplyOutput:
|
|
"""Returns x * y."""
|
|
return MultiplyOutput(product=x * y)
|
|
|
|
|
|
@client(auth=True)
|
|
def whoami(request) -> UserOutput:
|
|
"""Returns the authenticated user's identity."""
|
|
user = request.state.user
|
|
return UserOutput(
|
|
email=getattr(user, "email", ""),
|
|
authenticated=True,
|
|
is_staff=getattr(user, "is_staff", False),
|
|
)
|
|
|
|
|
|
@client(auth="staff")
|
|
def staff_only(request) -> MessageOutput:
|
|
"""Staff-only endpoint."""
|
|
return MessageOutput(message="staff access ok")
|
|
|
|
|
|
@client(auth="superuser")
|
|
def superuser_only(request) -> MessageOutput:
|
|
"""Superuser-only endpoint."""
|
|
return MessageOutput(message="superuser access ok")
|
|
|
|
|
|
def _is_verified(request) -> bool:
|
|
user = getattr(getattr(request, "state", None), "user", None)
|
|
return bool(user) and getattr(user, "is_verified", False)
|
|
|
|
|
|
@client(auth=_is_verified)
|
|
def verified_only(request) -> MessageOutput:
|
|
"""Verified-users-only endpoint."""
|
|
return MessageOutput(message="verified access ok")
|
|
|
|
|
|
_ECHO_TRANSFORMS = {"upper": str.upper, "lower": str.lower}
|
|
|
|
|
|
@client
|
|
def echo_transform(request, text: str, mode: str) -> EchoOutput:
|
|
"""Echoes the text through the named transform."""
|
|
transform = _ECHO_TRANSFORMS.get(mode)
|
|
if transform is None:
|
|
raise NotImplementedError(f"echo mode {mode!r} has no transform")
|
|
return EchoOutput(message=transform(text))
|
|
|
|
|
|
@client
|
|
def divide(request, numerator: int, denominator: int) -> DivideOutput:
|
|
"""Returns numerator / denominator."""
|
|
return DivideOutput(quotient=numerator / denominator)
|
|
|
|
|
|
@client
|
|
def permission_check_fn(request, secret: str) -> MessageOutput:
|
|
"""Grants access only for the correct secret."""
|
|
if secret != "open-sesame":
|
|
raise Forbidden("Invalid secret")
|
|
return MessageOutput(message="access granted")
|
|
|
|
|
|
@client(context="global")
|
|
def current_user(request) -> UserOutput:
|
|
"""The global context, auto-mounted at the React root."""
|
|
user = getattr(getattr(request, "state", None), "user", None)
|
|
return UserOutput(
|
|
email=getattr(user, "email", "") if user else "",
|
|
authenticated=bool(user) and getattr(user, "is_authenticated", False),
|
|
is_staff=getattr(user, "is_staff", False) if user else False,
|
|
)
|
|
|
|
|
|
@client(context="morphs")
|
|
def morph_groups(request) -> list[MorphGroupMeta]:
|
|
"""The group summaries in the morphs context bundle."""
|
|
return list(_morph_groups)
|
|
|
|
|
|
@client(context="morphs")
|
|
def morph_layers(request) -> list[MorphLayer]:
|
|
"""The layer rows in the morphs context bundle."""
|
|
return list(_morph_layers)
|
|
|
|
|
|
@client(merge="morphs")
|
|
def set_morph_value(request, id: int, value: float) -> MorphLayer:
|
|
"""Sets one layer's value and returns the changed row for the kernel to splice."""
|
|
layer = _morph_layer(id)
|
|
layer.value = value
|
|
return layer
|
|
|
|
|
|
# ─── Registration ───────────────────────────────────────────────────────────
|
|
|
|
|
|
register(echo, "echo")
|
|
register(add, "add")
|
|
register(multiply, "multiply")
|
|
register(whoami, "whoami")
|
|
register(staff_only, "staff_only")
|
|
register(superuser_only, "superuser_only")
|
|
register(verified_only, "verified_only")
|
|
register(echo_transform, "echo_transform")
|
|
register(divide, "divide")
|
|
register(permission_check_fn, "permission_check_fn")
|
|
register(current_user, "current_user")
|
|
register(morph_groups, "morph_groups")
|
|
register(morph_layers, "morph_layers")
|
|
register(set_morph_value, "set_morph_value")
|
|
|
|
|
|
# ─── App ────────────────────────────────────────────────────────────────────
|
|
|
|
|
|
app = FastAPI(title="mizan-fastapi e2e example")
|
|
app.include_router(mizan_router, prefix="/api/mizan")
|
|
app.add_exception_handler(MizanError, mizan_exception_handler)
|
|
app.add_exception_handler(RequestValidationError, mizan_validation_handler)
|