Pārlūkot izejas kodu

feat: implement coordinate node configuration management service and api

jerry 2 mēneši atpakaļ
vecāks
revīzija
a78ec0b7d9

+ 163 - 0
app/api/endpoints/node_configuration.py

@@ -0,0 +1,163 @@
+from typing import Optional
+from fastapi import APIRouter, Depends, Query, Body
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.core.database import get_db
+from app.core.auth import get_current_user
+from app.models.user import VasUser
+from app.utils.response import success
+from app.schemas.common import ApiResponse
+from app.schemas.node_configuration import (
+    NodeConfigurationSaveRequest,
+    NodeConfigurationToggleRequest,
+    NodeConfigurationCloneRequest,
+    NodeConfigurationDeleteRequest,
+    NodeConfigurationDetailOut,
+    NodeConfigurationListItem,
+    NodeConfigurationListResponse,
+    NodeConfigAuditLogItem,
+    NodeConfigAuditLogListResponse,
+)
+from app.services.node_configuration_service import NodeConfigurationService
+
+admin_required_router = APIRouter()
+
+
+@admin_required_router.get(
+    "/node_configurations/detail",
+    summary="获取节点配置详情(Worker 轮询与详情查询)",
+    tags=["节点配置管理"],
+    response_model=ApiResponse[NodeConfigurationDetailOut],
+)
+async def get_node_configuration_detail(
+    role: str = Query(..., description="角色类型: sentinel / booker / standalone"),
+    node_id: str = Query(..., description="节点唯一标识,如 node01"),
+    db: AsyncSession = Depends(get_db),
+):
+    node_config = await NodeConfigurationService.get_detail(db, role=role, node_id=node_id)
+    return success(data=node_config)
+
+
+@admin_required_router.get(
+    "/node_configurations/list",
+    summary="查询节点配置列表(支持多条件过滤与分页)",
+    tags=["节点配置管理"],
+    response_model=ApiResponse[NodeConfigurationListResponse],
+)
+async def list_node_configurations(
+    role: Optional[str] = Query(None, description="过滤角色类型"),
+    node_id: Optional[str] = Query(None, description="过滤节点标识 (支持模糊搜索)"),
+    is_enabled: Optional[int] = Query(None, description="过滤启用状态: 1-启用, 0-禁用"),
+    page: int = Query(1, ge=1, description="页码"),
+    page_size: int = Query(20, ge=1, le=100, description="每页条数"),
+    db: AsyncSession = Depends(get_db),
+):
+    total, items = await NodeConfigurationService.list_configs(
+        db,
+        role=role,
+        node_id=node_id,
+        is_enabled=is_enabled,
+        page=page,
+        page_size=page_size,
+    )
+    return success(
+        data=NodeConfigurationListResponse(
+            total=total,
+            items=[NodeConfigurationListItem.model_validate(item) for item in items],
+        )
+    )
+
+
+@admin_required_router.post(
+    "/node_configurations/save",
+    summary="保存/更新节点配置 (Save / Upsert)",
+    tags=["节点配置管理"],
+    response_model=ApiResponse[NodeConfigurationDetailOut],
+)
+async def save_node_configuration(
+    payload: NodeConfigurationSaveRequest = Body(...),
+    current_user: VasUser = Depends(get_current_user),
+    db: AsyncSession = Depends(get_db),
+):
+    operator = (current_user.email or current_user.nickname or current_user.id) if current_user else "system"
+    saved = await NodeConfigurationService.save_config(db, payload, operator=operator)
+    return success(data=saved, message="Configuration saved successfully")
+
+
+@admin_required_router.post(
+    "/node_configurations/toggle",
+    summary="快速启用/禁用节点配置",
+    tags=["节点配置管理"],
+    response_model=ApiResponse[NodeConfigurationDetailOut],
+)
+async def toggle_node_configuration(
+    payload: NodeConfigurationToggleRequest = Body(...),
+    current_user: VasUser = Depends(get_current_user),
+    db: AsyncSession = Depends(get_db),
+):
+    operator = (current_user.email or current_user.nickname or current_user.id) if current_user else "system"
+    updated = await NodeConfigurationService.toggle_config(db, payload, operator=operator)
+    return success(data=updated, message="Configuration status updated successfully")
+
+
+@admin_required_router.post(
+    "/node_configurations/clone",
+    summary="从源节点复制克隆配置",
+    tags=["节点配置管理"],
+    response_model=ApiResponse[NodeConfigurationDetailOut],
+)
+async def clone_node_configuration(
+    payload: NodeConfigurationCloneRequest = Body(...),
+    current_user: VasUser = Depends(get_current_user),
+    db: AsyncSession = Depends(get_db),
+):
+    operator = (current_user.email or current_user.nickname or current_user.id) if current_user else "system"
+    cloned = await NodeConfigurationService.clone_config(db, payload, operator=operator)
+    return success(data=cloned, message="Configuration cloned successfully")
+
+
+@admin_required_router.delete(
+    "/node_configurations/delete",
+    summary="删除节点配置",
+    tags=["节点配置管理"],
+    response_model=ApiResponse[dict],
+)
+async def delete_node_configuration(
+    role: str = Query(..., description="角色类型"),
+    node_id: str = Query(..., description="节点标识"),
+    remark: Optional[str] = Query("", description="删除原因"),
+    current_user: VasUser = Depends(get_current_user),
+    db: AsyncSession = Depends(get_db),
+):
+    operator = (current_user.email or current_user.nickname or current_user.id) if current_user else "system"
+    req = NodeConfigurationDeleteRequest(role=role, node_id=node_id, operator=operator, remark=remark)
+    await NodeConfigurationService.delete_config(db, req, operator=operator)
+    return success(data={"role": role, "node_id": node_id, "deleted": True}, message="Configuration deleted successfully")
+
+
+@admin_required_router.get(
+    "/node_configurations/audit-logs",
+    summary="查询配置修改审计日志",
+    tags=["节点配置管理"],
+    response_model=ApiResponse[NodeConfigAuditLogListResponse],
+)
+async def list_node_config_audit_logs(
+    role: Optional[str] = Query(None, description="过滤角色类型"),
+    node_id: Optional[str] = Query(None, description="过滤节点标识"),
+    page: int = Query(1, ge=1, description="页码"),
+    page_size: int = Query(20, ge=1, le=100, description="每页条数"),
+    db: AsyncSession = Depends(get_db),
+):
+    total, logs = await NodeConfigurationService.get_audit_logs(
+        db,
+        role=role,
+        node_id=node_id,
+        page=page,
+        page_size=page_size,
+    )
+    return success(
+        data=NodeConfigAuditLogListResponse(
+            total=total,
+            items=[NodeConfigAuditLogItem.model_validate(log) for log in logs],
+        )
+    )

