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)