Add macros, declarative handlers (defhandler), and convert all fragment routes to sx
Some checks failed
Build and Deploy / build-and-deploy (push) Has been cancelled

Phase 1 — Macros: defmacro + quasiquote syntax (`, ,, ,@) in parser,
evaluator, HTML renderer, and JS mirror. Macro type, expansion, and
round-trip serialization.

Phase 2 — Expanded primitives: app-url, url-for, asset-url, config,
format-date, parse-int (pure); service, request-arg, request-path,
nav-tree, get-children (I/O); jinja-global, relations-from (pure).
Updated _io_service to accept (service "registry-name" "method" :kwargs)
with auto kebab→snake conversion. DTO-to-dict now expands datetime fields
into year/month/day convenience keys. Tuple returns converted to lists.

Phase 3 — Declarative handlers: HandlerDef type, defhandler special form,
handler registry (service → name → HandlerDef), async evaluator+renderer
(async_eval.py) that awaits I/O primitives inline within control flow.
Handler loading from .sx files, execute_handler, blueprint factory.

Phase 4 — Convert all fragment routes: 13 Python fragment handlers across
8 services replaced with declarative .sx handler files. All routes.py
simplified to uniform sx dispatch pattern. Two Jinja HTML handlers
(events/container-cards, events/account-page) kept as Python.

New files: shared/sx/async_eval.py, shared/sx/handlers.py,
shared/sx/tests/test_handlers.py, plus 13 handler .sx files under
{service}/sx/handlers/. MarketService.product_by_slug() added.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-03 00:22:18 +00:00
parent 13bcf755f6
commit ab75e505a8
48 changed files with 2538 additions and 638 deletions

View File

@@ -19,6 +19,7 @@ Usage in s-expressions::
from __future__ import annotations
import contextvars
from typing import Any
# ---------------------------------------------------------------------------
@@ -34,6 +35,11 @@ IO_PRIMITIVES: frozenset[str] = frozenset({
"action",
"current-user",
"htmx-request?",
"service",
"request-arg",
"request-path",
"nav-tree",
"get-children",
})
@@ -41,6 +47,23 @@ IO_PRIMITIVES: frozenset[str] = frozenset({
# Request context (set per-request by the resolver)
# ---------------------------------------------------------------------------
# ContextVar for the handler's domain service object.
# Set by the handler blueprint before executing a defhandler.
_handler_service: contextvars.ContextVar[Any] = contextvars.ContextVar(
"_handler_service", default=None
)
def set_handler_service(service_obj: Any) -> None:
"""Bind the local domain service for ``(service ...)`` primitive calls."""
_handler_service.set(service_obj)
def get_handler_service() -> Any:
"""Get the currently bound handler service, or None."""
return _handler_service.get(None)
class RequestContext:
"""Per-request context provided to I/O primitives.
@@ -140,6 +163,129 @@ async def _io_htmx_request(
return ctx.is_htmx
async def _io_service(
args: list[Any], kwargs: dict[str, Any], ctx: RequestContext
) -> Any:
"""``(service "svc-name" "method-name" :key val ...)`` → call domain service.
Looks up the service from the shared registry by name, then calls the
named method with ``g.s`` (async session) + keyword args. Falls back
to the bound handler service if only one positional arg is given.
"""
if not args:
raise ValueError("service requires at least a method name")
if len(args) >= 2:
# (service "calendar" "associated-entries" :key val ...)
from shared.services.registry import services as svc_registry
svc_name = str(args[0]).replace("-", "_")
svc = getattr(svc_registry, svc_name, None)
if svc is None:
raise RuntimeError(f"No service registered as: {svc_name}")
method_name = str(args[1]).replace("-", "_")
else:
# (service "method-name" :key val ...) — legacy / bound service
svc = get_handler_service()
if svc is None:
raise RuntimeError(
"No handler service bound — cannot call (service ...)")
method_name = str(args[0]).replace("-", "_")
method = getattr(svc, method_name, None)
if method is None:
raise RuntimeError(f"Service has no method: {method_name}")
# Convert kwarg keys from kebab-case to snake_case
clean_kwargs = {k.replace("-", "_"): v for k, v in kwargs.items()}
from quart import g
result = await method(g.s, **clean_kwargs)
return _convert_result(result)
def _dto_to_dict(obj: Any) -> dict[str, Any]:
"""Convert a DTO/dataclass/namedtuple to a plain dict.
Adds ``{field}_year``, ``{field}_month``, ``{field}_day`` convenience
keys for any datetime-valued field so sx handlers can build URL paths
without parsing date strings.
"""
if hasattr(obj, "_asdict"):
d = dict(obj._asdict())
elif hasattr(obj, "__dict__"):
d = {k: v for k, v in obj.__dict__.items() if not k.startswith("_")}
else:
return {"value": obj}
# Expand datetime fields into year/month/day convenience keys
for key, val in list(d.items()):
if hasattr(val, "year") and hasattr(val, "strftime"):
d[f"{key}_year"] = val.year
d[f"{key}_month"] = val.month
d[f"{key}_day"] = val.day
return d
def _convert_result(result: Any) -> Any:
"""Convert a service method result for sx consumption."""
if result is None:
from .types import NIL
return NIL
if isinstance(result, tuple):
# Tuple returns (e.g. (entries, has_more)) → list for sx access
return [_convert_result(item) for item in result]
if hasattr(result, "__dataclass_fields__") or hasattr(result, "_asdict"):
return _dto_to_dict(result)
if isinstance(result, list):
return [
_dto_to_dict(item)
if hasattr(item, "__dataclass_fields__") or hasattr(item, "_asdict")
else item
for item in result
]
return result
async def _io_request_arg(
args: list[Any], kwargs: dict[str, Any], ctx: RequestContext
) -> Any:
"""``(request-arg "name" default?)`` → request.args.get(name, default)."""
if not args:
raise ValueError("request-arg requires a name")
from quart import request
name = str(args[0])
default = args[1] if len(args) > 1 else None
return request.args.get(name, default)
async def _io_request_path(
args: list[Any], kwargs: dict[str, Any], ctx: RequestContext
) -> str:
"""``(request-path)`` → request.path."""
from quart import request
return request.path
async def _io_nav_tree(
args: list[Any], kwargs: dict[str, Any], ctx: RequestContext
) -> list[dict[str, Any]]:
"""``(nav-tree)`` → list of navigation menu node dicts."""
from quart import g
from shared.services.navigation import get_navigation_tree
nodes = await get_navigation_tree(g.s)
return [_dto_to_dict(node) for node in nodes]
async def _io_get_children(
args: list[Any], kwargs: dict[str, Any], ctx: RequestContext
) -> list[dict[str, Any]]:
"""``(get-children :parent-type "page" :parent-id 1 ...)``"""
from quart import g
from shared.services.relationships import get_children
clean = {k.replace("-", "_"): v for k, v in kwargs.items()}
children = await get_children(g.s, **clean)
return [_dto_to_dict(child) for child in children]
# ---------------------------------------------------------------------------
# Handler registry
# ---------------------------------------------------------------------------
@@ -150,4 +296,9 @@ _IO_HANDLERS: dict[str, Any] = {
"action": _io_action,
"current-user": _io_current_user,
"htmx-request?": _io_htmx_request,
"service": _io_service,
"request-arg": _io_request_arg,
"request-path": _io_request_path,
"nav-tree": _io_nav_tree,
"get-children": _io_get_children,
}