"""AstrBot extension route resolution helpers. This module intentionally avoids starting a standalone web server. AstrBot can use these pure helpers while registering plugin extension routes in-process. """ from __future__ import annotations import importlib import inspect import re from dataclasses import dataclass from typing import Any, Callable from backend.dto.common import ErrorCode, error_response from backend.route_registry import ROUTES, RouteSpec, assert_known_permissions, assert_unique_routes from backend.services.ui_service import API_BASE from core.identity import RequestContext @dataclass(frozen=True) class RouteMatch: method: str endpoint: str permission: str handler_path: str handler: Callable[..., Any] path_params: dict[str, str] def normalize_extension_path(path: str) -> str: normalized = str(path or "").strip() if "?" in normalized: normalized = normalized.split("?", 1)[0] normalized = normalized.replace("\\", "/").strip("/") api_base = API_BASE.strip("/") if normalized == api_base: return "" if normalized.startswith(f"{api_base}/"): normalized = normalized[len(api_base) + 1 :] return normalized.strip("/") def resolve_route(method: str, path: str) -> RouteMatch | None: normalized_method = str(method or "").strip().upper() endpoint = normalize_extension_path(path) for route in ROUTES: if route.method != normalized_method: continue params = _match_endpoint(route.endpoint, endpoint) if params is None: continue return RouteMatch( method=route.method, endpoint=route.endpoint, permission=route.permission, handler_path=route.handler, handler=_load_handler(route.handler), path_params=params, ) return None def runtime_route_table() -> list[dict[str, Any]]: return [ { "method": route.method, "endpoint": route.endpoint, "path": f"{API_BASE}/{route.endpoint}", "permission": route.permission, "handler": route.handler, } for route in ROUTES ] def runtime_registration_manifest() -> dict[str, Any]: return { "plugin_name": "astrbot_plugin_imagestudio", "api_base": API_BASE, "dispatch_handler": "adapters.astrbot_adapter.dispatch_extension_request", "web_asset_handler": "adapters.webui_adapter.resolve_web_asset", "extension_routes": runtime_route_table(), "web_mounts": [ { "name": "standalone_web", "path": f"{API_BASE}/web", "handler": "adapters.webui_adapter.resolve_web_asset", } ], "health": runtime_health(), } def runtime_health() -> dict[str, Any]: errors: list[dict[str, Any]] = [] try: assert_unique_routes() except RuntimeError as exc: errors.append({"code": "DUPLICATE_ROUTE", "message": str(exc)}) try: assert_known_permissions() except RuntimeError as exc: errors.append({"code": "UNKNOWN_PERMISSION", "message": str(exc)}) importable = 0 for route in ROUTES: try: _load_handler(route.handler) importable += 1 except Exception as exc: errors.append( { "code": "HANDLER_IMPORT_FAILED", "route": route.endpoint, "handler": route.handler, "message": str(exc), } ) return { "ok": not errors, "route_count": len(ROUTES), "importable_handlers": importable, "errors": errors, } def register_astrbot_runtime(runtime: Any, registration: dict[str, Any] | None = None) -> dict[str, Any]: manifest = registration or runtime_registration_manifest() route_count = 0 web_mount_count = 0 missing: list[str] = [] for route in manifest["extension_routes"]: if _register_route(runtime, route): route_count += 1 else: missing.append("register_extension_route") break for mount in manifest["web_mounts"]: if _register_web_mount(runtime, mount): web_mount_count += 1 else: missing.append("register_web_mount") break return { "registered": not missing, "routes_registered": route_count, "web_mounts_registered": web_mount_count, "missing_capabilities": sorted(set(missing)), "health": manifest["health"], } def dispatch_extension_request( ctx: RequestContext, method: str, path: str, *, query: dict[str, Any] | None = None, payload: dict[str, Any] | None = None, ) -> dict[str, Any]: match = resolve_route(method, path) if match is None: return error_response( error_code=ErrorCode.RESOURCE_NOT_FOUND, message="route not found", details={"method": str(method or "").upper(), "path": normalize_extension_path(path)}, request_id=ctx.request_id, ) return match.handler(*_handler_args(match, ctx, query or {}, payload or {})) def _register_route(runtime: Any, route: dict[str, Any]) -> bool: handler = _load_handler(str(route["handler"])) for method_name in ("register_extension_route", "register_route", "add_route"): callback = getattr(runtime, method_name, None) if not callable(callback): continue try: callback( method=route["method"], path=route["path"], handler=handler, permission=route["permission"], endpoint=route["endpoint"], ) except TypeError: callback(route["method"], route["path"], handler) return True return False def _register_web_mount(runtime: Any, mount: dict[str, Any]) -> bool: handler = _load_handler(str(mount["handler"])) for method_name in ("register_web_mount", "mount_web", "add_web_mount"): callback = getattr(runtime, method_name, None) if not callable(callback): continue try: callback(name=mount["name"], path=mount["path"], handler=handler) except TypeError: callback(mount["path"], handler) return True return False def _match_endpoint(pattern: str, endpoint: str) -> dict[str, str] | None: param_names = re.findall(r"\{([^{}]+)\}", pattern) regex = "^" + re.sub(r"\{([^{}]+)\}", r"([^/]+)", pattern) + "$" match = re.match(regex, endpoint) if not match: return None return dict(zip(param_names, match.groups(), strict=False)) def _handler_args( match: RouteMatch, ctx: RequestContext, query: dict[str, Any], payload: dict[str, Any], ) -> list[Any]: args: list[Any] = [] for index, parameter in enumerate(inspect.signature(match.handler).parameters.values()): if index == 0: args.append(ctx) continue if parameter.name == "query": args.append(query) elif parameter.name == "payload": args.append(payload) elif parameter.name in match.path_params: args.append(match.path_params[parameter.name]) elif parameter.default is inspect.Parameter.empty: raise TypeError(f"cannot dispatch required parameter: {parameter.name}") return args def _load_handler(handler_path: str) -> Callable[..., Any]: module_name, function_name = handler_path.rsplit(".", 1) handler = getattr(importlib.import_module(module_name), function_name) if not callable(handler): raise TypeError(f"route handler is not callable: {handler_path}") return handler