2026-07-05 21:56:12 +08:00
|
|
|
"""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
|
2026-07-05 21:59:57 +08:00
|
|
|
import inspect
|
2026-07-05 21:56:12 +08:00
|
|
|
import re
|
|
|
|
|
from dataclasses import dataclass
|
|
|
|
|
from typing import Any, Callable
|
|
|
|
|
|
2026-07-05 21:59:57 +08:00
|
|
|
from backend.dto.common import ErrorCode, error_response
|
2026-07-05 21:56:12 +08:00
|
|
|
from backend.route_registry import ROUTES, RouteSpec
|
|
|
|
|
from backend.services.ui_service import API_BASE
|
2026-07-05 21:59:57 +08:00
|
|
|
from core.identity import RequestContext
|
2026-07-05 21:56:12 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@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
|
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
|
2026-07-05 21:59:57 +08:00
|
|
|
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 {}))
|
|
|
|
|
|
|
|
|
|
|
2026-07-05 21:56:12 +08:00
|
|
|
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))
|
|
|
|
|
|
|
|
|
|
|
2026-07-05 21:59:57 +08:00
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
2026-07-05 21:56:12 +08:00
|
|
|
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
|