+ 2 - 0
app/api/router.py

@@ -10,6 +10,7 @@ from app.api.endpoints import (
     order,
     payment,
     plugin,
+    node_configuration,
     product,
     proxy,
     slot,
@@ -39,6 +40,7 @@ _modules = [
     order,
     payment,
     plugin,
+    node_configuration,
     product,
     proxy,
     slot,

+ 2 - 0
app/models/__init__.py

@@ -7,3 +7,5 @@ from .configuration import Configuration
 from .notification_outbox import NotificationOutbox
 from .emails import VasEmail
 from .plugin import Plugin, PluginVersion
+from .node_configuration import NodeConfiguration, NodeConfigAuditLog
+

+ 57 - 0
app/models/node_configuration.py

@@ -0,0 +1,57 @@
+from datetime import datetime
+from sqlalchemy import (
+    Column,
+    BigInteger,
+    String,
+    JSON,
+    SmallInteger,
+    DateTime,
+    UniqueConstraint,
+    Index,
+)
+from app.core.database import Base
+
+
+class NodeConfiguration(Base):
+    """
+    节点角色配置主表
+    """
+    __tablename__ = "node_configurations"
+
+    id = Column(BigInteger, primary_key=True, autoincrement=True)
+    role = Column(String(32), nullable=False, comment="角色类型: sentinel / booker / standalone")
+    node_id = Column(String(64), nullable=False, comment="节点唯一标识,如: node01")
+    config_content = Column(JSON, nullable=False, comment="完整配置内容 (JSON 数组或 JSON 对象)")
+    config_hash = Column(String(32), nullable=False, index=True, comment="配置内容 MD5 哈希,用于节点秒级比对")
+    is_enabled = Column(SmallInteger, nullable=False, default=1, index=True, comment="是否启用: 1-启用, 0-禁用")
+    description = Column(String(255), nullable=True, default="", comment="配置用途/备注说明")
+    created_by = Column(String(64), nullable=True, default="system", comment="创建人")
+    updated_by = Column(String(64), nullable=True, default="system", comment="最后更新人")
+    created_at = Column(DateTime, default=datetime.utcnow, nullable=False, comment="创建时间")
+    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, comment="更新时间")
+
+    __table_args__ = (
+        UniqueConstraint("role", "node_id", name="uk_role_node"),
+        Index("idx_node_config_updated_at", "updated_at"),
+    )
+
+
+class NodeConfigAuditLog(Base):
+    """
+    配置修改审计日志表
+    """
+    __tablename__ = "node_config_audit_logs"
+
+    id = Column(BigInteger, primary_key=True, autoincrement=True)
+    role = Column(String(32), nullable=False, comment="角色类型")
+    node_id = Column(String(64), nullable=False, comment="节点标识")
+    action = Column(String(32), nullable=False, comment="操作类型: CREATE / UPDATE / TOGGLE / DELETE / CLONE")
+    before_hash = Column(String(32), nullable=True, comment="修改前配置 Hash")
+    after_hash = Column(String(32), nullable=True, comment="修改后配置 Hash")
+    operator = Column(String(64), nullable=False, default="system", comment="操作人")
+    remark = Column(String(500), nullable=True, default="", comment="修改原因或备注说明")
+    created_at = Column(DateTime, default=datetime.utcnow, nullable=False, comment="操作时间")
+
+    __table_args__ = (
+        Index("idx_role_node_time", "role", "node_id", "created_at"),
+    )

+ 100 - 0
app/schemas/node_configuration.py

@@ -0,0 +1,100 @@
+from datetime import datetime
+from typing import Optional, Any, List, Union
+from pydantic import BaseModel, Field, field_validator
+
+
+class NodeConfigurationSaveRequest(BaseModel):
+    role: str = Field(..., description="角色类型,如 sentinel / booker / standalone")
+    node_id: str = Field(..., description="节点唯一标识,如 node01")
+    config_content: Union[List[Any], dict] = Field(..., description="完整配置内容 (JSON 数组或 JSON 对象)")
+    is_enabled: Optional[int] = Field(1, description="是否启用: 1-启用, 0-禁用")
+    description: Optional[str] = Field("", description="配置用途/备注说明")
+    operator: Optional[str] = Field("system", description="操作人")
+    remark: Optional[str] = Field("", description="修改原因或备注说明")
+
+    @field_validator("config_content")
+    @classmethod
+    def validate_config_content(cls, v):
+        if not isinstance(v, (list, dict)):
+            raise ValueError("config_content 必须是 JSON 对象 (dict) 或 JSON 数组 (list)")
+        return v
+
+
+class NodeConfigurationToggleRequest(BaseModel):
+    role: str = Field(..., description="角色类型")
+    node_id: str = Field(..., description="节点标识")
+    is_enabled: int = Field(..., description="是否启用: 1-启用, 0-禁用")
+    operator: Optional[str] = Field("system", description="操作人")
+    remark: Optional[str] = Field("", description="操作备注")
+
+
+class NodeConfigurationCloneRequest(BaseModel):
+    source_role: str = Field(..., description="源角色类型")
+    source_node_id: str = Field(..., description="源节点标识")
+    target_role: str = Field(..., description="目标角色类型")
+    target_node_id: str = Field(..., description="目标节点标识")
+    operator: Optional[str] = Field("system", description="操作人")
+    remark: Optional[str] = Field("", description="操作备注")
+
+
+class NodeConfigurationDeleteRequest(BaseModel):
+    role: str = Field(..., description="角色类型")
+    node_id: str = Field(..., description="节点标识")
+    operator: Optional[str] = Field("system", description="操作人")
+    remark: Optional[str] = Field("", description="操作备注")
+
+
+class NodeConfigurationDetailOut(BaseModel):
+    id: int
+    role: str
+    node_id: str
+    is_enabled: int
+    config_hash: str
+    config_content: Any
+    description: Optional[str] = ""
+    created_by: Optional[str] = None
+    updated_by: Optional[str] = None
+    created_at: Optional[datetime] = None
+    updated_at: Optional[datetime] = None
+
+    model_config = {"from_attributes": True}
+
+
+class NodeConfigurationListItem(BaseModel):
+    id: int
+    role: str
+    node_id: str
+    is_enabled: int
+    config_hash: str
+    description: Optional[str] = ""
+    created_by: Optional[str] = None
+    updated_by: Optional[str] = None
+    created_at: Optional[datetime] = None
+    updated_at: Optional[datetime] = None
+
+    model_config = {"from_attributes": True}
+
+
+class NodeConfigurationListResponse(BaseModel):
+    total: int
+    items: List[NodeConfigurationListItem]
+
+
+class NodeConfigAuditLogItem(BaseModel):
+    id: int
+    role: str
+    node_id: str
+    action: str
+    before_hash: Optional[str] = None
+    after_hash: Optional[str] = None
+    operator: str
+    remark: Optional[str] = ""
+    created_at: Optional[datetime] = None
+
+    model_config = {"from_attributes": True}
+
+
+
+class NodeConfigAuditLogListResponse(BaseModel):
+    total: int
+    items: List[NodeConfigAuditLogItem]

+ 286 - 0
app/services/node_configuration_service.py

@@ -0,0 +1,286 @@
+import json
+import hashlib
+from typing import Optional, List, Tuple, Any
+from sqlalchemy import select, func, desc, delete
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.core.biz_exception import NotFoundError, BizLogicError
+from app.core.logger import logger
+from app.models.node_configuration import NodeConfiguration, NodeConfigAuditLog
+from app.schemas.node_configuration import (
+    NodeConfigurationSaveRequest,
+    NodeConfigurationToggleRequest,
+    NodeConfigurationCloneRequest,
+    NodeConfigurationDeleteRequest,
+)
+
+
+def calculate_config_hash(content: Any) -> str:
+    """
+    使用 Canonical JSON (键排序、紧凑分隔符) 统一计算 MD5 哈希
+    保证与 Python Coordinate 节点客户端计算完全一致
+    """
+    if isinstance(content, str):
+        try:
+            content = json.loads(content)
+        except Exception:
+            pass
+    canonical_json_str = json.dumps(content, sort_keys=True, separators=(',', ':'), ensure_ascii=False)
+    return hashlib.md5(canonical_json_str.encode('utf-8')).hexdigest()
+
+
+class NodeConfigurationService:
+
+    @staticmethod
+    def compute_hash(content: Any) -> str:
+        return calculate_config_hash(content)
+
+    @classmethod
+    async def get_detail(
+        cls,
+        db: AsyncSession,
+        role: str,
+        node_id: str,
+    ) -> NodeConfiguration:
+        """
+        获取指定角色与节点的配置详情(供 Worker 轮询与详情展示)
+        """
+        stmt = select(NodeConfiguration).where(
+            NodeConfiguration.role == role,
+            NodeConfiguration.node_id == node_id,
+        )
+        res = (await db.execute(stmt)).scalar_one_or_none()
+        if not res:
+            raise NotFoundError(f"Node configuration for role='{role}' and node_id='{node_id}' not found")
+        return res
+
+    @classmethod
+    async def list_configs(
+        cls,
+        db: AsyncSession,
+        role: Optional[str] = None,
+        node_id: Optional[str] = None,
+        is_enabled: Optional[int] = None,
+        page: int = 1,
+        page_size: int = 20,
+    ) -> Tuple[int, List[NodeConfiguration]]:
+        """
+        分页查询配置列表
+        """
+        stmt = select(NodeConfiguration)
+        count_stmt = select(func.count(NodeConfiguration.id))
+
+        if role:
+            stmt = stmt.where(NodeConfiguration.role == role)
+            count_stmt = count_stmt.where(NodeConfiguration.role == role)
+        if node_id:
+            stmt = stmt.where(NodeConfiguration.node_id.like(f"%{node_id}%"))
+            count_stmt = count_stmt.where(NodeConfiguration.node_id.like(f"%{node_id}%"))
+        if is_enabled is not None:
+            stmt = stmt.where(NodeConfiguration.is_enabled == is_enabled)
+            count_stmt = count_stmt.where(NodeConfiguration.is_enabled == is_enabled)
+
+        total = (await db.execute(count_stmt)).scalar() or 0
+
+        offset = max(0, (page - 1) * page_size)
+        stmt = stmt.order_by(desc(NodeConfiguration.updated_at), desc(NodeConfiguration.id)).offset(offset).limit(page_size)
+        result = (await db.execute(stmt)).scalars().all()
+
+        return total, list(result)
+
+    @classmethod
+    async def save_config(
+        cls,
+        db: AsyncSession,
+        req: NodeConfigurationSaveRequest,
+        operator: Optional[str] = None,
+    ) -> NodeConfiguration:
+        """
+        新增或更新节点配置,并自动写入审计日志
+        """
+        op_user = operator or req.operator or "system"
+        calculated_hash = calculate_config_hash(req.config_content)
+
+        stmt = select(NodeConfiguration).where(
+            NodeConfiguration.role == req.role,
+            NodeConfiguration.node_id == req.node_id,
+        )
+        existing = (await db.execute(stmt)).scalar_one_or_none()
+
+        if existing:
+            action = "UPDATE"
+            before_hash = existing.config_hash
+            after_hash = calculated_hash
+
+            existing.config_content = req.config_content
+            existing.config_hash = calculated_hash
+            if req.is_enabled is not None:
+                existing.is_enabled = req.is_enabled
+            if req.description is not None:
+                existing.description = req.description
+            existing.updated_by = op_user
+
+            target_obj = existing
+        else:
+            action = "CREATE"
+            before_hash = None
+            after_hash = calculated_hash
+
+            target_obj = NodeConfiguration(
+                role=req.role,
+                node_id=req.node_id,
+                config_content=req.config_content,
+                config_hash=calculated_hash,
+                is_enabled=req.is_enabled if req.is_enabled is not None else 1,
+                description=req.description or "",
+                created_by=op_user,
+                updated_by=op_user,
+            )
+            db.add(target_obj)
+
+        audit_log = NodeConfigAuditLog(
+            role=req.role,
+            node_id=req.node_id,
+            action=action,
+            before_hash=before_hash,
+            after_hash=after_hash,
+            operator=op_user,
+            remark=req.remark or f"{action} configuration for {req.role}:{req.node_id}",
+        )
+        db.add(audit_log)
+
+        await db.commit()
+        await db.refresh(target_obj)
+        logger.info(f"✅ Node configuration saved: role={req.role}, node_id={req.node_id}, hash={calculated_hash}, action={action}")
+        return target_obj
+
+    @classmethod
+    async def toggle_config(
+        cls,
+        db: AsyncSession,
+        req: NodeConfigurationToggleRequest,
+        operator: Optional[str] = None,
+    ) -> NodeConfiguration:
+        """
+        切换启用/禁用状态
+        """
+        op_user = operator or req.operator or "system"
+        stmt = select(NodeConfiguration).where(
+            NodeConfiguration.role == req.role,
+            NodeConfiguration.node_id == req.node_id,
+        )
+        existing = (await db.execute(stmt)).scalar_one_or_none()
+        if not existing:
+            raise NotFoundError(f"Node configuration for role='{req.role}' and node_id='{req.node_id}' not found")
+
+        old_status = existing.is_enabled
+        existing.is_enabled = 1 if req.is_enabled else 0
+        existing.updated_by = op_user
+
+        audit_log = NodeConfigAuditLog(
+            role=req.role,
+            node_id=req.node_id,
+            action="TOGGLE",
+            before_hash=existing.config_hash,
+            after_hash=existing.config_hash,
+            operator=op_user,
+            remark=req.remark or f"Toggle is_enabled from {old_status} to {existing.is_enabled}",
+        )
+        db.add(audit_log)
+
+        await db.commit()
+        await db.refresh(existing)
+        return existing
+
+    @classmethod
+    async def clone_config(
+        cls,
+        db: AsyncSession,
+        req: NodeConfigurationCloneRequest,
+        operator: Optional[str] = None,
+    ) -> NodeConfiguration:
+        """
+        从源节点复制配置到目标节点
+        """
+        op_user = operator or req.operator or "system"
+        stmt = select(NodeConfiguration).where(
+            NodeConfiguration.role == req.source_role,
+            NodeConfiguration.node_id == req.source_node_id,
+        )
+        source = (await db.execute(stmt)).scalar_one_or_none()
+        if not source:
+            raise NotFoundError(f"Source configuration for role='{req.source_role}' and node_id='{req.source_node_id}' not found")
+
+        save_req = NodeConfigurationSaveRequest(
+            role=req.target_role,
+            node_id=req.target_node_id,
+            config_content=source.config_content,
+            is_enabled=source.is_enabled,
+            description=f"Cloned from {req.source_role}:{req.source_node_id}. {source.description or ''}".strip(),
+            operator=op_user,
+            remark=req.remark or f"Cloned from {req.source_role}:{req.source_node_id}",
+        )
+        return await cls.save_config(db, save_req, operator=op_user)
+
+    @classmethod
+    async def delete_config(
+        cls,
+        db: AsyncSession,
+        req: NodeConfigurationDeleteRequest,
+        operator: Optional[str] = None,
+    ) -> bool:
+        """
+        删除节点配置,并记录审计日志
+        """
+        op_user = operator or req.operator or "system"
+        stmt = select(NodeConfiguration).where(
+            NodeConfiguration.role == req.role,
+            NodeConfiguration.node_id == req.node_id,
+        )
+        existing = (await db.execute(stmt)).scalar_one_or_none()
+        if not existing:
+            raise NotFoundError(f"Node configuration for role='{req.role}' and node_id='{req.node_id}' not found")
+
+        audit_log = NodeConfigAuditLog(
+            role=req.role,
+            node_id=req.node_id,
+            action="DELETE",
+            before_hash=existing.config_hash,
+            after_hash=None,
+            operator=op_user,
+            remark=req.remark or f"Deleted configuration for {req.role}:{req.node_id}",
+        )
+        db.add(audit_log)
+        await db.delete(existing)
+        await db.commit()
+        return True
+
+    @classmethod
+    async def get_audit_logs(
+        cls,
+        db: AsyncSession,
+        role: Optional[str] = None,
+        node_id: Optional[str] = None,
+        page: int = 1,
+        page_size: int = 20,
+    ) -> Tuple[int, List[NodeConfigAuditLog]]:
+        """
+        查询审计日志
+        """
+        stmt = select(NodeConfigAuditLog)
+        count_stmt = select(func.count(NodeConfigAuditLog.id))
+
+        if role:
+            stmt = stmt.where(NodeConfigAuditLog.role == role)
+            count_stmt = count_stmt.where(NodeConfigAuditLog.role == role)
+        if node_id:
+            stmt = stmt.where(NodeConfigAuditLog.node_id == node_id)
+            count_stmt = count_stmt.where(NodeConfigAuditLog.node_id == node_id)
+
+        total = (await db.execute(count_stmt)).scalar() or 0
+
+        offset = max(0, (page - 1) * page_size)
+        stmt = stmt.order_by(desc(NodeConfigAuditLog.created_at), desc(NodeConfigAuditLog.id)).offset(offset).limit(page_size)
+        result = (await db.execute(stmt)).scalars().all()
+
+        return total, list(result)

+ 393 - 0
docs/node_configuration.md

@@ -0,0 +1,393 @@
+# 节点配置管理服务 (Node Configuration) HTTP API 接口文档
+
+本文档为 Coordinate 节点配置管理服务(`node_configurations`)的后端 HTTP RESTful API 接口规范。
+
+---
+
+## 1. 接口通用规范
+
+- **协议规范**: `HTTP/1.1` 或 `HTTP/2`
+- **基础路径 (Base URL)**: `/api`
+- **数据交互格式**: `application/json`
+- **字符编码**: `UTF-8`
+- **认证方式**: Bearer Token 鉴权(管理员权限):
+  ```http
+  Authorization: Bearer <token>
+  ```
+
+### 统一响应结构
+
+所有接口均返回标准 JSON 结构:
+
+```json
+{
+  "code": 0,          // 0 为成功,非 0 为错误码
+  "message": "success",
+  "data": {}          // 响应数据对象
+}
+```
+
+---
+
+## 2. API 接口列表
+
+| 方法 | 接口路径 | 说明 |
+| :--- | :--- | :--- |
+| `GET` | `/api/node_configurations/list` | 分页查询节点配置列表 |
+| `GET` | `/api/node_configurations/detail` | 获取指定节点配置详情 |
+| `POST` | `/api/node_configurations/save` | 新增或更新节点配置 (Save/Upsert) |
+| `POST` | `/api/node_configurations/toggle` | 快速启用 / 禁用节点配置 |
+| `POST` | `/api/node_configurations/clone` | 节点配置克隆复制 |
+| `DELETE` | `/api/node_configurations/delete` | 删除指定节点配置 |
+| `GET` | `/api/node_configurations/audit-logs` | 查询配置修改审计日志 |
+
+---
+
+## 3. 接口详细说明
+
+### 3.1 查询节点配置列表
+
+- **接口地址**: `GET /api/node_configurations/list`
+- **Query 参数**:
+  | 参数名 | 类型 | 必填 | 默认值 | 说明 |
+  | :--- | :--- | :--- | :--- | :--- |
+  | `role` | string | 否 | `null` | 过滤角色: `sentinel` / `booker` / `standalone` |
+  | `node_id` | string | 否 | `null` | 过滤节点标识 (支持模糊搜索) |
+  | `is_enabled` | int | 否 | `null` | 过滤启用状态: `1` (启用), `0` (禁用) |
+  | `page` | int | 否 | `1` | 当前页码 (>= 1) |
+  | `page_size` | int | 否 | `20` | 每页数量 (1 ~ 100) |
+
+- **响应报文 (Response)**:
+  ```json
+  {
+    "code": 0,
+    "message": "success",
+    "data": {
+      "total": 2,
+      "items": [
+        {
+          "id": 1,
+          "role": "sentinel",
+          "node_id": "node01",
+          "is_enabled": 1,
+          "config_hash": "6cbc001d68b050867db78f262a884ca6",
+          "description": "节点01 哨兵监控配置",
+          "created_by": "admin",
+          "updated_by": "admin",
+          "created_at": "2026-08-23T00:30:00",
+          "updated_at": "2026-08-23T00:45:00"
+        }
+      ]
+    }
+  }
+  ```
+
+---
+
+### 3.2 获取指定节点配置详情
+
+- **接口地址**: `GET /api/node_configurations/detail`
+- **Query 参数**:
+  | 参数名 | 类型 | 必填 | 说明 |
+  | :--- | :--- | :--- | :--- |
+  | `role` | string | 是 | 角色类型: `sentinel` / `booker` / `standalone` |
+  | `node_id` | string | 是 | 节点唯一标识,如 `node01` |
+
+- **响应报文 (Response)**:
+  ```json
+  {
+    "code": 0,
+    "message": "success",
+    "data": {
+      "id": 1,
+      "role": "sentinel",
+      "node_id": "node01",
+      "is_enabled": 1,
+      "config_hash": "6cbc001d68b050867db78f262a884ca6",
+      "config_content": [
+        {
+          "identifier": "vfs.ie.nl",
+          "debug": false,
+          "enable": true,
+          "need_account": true,
+          "need_proxy": true,
+          "proxy_pool": ["proxy-cheap"],
+          "proxy_cd": 300,
+          "session_max_life": 1800,
+          "active_time_start": "00:00",
+          "active_time_end": "23:59",
+          "sentinel": {
+            "account_source": "built-in",
+            "account_pool_id": "ie.nl.sentinel",
+            "target_instances": 1,
+            "account_cd": 10800,
+            "signal_ttl": 30,
+            "query_wait": {
+              "mode": "Random",
+              "fixed_wait": 10,
+              "random_min": 60,
+              "random_max": 300
+            }
+          },
+          "plugin_config": {
+            "lib_path": "plugins",
+            "plugin_name": "vfs_plugin",
+            "plugin_bin": "vfs_plugin.py",
+            "plugin_proto": "IVSPlg"
+          },
+          "appointment_types": [
+            {
+              "weight": 10,
+              "routing_key": "slot.dub.nl.tourist",
+              "city": "Dublin",
+              "visa_type": "Tourist",
+              "country": "Netherlands"
+            }
+          ],
+          "website": "https://visa.vfsglobal.com/irl/en/nld/login",
+          "free_config": {
+            "mission_code": "nld",
+            "mission_name": "Netherlands",
+            "country_code": "irl",
+            "country_name": "Ireland",
+            "culture_code": "en-US",
+            "language": "en"
+          }
+        }
+      ],
+      "description": "节点01 哨兵监控配置",
+      "created_by": "admin",
+      "updated_by": "admin",
+      "created_at": "2026-08-23T00:30:00",
+      "updated_at": "2026-08-23T00:45:00"
+    }
+  }
+  ```
+
+---
+
+### 3.3 保存 / 更新节点配置 (Save / Upsert)
+
+- **接口地址**: `POST /api/node_configurations/save`
+- **请求头**: `Content-Type: application/json`
+- **请求体 (Body)**:
+  | 字段名 | 类型 | 必填 | 默认值 | 说明 |
+  | :--- | :--- | :--- | :--- | :--- |
+  | `role` | string | 是 | - | 角色类型: `sentinel` / `booker` / `standalone` |
+  | `node_id` | string | 是 | - | 节点标识,如 `node01` |
+  | `config_content` | array / object | 是 | - | 完整的配置 JSON 内容 |
+  | `is_enabled` | int | 否 | `1` | 启用状态: `1` (启用), `0` (禁用) |
+  | `description` | string | 否 | `""` | 配置描述/用途说明 |
+  | `remark` | string | 否 | `""` | 修改原因/变更备注(记录到审计日志) |
+
+- **请求示例**:
+  ```json
+  {
+    "role": "sentinel",
+    "node_id": "node01",
+    "config_content": [
+      {
+        "identifier": "vfs.ie.nl",
+        "debug": true,
+        "enable": true
+      }
+    ],
+    "is_enabled": 1,
+    "description": "更新为调试模式",
+    "remark": "排查爱尔兰荷兰节点抓取问题"
+  }
+  ```
+
+- **响应报文 (Response)**:
+  ```json
+  {
+    "code": 0,
+    "message": "Configuration saved successfully",
+    "data": {
+      "id": 1,
+      "role": "sentinel",
+      "node_id": "node01",
+      "is_enabled": 1,
+      "config_hash": "779854f7892e9bacc6e73f32e4fa830a",
+      "config_content": [ ... ],
+      "description": "更新为调试模式",
+      "created_by": "admin",
+      "updated_by": "admin",
+      "created_at": "2026-08-23T00:30:00",
+      "updated_at": "2026-08-23T01:00:00"
+    }
+  }
+  ```
+
+---
+
+### 3.4 快速启用 / 禁用节点配置
+
+- **接口地址**: `POST /api/node_configurations/toggle`
+- **请求头**: `Content-Type: application/json`
+- **请求体 (Body)**:
+  | 字段名 | 类型 | 必填 | 说明 |
+  | :--- | :--- | :--- | :--- |
+  | `role` | string | 是 | 角色类型: `sentinel` / `booker` / `standalone` |
+  | `node_id` | string | 是 | 节点标识,如 `node01` |
+  | `is_enabled` | int | 是 | 状态: `1` (启用), `0` (禁用) |
+  | `remark` | string | 否 | 操作备注说明 |
+
+- **请求示例**:
+  ```json
+  {
+    "role": "sentinel",
+    "node_id": "node01",
+    "is_enabled": 0,
+    "remark": "临时下线维护"
+  }
+  ```
+
+- **响应报文 (Response)**:
+  ```json
+  {
+    "code": 0,
+    "message": "Configuration status updated successfully",
+    "data": {
+      "id": 1,
+      "role": "sentinel",
+      "node_id": "node01",
+      "is_enabled": 0,
+      "config_hash": "779854f7892e9bacc6e73f32e4fa830a",
+      "description": "节点01 哨兵监控配置",
+      "updated_by": "admin",
+      "updated_at": "2026-08-23T01:05:00"
+    }
+  }
+  ```
+
+---
+
+### 3.5 跨节点克隆 / 复制配置
+
+- **接口地址**: `POST /api/node_configurations/clone`
+- **请求头**: `Content-Type: application/json`
+- **请求体 (Body)**:
+  | 字段名 | 类型 | 必填 | 说明 |
+  | :--- | :--- | :--- | :--- |
+  | `source_role` | string | 是 | 源角色类型 |
+  | `source_node_id` | string | 是 | 源节点标识 |
+  | `target_role` | string | 是 | 目标角色类型 |
+  | `target_node_id` | string | 是 | 目标节点标识 |
+  | `remark` | string | 否 | 克隆操作备注 |
+
+- **请求示例**:
+  ```json
+  {
+    "source_role": "sentinel",
+    "source_node_id": "node01",
+    "target_role": "sentinel",
+    "target_node_id": "node02",
+    "remark": "扩容新节点"
+  }
+  ```
+
+- **响应报文 (Response)**:
+  ```json
+  {
+    "code": 0,
+    "message": "Configuration cloned successfully",
+    "data": {
+      "id": 2,
+      "role": "sentinel",
+      "node_id": "node02",
+      "is_enabled": 1,
+      "config_hash": "779854f7892e9bacc6e73f32e4fa830a",
+      "config_content": [ ... ],
+      "description": "Cloned from sentinel:node01. 节点01 哨兵监控配置",
+      "created_by": "admin",
+      "updated_by": "admin",
+      "created_at": "2026-08-23T01:10:00",
+      "updated_at": "2026-08-23T01:10:00"
+    }
+  }
+  ```
+
+---
+
+### 3.6 删除节点配置
+
+- **接口地址**: `DELETE /api/node_configurations/delete`
+- **Query 参数**:
+  | 参数名 | 类型 | 必填 | 说明 |
+  | :--- | :--- | :--- | :--- |
+  | `role` | string | 是 | 角色类型: `sentinel` / `booker` / `standalone` |
+  | `node_id` | string | 是 | 节点标识 |
+  | `remark` | string | 否 | 删除原因说明 |
+
+- **响应报文 (Response)**:
+  ```json
+  {
+    "code": 0,
+    "message": "Configuration deleted successfully",
+    "data": {
+      "role": "sentinel",
+      "node_id": "node02",
+      "deleted": true
+    }
+  }
+  ```
+
+---
+
+### 3.7 查询配置修改审计日志
+
+- **接口地址**: `GET /api/node_configurations/audit-logs`
+- **Query 参数**:
+  | 参数名 | 类型 | 必填 | 默认值 | 说明 |
+  | :--- | :--- | :--- | :--- | :--- |
+  | `role` | string | 否 | `null` | 过滤角色类型 |
+  | `node_id` | string | 否 | `null` | 过滤节点标识 |
+  | `page` | int | 否 | `1` | 页码 (>= 1) |
+  | `page_size` | int | 否 | `20` | 每页数量 (1 ~ 100) |
+
+- **响应报文 (Response)**:
+  ```json
+  {
+    "code": 0,
+    "message": "success",
+    "data": {
+      "total": 3,
+      "items": [
+        {
+          "id": 3,
+          "role": "sentinel",
+          "node_id": "node01",
+          "action": "UPDATE",
+          "before_hash": "6cbc001d68b050867db78f262a884ca6",
+          "after_hash": "779854f7892e9bacc6e73f32e4fa830a",
+          "operator": "admin@example.com",
+          "remark": "排查爱尔兰荷兰节点抓取问题",
+          "created_at": "2026-08-23T01:00:00"
+        },
+        {
+          "id": 2,
+          "role": "sentinel",
+          "node_id": "node01",
+          "action": "TOGGLE",
+          "before_hash": "6cbc001d68b050867db78f262a884ca6",
+          "after_hash": "6cbc001d68b050867db78f262a884ca6",
+          "operator": "admin@example.com",
+          "remark": "临时下线维护",
+          "created_at": "2026-08-23T00:50:00"
+        },
+        {
+          "id": 1,
+          "role": "sentinel",
+          "node_id": "node01",
+          "action": "CREATE",
+          "before_hash": null,
+          "after_hash": "6cbc001d68b050867db78f262a884ca6",
+          "operator": "system",
+          "remark": "Initial import from config_sentinel.json",
+          "created_at": "2026-08-23T00:30:00"
+        }
+      ]
+    }
+  }
+  ```

+ 95 - 0
scripts/import_node_configurations.py

@@ -0,0 +1,95 @@
+"""
+将 Coordinate 项目的本地 JSON 配置文件 (config_sentinel.json, config_booker.json, config_standalone.json)
+批量或按节点导入到 webapp 的 node_configurations 表中。
+
+用法示例:
+  python3 scripts/import_node_configurations.py --node-id node01 \
+      --sentinel /path/to/config_sentinel.json \
+      --booker /path/to/config_booker.json \
+      --standalone /path/to/config_standalone.json
+"""
+
+import os
+import sys
+import json
+import asyncio
+import argparse
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from app.core.database import AsyncSessionLocal
+from app.services.node_configuration_service import NodeConfigurationService
+from app.schemas.node_configuration import NodeConfigurationSaveRequest
+
+
+async def import_configs(
+    node_id: str,
+    sentinel_file: str = None,
+    booker_file: str = None,
+    standalone_file: str = None,
+    description: str = None,
+    operator: str = "import_script",
+):
+    if not node_id:
+        print("❌ Error: --node-id is required")
+        return
+
+    items = [
+        ("sentinel", sentinel_file, "哨兵轮询配置"),
+        ("booker", booker_file, "预约抢单配置"),
+        ("standalone", standalone_file, "独立 Booker 配置"),
+    ]
+
+    async with AsyncSessionLocal() as db:
+        for role, file_path, default_desc in items:
+            if not file_path:
+                continue
+
+            if not os.path.exists(file_path):
+                print(f"⚠️ [SKIP] File not found: {file_path}")
+                continue
+
+            try:
+                with open(file_path, "r", encoding="utf-8") as f:
+                    content = json.load(f)
+            except Exception as e:
+                print(f"❌ [ERROR] Failed to parse JSON file '{file_path}': {e}")
+                continue
+
+            req = NodeConfigurationSaveRequest(
+                role=role,
+                node_id=node_id,
+                config_content=content,
+                is_enabled=1,
+                description=description or f"{node_id} {default_desc} (imported from {os.path.basename(file_path)})",
+                operator=operator,
+                remark=f"Initial import from {file_path}",
+            )
+
+            try:
+                saved = await NodeConfigurationService.save_config(db, req, operator=operator)
+                print(f"✅ [SUCCESS] Imported {role} for node '{node_id}' | hash={saved.config_hash} (id={saved.id})")
+            except Exception as e:
+                print(f"❌ [ERROR] Failed to save {role} config for node '{node_id}': {e}")
+
+
+if __name__ == "__main__":
+    parser = argparse.ArgumentParser(description="Import Coordinate JSON configs to node_configurations table")
+    parser.add_argument("--node-id", type=str, required=True, help="Target node ID, e.g. node01")
+    parser.add_argument("--sentinel", type=str, help="Path to config_sentinel.json")
+    parser.add_argument("--booker", type=str, help="Path to config_booker.json")
+    parser.add_argument("--standalone", type=str, help="Path to config_standalone.json")
+    parser.add_argument("--description", type=str, help="Custom description")
+    parser.add_argument("--operator", type=str, default="migration_script", help="Operator name for audit log")
+    args = parser.parse_args()
+
+    asyncio.run(
+        import_configs(
+            node_id=args.node_id,
+            sentinel_file=args.sentinel,
+            booker_file=args.booker,
+            standalone_file=args.standalone,
+            description=args.description,
+            operator=args.operator,
+        )
+    )

+ 257 - 0
tests/test_node_configuration.py

@@ -0,0 +1,257 @@
+from datetime import datetime
+import json
+import pytest
+from unittest.mock import AsyncMock, MagicMock, patch
+from fastapi.testclient import TestClient
+
+
+from app.core.auth import get_current_user, require_min_role, RoleLevel
+from app.core.database import get_db
+from app.models.user import VasUser
+from app.models.node_configuration import NodeConfiguration, NodeConfigAuditLog
+from app.services.node_configuration_service import (
+    NodeConfigurationService,
+    calculate_config_hash,
+)
+from app.schemas.node_configuration import (
+    NodeConfigurationSaveRequest,
+    NodeConfigurationToggleRequest,
+    NodeConfigurationCloneRequest,
+    NodeConfigurationDeleteRequest,
+)
+from app.core.biz_exception import NotFoundError
+from app.main import app
+
+
+class DummyAdminUser:
+    id = "admin_01"
+    role = "admin"
+    email = "admin@example.com"
+    nickname = "SuperAdmin"
+
+
+def test_calculate_config_hash_idempotency():
+    """
+    测试不同键顺序与格式下,Canonical Hash 的幂等一致性
+    """
+    content_a = {
+        "identifier": "vfs.ie.nl",
+        "debug": False,
+        "sentinel": {"target_instances": 1, "account_pool_id": "ie.nl"},
+    }
+    content_b = {
+        "debug": False,
+        "sentinel": {"account_pool_id": "ie.nl", "target_instances": 1},
+        "identifier": "vfs.ie.nl",
+    }
+    hash_a = calculate_config_hash(content_a)
+    hash_b = calculate_config_hash(content_b)
+    assert hash_a == hash_b
+    assert len(hash_a) == 32
+
+
+@pytest.mark.anyio
+async def test_node_configuration_service_unit():
+    mock_db = AsyncMock()
+
+    # 1. Test save_config (Create)
+    mock_exec_res = MagicMock()
+    mock_exec_res.scalar_one_or_none.return_value = None
+    mock_db.execute.return_value = mock_exec_res
+
+    payload = NodeConfigurationSaveRequest(
+        role="sentinel",
+        node_id="node01",
+        config_content=[{"identifier": "vfs.ie.nl", "enable": True}],
+        is_enabled=1,
+        description="Sentinel test node",
+        operator="admin",
+        remark="Initial create",
+    )
+
+    created = await NodeConfigurationService.save_config(mock_db, payload, operator="admin")
+    assert created.role == "sentinel"
+    assert created.node_id == "node01"
+    assert len(created.config_hash) == 32
+    assert mock_db.add.call_count == 2  # config + audit_log
+    assert mock_db.commit.called
+
+    # 2. Test save_config (Update)
+    existing_obj = NodeConfiguration(
+        id=1,
+        role="sentinel",
+        node_id="node01",
+        config_content=[{"identifier": "vfs.ie.nl", "enable": True}],
+        config_hash="old_hash_1234567890123456789012",
+        is_enabled=1,
+        description="Old description",
+    )
+    mock_exec_res.scalar_one_or_none.return_value = existing_obj
+
+    update_payload = NodeConfigurationSaveRequest(
+        role="sentinel",
+        node_id="node01",
+        config_content=[{"identifier": "vfs.ie.nl", "enable": False}],
+        is_enabled=1,
+        description="Updated description",
+        operator="admin",
+        remark="Update config",
+    )
+
+    updated = await NodeConfigurationService.save_config(mock_db, update_payload, operator="admin")
+    assert updated.id == 1
+    assert updated.description == "Updated description"
+    assert updated.config_hash != "old_hash_1234567890123456789012"
+
+    # 3. Test toggle_config
+    toggled = await NodeConfigurationService.toggle_config(
+        mock_db,
+        NodeConfigurationToggleRequest(role="sentinel", node_id="node01", is_enabled=0, remark="disable"),
+        operator="admin",
+    )
+    assert toggled.is_enabled == 0
+
+    # 4. Test delete_config
+    deleted = await NodeConfigurationService.delete_config(
+        mock_db,
+        NodeConfigurationDeleteRequest(role="sentinel", node_id="node01", remark="delete"),
+        operator="admin",
+    )
+    assert deleted is True
+
+    # 5. Test get_detail not found
+    mock_exec_res.scalar_one_or_none.return_value = None
+    with pytest.raises(NotFoundError):
+        await NodeConfigurationService.get_detail(mock_db, role="sentinel", node_id="not_exist")
+
+
+def test_node_configuration_api_endpoints():
+    mock_db = AsyncMock()
+    mock_user = DummyAdminUser()
+
+    async def override_get_db():
+        yield mock_db
+
+    async def override_current_user():
+        return mock_user
+
+    app.dependency_overrides[get_db] = override_get_db
+    app.dependency_overrides[get_current_user] = override_current_user
+
+    # Mock service methods
+    sample_node = NodeConfiguration(
+        id=10,
+        role="booker",
+        node_id="worker01",
+        config_content=[{"identifier": "tls.uk.fr", "enable": True}],
+        config_hash="abc12345678901234567890123456789",
+        is_enabled=1,
+        description="Test node",
+        created_by="admin",
+        updated_by="admin",
+        created_at=datetime.utcnow(),
+        updated_at=datetime.utcnow(),
+    )
+
+    sample_log = NodeConfigAuditLog(
+        id=1,
+        role="booker",
+        node_id="worker01",
+        action="CREATE",
+        before_hash=None,
+        after_hash="abc12345678901234567890123456789",
+        operator="admin",
+        remark="Test creation",
+        created_at=datetime.utcnow(),
+    )
+
+
+    with patch.object(NodeConfigurationService, "save_config", return_value=sample_node), \
+         patch.object(NodeConfigurationService, "get_detail", return_value=sample_node), \
+         patch.object(NodeConfigurationService, "list_configs", return_value=(1, [sample_node])), \
+         patch.object(NodeConfigurationService, "toggle_config", return_value=sample_node), \
+         patch.object(NodeConfigurationService, "clone_config", return_value=sample_node), \
+         patch.object(NodeConfigurationService, "delete_config", return_value=True), \
+         patch.object(NodeConfigurationService, "get_audit_logs", return_value=(1, [sample_log])):
+
+        with TestClient(app) as client:
+            headers = {"Authorization": "Bearer test_token"}
+
+            # 1. Save
+            res_save = client.post(
+                "/api/node_configurations/save",
+                json={
+                    "role": "booker",
+                    "node_id": "worker01",
+                    "config_content": [{"identifier": "tls.uk.fr", "enable": True}],
+                    "is_enabled": 1,
+                    "description": "Test node",
+                },
+                headers=headers,
+            )
+            assert res_save.status_code == 200
+            assert res_save.json()["code"] == 0
+            assert res_save.json()["data"]["role"] == "booker"
+            assert res_save.json()["data"]["config_hash"] == "abc12345678901234567890123456789"
+
+            # 2. Detail
+            res_detail = client.get(
+                "/api/node_configurations/detail?role=booker&node_id=worker01",
+                headers=headers,
+            )
+            assert res_detail.status_code == 200
+            assert res_detail.json()["code"] == 0
+            assert res_detail.json()["data"]["node_id"] == "worker01"
+
+            # 3. List
+            res_list = client.get(
+                "/api/node_configurations/list?role=booker&page=1&page_size=10",
+                headers=headers,
+            )
+            assert res_list.status_code == 200
+            assert res_list.json()["code"] == 0
+            assert res_list.json()["data"]["total"] == 1
+            assert len(res_list.json()["data"]["items"]) == 1
+
+            # 4. Toggle
+            res_toggle = client.post(
+                "/api/node_configurations/toggle",
+                json={"role": "booker", "node_id": "worker01", "is_enabled": 0},
+                headers=headers,
+            )
+            assert res_toggle.status_code == 200
+            assert res_toggle.json()["code"] == 0
+
+            # 5. Clone
+            res_clone = client.post(
+                "/api/node_configurations/clone",
+                json={
+                    "source_role": "booker",
+                    "source_node_id": "worker01",
+                    "target_role": "booker",
+                    "target_node_id": "worker02",
+                },
+                headers=headers,
+            )
+            assert res_clone.status_code == 200
+            assert res_clone.json()["code"] == 0
+
+            # 6. Audit Logs
+            res_logs = client.get(
+                "/api/node_configurations/audit-logs?role=booker&node_id=worker01",
+                headers=headers,
+            )
+            assert res_logs.status_code == 200
+            assert res_logs.json()["code"] == 0
+            assert res_logs.json()["data"]["total"] == 1
+
+            # 7. Delete
+            res_del = client.delete(
+                "/api/node_configurations/delete?role=booker&node_id=worker01",
+                headers=headers,
+            )
+            assert res_del.status_code == 200
+            assert res_del.json()["code"] == 0
+            assert res_del.json()["data"]["deleted"] is True
+
+    app.dependency_overrides.clear()