Source code for fleetmesh_protocols.arcade.routes

"""`/api/arcade*` HTTP routing for `StandaloneArcadeStore` (`node.protocols.arcade.routes`)."""
from __future__ import annotations

import urllib.parse
from typing import Any, Dict, Mapping, Optional, Tuple

from fleetmesh_core.textile.principal import MeshAccessError, Principal, is_public

from ..textile.fiber_routes import binary_http_response

HttpResult = Tuple[int, Any, str, Dict[str, str]]
JSON_CT = "application/json; charset=utf-8"


def _item_binary_response(raw: bytes, rec: Mapping[str, Any], as_json: bool) -> HttpResult:
    return binary_http_response(
        raw,
        bao_root=str(rec.get("bao_root") or ""),
        sha256_hex=str(rec.get("sha256_hex") or ""),
        mime_type=str(rec.get("mime_type") or ""),
        public=is_public(rec),
        filename=str(rec.get("filename") or rec.get("item_id") or "arcade.bin"),
        as_json=as_json,
        json_extra={"item_id": rec.get("item_id")},
    )


def _sub(payload: Mapping[str, Any], key: str) -> Mapping[str, Any]:
    inner = payload.get(key)
    return inner if isinstance(inner, Mapping) else payload


[docs]def handle_arcade_http( store: Any, method: str, route: str, query: Any = "", body: Optional[Mapping[str, Any]] = None, principal: Principal = None, ) -> Optional[HttpResult]: """Route `/api/arcade*`. `principal` must come from the server's own session resolution.""" store = getattr(store, "arcade_store", store) qp = query if isinstance(query, Mapping) else urllib.parse.parse_qs(str(query or "")) try: if method == "GET": if route == "/api/arcade": return 200, store.snapshot(principal), JSON_CT, {"Cache-Control": "private, no-store"} if ( route.startswith("/api/arcade/items/") or route.startswith("/api/arcade/engines/") ) and route.endswith("/binary"): prefix = "/api/arcade/items/" if route.startswith("/api/arcade/items/") else "/api/arcade/engines/" item_id = urllib.parse.unquote(route[len(prefix) : -len("/binary")].strip("/")) found = store.get_item_binary(item_id, principal) if found is None: return 404, {"ok": False, "error": "arcade_binary_not_found", "item_id": item_id}, JSON_CT, {} as_json = (qp.get("format", [""])[0] or "").strip().lower() == "json" return _item_binary_response(found[0], found[1], as_json) return None if method != "POST" or not route.startswith("/api/arcade"): return None payload_in: Mapping[str, Any] = body or {} if route in ("/api/arcade", "/api/arcade/items", "/api/arcade/items/save"): item_in = _sub(payload_in, "item") saved = store.save_item(item_in, payload_in.get("data_b64") or item_in.get("data_b64"), principal) return 200, {"ok": True, "item": saved}, JSON_CT, {} if route == "/api/arcade/items/delete": iid = str(payload_in.get("item_id") or "") existed = store.delete_item(iid, principal) return (200 if existed else 404), {"ok": existed, "deleted_id": iid}, JSON_CT, {} if route in ("/api/arcade/engines", "/api/arcade/engines/save"): eng_in = _sub(payload_in, "engine") saved = store.save_engine( eng_in, principal, data_b64=payload_in.get("data_b64") or eng_in.get("data_b64") ) return 200, {"ok": True, "engine": saved}, JSON_CT, {} if route == "/api/arcade/engines/delete": eid = str(payload_in.get("engine_id") or "") existed = store.delete_engine(eid, principal) return (200 if existed else 404), {"ok": existed, "deleted_id": eid}, JSON_CT, {} if route in ("/api/arcade/desktop", "/api/arcade/desktop/save"): saved = store.save_desktop_state(_sub(payload_in, "desktop_state"), principal) return 200, {"ok": True, "arcade_desktop_state": saved}, JSON_CT, {} if route in ("/api/arcade/metadata", "/api/arcade/metadata/save"): saved = store.save_metadata_record(_sub(_sub(payload_in, "metadata"), "record"), principal) return 200, {"ok": True, "metadata": saved}, JSON_CT, {} if route in ("/api/arcade/scores", "/api/arcade/scores/save"): saved = store.save_score(_sub(payload_in, "score"), principal) return 200, {"ok": True, "score": saved}, JSON_CT, {} if route in ("/api/arcade/repos", "/api/arcade/repos/save"): saved = store.save_repo(_sub(payload_in, "repo"), principal) return 200, {"ok": True, "repo": saved}, JSON_CT, {} return None except MeshAccessError as exc: return exc.status, {"ok": False, "error": exc.error}, JSON_CT, {}