Files
mono/shared/services/relations_impl.py
giles 1f36987f77 Replace inter-service _handlers dicts with declarative sx defquery/defaction
The inter-service data layer (fetch_data/call_action) was the least
structured part of the codebase — Python _handlers dicts with ad-hoc
param extraction scattered across 16 route files. This replaces them
with declarative .sx query/action definitions that make the entire
inter-service protocol self-describing and greppable.

Infrastructure:
- defquery/defaction special forms in the sx evaluator
- Query/action registry with load, lookup, and schema introspection
- Query executor using async_eval with I/O primitives
- Blueprint factories (create_data_blueprint/create_action_blueprint)
  with sx-first dispatch and Python fallback
- /internal/schema endpoint on every service
- parse-datetime and split-ids primitives for type coercion

Service extractions:
- LikesService (toggle, is_liked, liked_slugs, liked_ids)
- PageConfigService (ensure, get_by_container, get_by_id, get_batch, update)
- RelationsService (wraps module-level functions)
- AccountDataService (user_by_email, newsletters)
- CartItemsService, MarketDataService (raw SQLAlchemy lookups)

50 of 54 handlers converted to sx, 4 Python fallbacks remain
(ghost-sync/push-member, clear-cart-for-order, create-order).
Net: -1,383 lines Python, +251 lines modified.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 08:13:50 +00:00

165 lines
5.5 KiB
Python

"""Service wrapper for relations module functions.
Wraps the module-level functions in shared.services.relationships into
a class so they can be called via the ``(service "relations" ...)`` primitive.
"""
from __future__ import annotations
from typing import Any
from sqlalchemy.ext.asyncio import AsyncSession
def _serialize_rel(r) -> dict[str, Any]:
return {
"id": r.id,
"parent_type": r.parent_type,
"parent_id": r.parent_id,
"child_type": r.child_type,
"child_id": r.child_id,
"sort_order": r.sort_order,
"label": r.label,
"relation_type": r.relation_type,
"metadata": r.metadata_,
}
class SqlRelationsService:
async def get_children(
self, session: AsyncSession, *,
parent_type: str, parent_id: int,
child_type: str | None = None,
relation_type: str | None = None,
) -> list[dict[str, Any]]:
from shared.services.relationships import get_children
rels = await get_children(
session, parent_type, parent_id, child_type,
relation_type=relation_type,
)
return [_serialize_rel(r) for r in rels]
async def get_parents(
self, session: AsyncSession, *,
child_type: str, child_id: int,
parent_type: str | None = None,
relation_type: str | None = None,
) -> list[dict[str, Any]]:
from shared.services.relationships import get_parents
rels = await get_parents(
session, child_type, child_id, parent_type,
relation_type=relation_type,
)
return [_serialize_rel(r) for r in rels]
async def attach_child(
self, session: AsyncSession, *,
parent_type: str, parent_id: int,
child_type: str, child_id: int,
label: str | None = None,
sort_order: int | None = None,
relation_type: str | None = None,
metadata: dict | None = None,
) -> dict[str, Any]:
from shared.services.relationships import attach_child
rel = await attach_child(
session,
parent_type=parent_type, parent_id=parent_id,
child_type=child_type, child_id=child_id,
label=label, sort_order=sort_order,
relation_type=relation_type, metadata=metadata,
)
return _serialize_rel(rel)
async def detach_child(
self, session: AsyncSession, *,
parent_type: str, parent_id: int,
child_type: str, child_id: int,
relation_type: str | None = None,
) -> bool:
from shared.services.relationships import detach_child
return await detach_child(
session,
parent_type=parent_type, parent_id=parent_id,
child_type=child_type, child_id=child_id,
relation_type=relation_type,
)
async def relate(
self, session: AsyncSession, *,
relation_type: str,
from_id: int, to_id: int,
label: str | None = None,
sort_order: int | None = None,
metadata: dict | None = None,
) -> dict[str, Any]:
"""Registry-aware relation creation with cardinality enforcement."""
from shared.services.relationships import attach_child, get_children
from shared.sx.relations import get_relation
defn = get_relation(relation_type)
if defn is None:
raise ValueError(f"unknown relation_type: {relation_type}")
if defn.cardinality == "one-to-one":
existing = await get_children(
session,
parent_type=defn.from_type,
parent_id=from_id,
child_type=defn.to_type,
relation_type=relation_type,
)
if existing:
raise ValueError("one-to-one relation already exists")
rel = await attach_child(
session,
parent_type=defn.from_type, parent_id=from_id,
child_type=defn.to_type, child_id=to_id,
label=label, sort_order=sort_order,
relation_type=relation_type, metadata=metadata,
)
return _serialize_rel(rel)
async def unrelate(
self, session: AsyncSession, *,
relation_type: str, from_id: int, to_id: int,
) -> bool:
from shared.services.relationships import detach_child
from shared.sx.relations import get_relation
defn = get_relation(relation_type)
if defn is None:
raise ValueError(f"unknown relation_type: {relation_type}")
return await detach_child(
session,
parent_type=defn.from_type, parent_id=from_id,
child_type=defn.to_type, child_id=to_id,
relation_type=relation_type,
)
async def can_relate(
self, session: AsyncSession, *,
relation_type: str, from_id: int,
) -> dict[str, Any]:
from shared.services.relationships import get_children
from shared.sx.relations import get_relation
defn = get_relation(relation_type)
if defn is None:
return {"allowed": False, "reason": f"unknown relation_type: {relation_type}"}
if defn.cardinality == "one-to-one":
existing = await get_children(
session,
parent_type=defn.from_type,
parent_id=from_id,
child_type=defn.to_type,
relation_type=relation_type,
)
if existing:
return {"allowed": False, "reason": "one-to-one relation already exists"}
return {"allowed": True}