astrbot_plugin_imagestudio/adapters/astrbot_adapter.py

132 行
4.1 KiB
Python

"""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
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 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 _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