207 lines
8.0 KiB
Python
207 lines
8.0 KiB
Python
from typing import Any
|
|
|
|
from fastapi import APIRouter, Depends, Header, Path, Query, Response
|
|
from pydantic import BaseModel
|
|
|
|
from app.api.dependencies.auth import build_request_context
|
|
from app.api.dependencies.rate_limit import enforce_rate_limit
|
|
from app.api.schemas.admin import (
|
|
EmptyPayload,
|
|
EndpointPayload,
|
|
IntentPayload,
|
|
ItemPayload,
|
|
NegativePayload,
|
|
PromptPayload,
|
|
ReleasePayload,
|
|
ReplyPayload,
|
|
ReviewPayload,
|
|
RoutingPayload,
|
|
)
|
|
from app.core.advisor_backtest_contracts import AllocationBacktestQuery
|
|
from app.core.contracts import RequestContext
|
|
from app.core.profile_governance_contracts import ProfileDriftReviewRequest
|
|
from app.service.admin_service import AdminService
|
|
from app.service.allocation_backtest_service import AllocationBacktestService
|
|
from app.service.profile_governance_service import ProfileGovernanceService
|
|
|
|
router = APIRouter(
|
|
prefix="/api/v1/admin", tags=["platform-admin"], dependencies=[Depends(enforce_rate_limit)]
|
|
)
|
|
|
|
|
|
@router.post("/advisor/asset-allocation-backtests", status_code=201)
|
|
async def run_asset_allocation_backtest(
|
|
payload: AllocationBacktestQuery,
|
|
context: RequestContext = Depends(build_request_context), # noqa: B008
|
|
key: str | None = Header(default=None, alias="Idempotency-Key"),
|
|
) -> dict[str, object]:
|
|
return await AllocationBacktestService().run(payload, context, key)
|
|
|
|
|
|
@router.get("/advisor/profile-tags")
|
|
async def list_profile_tags(
|
|
customer_id: int = Query(gt=0),
|
|
context: RequestContext = Depends(build_request_context), # noqa: B008
|
|
) -> dict[str, object]:
|
|
return await ProfileGovernanceService().tags(customer_id, context)
|
|
|
|
|
|
@router.get("/advisor/profile-drift-reviews")
|
|
async def list_profile_drift_reviews(
|
|
context: RequestContext = Depends(build_request_context), # noqa: B008
|
|
) -> dict[str, object]:
|
|
return await ProfileGovernanceService().pending_reviews(context)
|
|
|
|
|
|
@router.post("/advisor/profile-drift-reviews/{review_id}/reviews")
|
|
async def review_profile_drift(
|
|
payload: ProfileDriftReviewRequest,
|
|
review_id: int = Path(gt=0),
|
|
context: RequestContext = Depends(build_request_context), # noqa: B008
|
|
key: str | None = Header(default=None, alias="Idempotency-Key"),
|
|
) -> dict[str, object]:
|
|
return await ProfileGovernanceService().review(review_id, payload, context, key)
|
|
|
|
|
|
def register_resource(
|
|
resource: str,
|
|
schema: type[BaseModel],
|
|
id_name: str,
|
|
*,
|
|
scoped: bool = False,
|
|
update: bool = True,
|
|
detail: bool = True,
|
|
) -> None:
|
|
prefix = f"/config-releases/{{release_id}}/{resource}" if scoped else f"/{resource}"
|
|
|
|
async def create(
|
|
payload: BaseModel,
|
|
response: Response,
|
|
release_id: int | None = None,
|
|
context: RequestContext = Depends(build_request_context), # noqa: B008
|
|
key: str | None = Header(default=None, alias="Idempotency-Key"),
|
|
) -> dict[str, Any]:
|
|
result = await AdminService().mutate(
|
|
resource, context, payload.model_dump(mode="json"), key, None, release_id=release_id
|
|
)
|
|
response.headers["ETag"] = f'"{result["meta"]["etag"]}"'
|
|
return result
|
|
|
|
create.__annotations__["payload"] = schema
|
|
router.add_api_route(
|
|
prefix, create, methods=["POST"], status_code=201, operation_id=f"create_{resource}"
|
|
)
|
|
|
|
async def list_rows(
|
|
release_id: int | None = None,
|
|
limit: int = Query(default=20, ge=1, le=100),
|
|
cursor: str | None = Query(default=None),
|
|
context: RequestContext = Depends(build_request_context), # noqa: B008
|
|
) -> dict[str, Any]:
|
|
"""列表查询(文档 §3.8 统一游标)。游标校验在 Service 的权限闸门之后进行。"""
|
|
return await AdminService().query(
|
|
resource, context, release_id=release_id, limit=limit, cursor=cursor
|
|
)
|
|
|
|
router.add_api_route(prefix, list_rows, methods=["GET"], operation_id=f"list_{resource}")
|
|
|
|
async def get(
|
|
response: Response,
|
|
row_id: int = Path(alias=id_name, gt=0),
|
|
context: RequestContext = Depends(build_request_context), # noqa: B008
|
|
) -> dict[str, Any]:
|
|
result = await AdminService().query(resource, context, row_id=row_id)
|
|
response.headers["ETag"] = f'"{result["meta"]["etag"]}"'
|
|
return result
|
|
|
|
if detail:
|
|
router.add_api_route(
|
|
f"{prefix}/{{{id_name}}}", get, methods=["GET"], operation_id=f"get_{resource}"
|
|
)
|
|
|
|
async def put(
|
|
payload: BaseModel,
|
|
response: Response,
|
|
row_id: int = Path(alias=id_name, gt=0),
|
|
release_id: int | None = None,
|
|
context: RequestContext = Depends(build_request_context), # noqa: B008
|
|
key: str | None = Header(default=None, alias="Idempotency-Key"),
|
|
if_match: str | None = Header(default=None, alias="If-Match"),
|
|
) -> dict[str, Any]:
|
|
result = await AdminService().mutate(
|
|
resource,
|
|
context,
|
|
payload.model_dump(mode="json"),
|
|
key,
|
|
if_match,
|
|
row_id=row_id,
|
|
release_id=release_id,
|
|
)
|
|
response.headers["ETag"] = f'"{result["meta"]["etag"]}"'
|
|
return result
|
|
|
|
put.__annotations__["payload"] = schema
|
|
if update:
|
|
router.add_api_route(
|
|
f"{prefix}/{{{id_name}}}", put, methods=["PUT"], operation_id=f"update_{resource}"
|
|
)
|
|
|
|
|
|
def register_transition(resource: str, id_name: str, action: str) -> None:
|
|
async def transition(
|
|
payload: BaseModel,
|
|
response: Response,
|
|
row_id: int = Path(alias=id_name, gt=0),
|
|
context: RequestContext = Depends(build_request_context), # noqa: B008
|
|
key: str | None = Header(default=None, alias="Idempotency-Key"),
|
|
if_match: str | None = Header(default=None, alias="If-Match"),
|
|
) -> dict[str, Any]:
|
|
result = await AdminService().mutate(
|
|
resource,
|
|
context,
|
|
payload.model_dump(mode="json"),
|
|
key,
|
|
if_match,
|
|
row_id=row_id,
|
|
action=action,
|
|
)
|
|
response.headers["ETag"] = f'"{result["meta"]["etag"]}"'
|
|
return result
|
|
|
|
transition.__annotations__["payload"] = ReviewPayload if action == "reviews" else EmptyPayload
|
|
router.add_api_route(
|
|
f"/{resource}/{{{id_name}}}/{action}",
|
|
transition,
|
|
methods=["POST"],
|
|
status_code=201 if action == "rollbacks" else 200,
|
|
operation_id=f"{action}_{resource}",
|
|
)
|
|
|
|
|
|
register_resource("config-releases", ReleasePayload, "release_id", update=False)
|
|
register_resource("platform-config-items", ItemPayload, "item_id", scoped=True, detail=False)
|
|
register_resource("model-endpoints", EndpointPayload, "endpoint_id")
|
|
register_resource("model-routing-rules", RoutingPayload, "rule_id", scoped=True, detail=False)
|
|
register_resource("prompt-templates", PromptPayload, "prompt_id", update=False)
|
|
register_resource("agent-intent-configs", IntentPayload, "config_id")
|
|
register_resource("reply-templates", ReplyPayload, "template_id", detail=False)
|
|
register_resource("negative-word-rules", NegativePayload, "rule_id", detail=False)
|
|
for action in ("validations", "reviews", "activations", "rollbacks"):
|
|
register_transition("config-releases", "release_id", action)
|
|
for action in ("reviews", "activations", "disablements"):
|
|
register_transition("model-endpoints", "endpoint_id", action)
|
|
# 意图配置沿用同一套"审核 → 生效 → 归档"流转;归档落 `archived`
|
|
# (该表 CHECK 约束只允许 draft/approved/active/archived,没有 disabled)。
|
|
for action in ("reviews", "activations", "archivals"):
|
|
register_transition("agent-intent-configs", "config_id", action)
|
|
|
|
|
|
@router.get("/audit-records")
|
|
async def audit_records(
|
|
limit: int = Query(default=20, ge=1, le=100),
|
|
cursor: str | None = Query(default=None),
|
|
context: RequestContext = Depends(build_request_context), # noqa: B008
|
|
) -> dict[str, Any]:
|
|
"""审计查询(文档 §9.6 支持游标过滤)。游标非法时返回 `400 INVALID_CURSOR`。"""
|
|
return await AdminService().query("audit-records", context, limit=limit, cursor=cursor)
|