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

@@ -1,5 +1,6 @@
from __future__ import annotations
import path_setup # noqa: F401
import sx.sx_components as sx_components # noqa: F401 # ensure Hypercorn --reload watches this file
from shared.infrastructure.factory import create_base_app

View File

@@ -1,21 +1,23 @@
"""Relations app fragment endpoints.
Generic container-nav fragment that renders navigation items for all
related entities, driven by the relation registry.
Exposes sx fragments at ``/internal/fragments/<type>`` for consumption
by other coop apps via the fragment client.
All handlers are defined declaratively in .sx files under
``relations/sx/handlers/`` and dispatched via the sx handler registry.
"""
from __future__ import annotations
from quart import Blueprint, Response, g, request
from quart import Blueprint, Response, request
from shared.infrastructure.fragments import FRAGMENT_HEADER
from shared.sx.handlers import get_handler, execute_handler
def register():
bp = Blueprint("fragments", __name__, url_prefix="/internal/fragments")
_handlers: dict[str, object] = {}
@bp.before_request
async def _require_fragment_header():
if not request.headers.get(FRAGMENT_HEADER):
@@ -23,70 +25,12 @@ def register():
@bp.get("/<fragment_type>")
async def get_fragment(fragment_type: str):
handler = _handlers.get(fragment_type)
if handler is None:
return Response("", status=200, content_type="text/sx")
src = await handler()
return Response(src, status=200, content_type="text/sx")
# --- generic container-nav fragment ----------------------------------------
async def _container_nav_handler():
from shared.sx.helpers import sx_call
from shared.sx.relations import relations_from
from shared.services.relationships import get_children
from shared.infrastructure.urls import events_url, market_url
_SERVICE_URL = {
"calendar": events_url,
"market": market_url,
}
container_type = request.args.get("container_type", "page")
container_id = int(request.args.get("container_id", 0))
post_slug = request.args.get("post_slug", "")
nav_class = request.args.get("nav_class", "")
exclude_raw = request.args.get("exclude", "")
exclude = set(exclude_raw.split(",")) if exclude_raw else set()
nav_defs = [
d for d in relations_from(container_type)
if d.nav != "hidden" and d.name not in exclude
]
if not nav_defs:
return ""
parts = []
for defn in nav_defs:
children = await get_children(
g.s,
parent_type=container_type,
parent_id=container_id,
child_type=defn.to_type,
relation_type=defn.name,
handler_def = get_handler("relations", fragment_type)
if handler_def is not None:
result = await execute_handler(
handler_def, "relations", args=dict(request.args),
)
for child in children:
slug = (child.metadata_ or {}).get("slug", "")
if not slug:
continue
if post_slug:
path = f"/{post_slug}/{slug}/"
else:
path = f"/{slug}/"
url_fn = _SERVICE_URL.get(defn.to_type)
href = url_fn(path) if url_fn else path
parts.append(sx_call("relation-nav",
href=href,
name=child.label or "",
icon=defn.nav_icon or "",
nav_class=nav_class,
relation_type=defn.name))
if not parts:
return ""
return "(<> " + " ".join(parts) + ")"
_handlers["container-nav"] = _container_nav_handler
return Response(result, status=200, content_type="text/sx")
return Response("", status=200, content_type="text/sx")
return bp

0
relations/sx/__init__.py Normal file
View File

View File

@@ -0,0 +1,47 @@
;; Relations container-nav fragment handler
;;
;; Generic navigation fragment driven by the relation registry.
;; Renders nav items for all related entities of a container.
(defhandler container-nav (&key container_type container_id post_slug nav_class exclude)
(let ((ct (or container_type "page"))
(cid (parse-int (or container_id "0")))
(slug (or post_slug ""))
(ncls (or nav_class ""))
(excl-raw (or exclude ""))
(excl-set (filter (fn (e) (not (empty? e)))
(map trim (split excl-raw ","))))
;; URL builders per child type
(url-builders (dict :calendar "events" :market "market"))
;; Filter relation defs: visible + not excluded
(nav-defs (filter (fn (d)
(and (!= (get d "nav") "hidden")
(not (contains? excl-set (get d "name")))))
(relations-from ct))))
(when (not (empty? nav-defs))
(let ((parts (map (fn (defn)
(let ((children (get-children
:parent-type ct
:parent-id cid
:child-type (get defn "to_type")
:relation-type (get defn "name"))))
(<> (map (fn (child)
(let ((child-slug (or (get (or (get child "metadata_") (dict)) "slug") "")))
(when (not (empty? child-slug))
(let ((path (if (not (empty? slug))
(str "/" slug "/" child-slug "/")
(str "/" child-slug "/")))
(svc-name (get url-builders (get defn "to_type")))
(href (if svc-name
(app-url svc-name path)
path)))
(~relation-nav
:href href
:name (or (get child "label") "")
:icon (or (get defn "nav_icon") "")
:nav-class ncls
:relation-type (get defn "name")))))) children)))) nav-defs)))
(<> parts)))))

View File

@@ -0,0 +1,14 @@
"""
Relations service s-expression components.
Loads relation-specific .sx components and handlers.
"""
from __future__ import annotations
import os
from shared.sx.jinja_bridge import load_service_components
# Load relations-specific .sx components + handlers at import time
load_service_components(os.path.dirname(os.path.dirname(__file__)),
service_name="relations")