|
|
@@ -1,286 +1,396 @@
|
|
|
-import json
|
|
|
-import hashlib
|
|
|
-from typing import Optional, List, Tuple, Any
|
|
|
-from sqlalchemy import select, func, desc, delete
|
|
|
+import copy
|
|
|
+from typing import Dict, Any, List, Optional, Tuple, Type
|
|
|
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,
|
|
|
+from sqlalchemy import select, func, desc
|
|
|
+from sqlalchemy.orm.attributes import flag_modified
|
|
|
+
|
|
|
+from app.core.biz_exception import BizException
|
|
|
+from app.models.node_configuration import (
|
|
|
+ BookerEntry,
|
|
|
+ SentinelEntry,
|
|
|
+ StandaloneEntry,
|
|
|
+ NodeConfigurationRevision,
|
|
|
)
|
|
|
|
|
|
|
|
|
-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:
|
|
|
+ ENTRY_MODEL_MAP: Dict[str, Type[Any]] = {
|
|
|
+ "booker": BookerEntry,
|
|
|
+ "sentinel": SentinelEntry,
|
|
|
+ "standalone": StandaloneEntry,
|
|
|
+ }
|
|
|
+
|
|
|
+ @classmethod
|
|
|
+ def get_model(cls, entry_type: str) -> Type[Any]:
|
|
|
+ model = cls.ENTRY_MODEL_MAP.get(entry_type.lower())
|
|
|
+ if not model:
|
|
|
+ raise BizException(
|
|
|
+ code=40000,
|
|
|
+ message=f"Invalid entry_type: '{entry_type}'. Must be one of {list(cls.ENTRY_MODEL_MAP.keys())}",
|
|
|
+ http_status=400,
|
|
|
+ )
|
|
|
+ return model
|
|
|
|
|
|
- @staticmethod
|
|
|
- def compute_hash(content: Any) -> str:
|
|
|
- return calculate_config_hash(content)
|
|
|
+ @classmethod
|
|
|
+ def _to_snapshot(cls, obj: Any) -> Dict[str, Any]:
|
|
|
+ """Serialize SQLAlchemy model columns to dict snapshot"""
|
|
|
+ snapshot = {}
|
|
|
+ for column in obj.__table__.columns:
|
|
|
+ val = getattr(obj, column.name)
|
|
|
+ if hasattr(val, "isoformat"):
|
|
|
+ val = val.isoformat()
|
|
|
+ snapshot[column.name] = copy.deepcopy(val)
|
|
|
+ return snapshot
|
|
|
|
|
|
@classmethod
|
|
|
- async def get_detail(
|
|
|
+ async def _record_revision(
|
|
|
cls,
|
|
|
db: AsyncSession,
|
|
|
- role: str,
|
|
|
- node_id: str,
|
|
|
- ) -> NodeConfiguration:
|
|
|
- """
|
|
|
- 获取指定角色与节点的配置详情(供 Worker 轮询与详情展示)
|
|
|
- """
|
|
|
- stmt = select(NodeConfiguration).where(
|
|
|
- NodeConfiguration.role == role,
|
|
|
- NodeConfiguration.node_id == node_id,
|
|
|
+ entry_type: str,
|
|
|
+ entry_id: int,
|
|
|
+ version: int,
|
|
|
+ action: str,
|
|
|
+ snapshot: Dict[str, Any],
|
|
|
+ updated_by: str,
|
|
|
+ ) -> NodeConfigurationRevision:
|
|
|
+ rev = NodeConfigurationRevision(
|
|
|
+ entry_type=entry_type,
|
|
|
+ entry_id=entry_id,
|
|
|
+ version=version,
|
|
|
+ action=action,
|
|
|
+ snapshot=snapshot,
|
|
|
+ updated_by=updated_by or "system",
|
|
|
)
|
|
|
- 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
|
|
|
+ db.add(rev)
|
|
|
+ await db.flush()
|
|
|
+ return rev
|
|
|
|
|
|
@classmethod
|
|
|
- async def list_configs(
|
|
|
+ async def list_entries(
|
|
|
cls,
|
|
|
db: AsyncSession,
|
|
|
- role: Optional[str] = None,
|
|
|
- node_id: Optional[str] = None,
|
|
|
- is_enabled: Optional[int] = None,
|
|
|
+ entry_type: str,
|
|
|
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)
|
|
|
+ identifier: Optional[str] = None,
|
|
|
+ node_id: Optional[str] = None,
|
|
|
+ order_id: Optional[str] = None,
|
|
|
+ ) -> Tuple[int, List[Any]]:
|
|
|
+ model = cls.get_model(entry_type)
|
|
|
+ stmt = select(model)
|
|
|
+ count_stmt = select(func.count(model.id))
|
|
|
+
|
|
|
+ if identifier:
|
|
|
+ stmt = stmt.where(model.identifier.like(f"%{identifier}%"))
|
|
|
+ count_stmt = count_stmt.where(model.identifier.like(f"%{identifier}%"))
|
|
|
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)
|
|
|
+ stmt = stmt.where(model.node_id == node_id)
|
|
|
+ count_stmt = count_stmt.where(model.node_id == node_id)
|
|
|
+ if order_id and hasattr(model, "order_id"):
|
|
|
+ stmt = stmt.where(model.order_id == order_id)
|
|
|
+ count_stmt = count_stmt.where(model.order_id == order_id)
|
|
|
+
|
|
|
+ total = await db.scalar(count_stmt) or 0
|
|
|
+ offset = (page - 1) * page_size
|
|
|
+ stmt = stmt.order_by(desc(model.updated_at), desc(model.id)).offset(offset).limit(page_size)
|
|
|
+ result = await db.execute(stmt)
|
|
|
+ items = list(result.scalars().all())
|
|
|
+ return total, items
|
|
|
|
|
|
- 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 get_entry(
|
|
|
+ cls, db: AsyncSession, entry_type: str, entry_id: int
|
|
|
+ ) -> Any:
|
|
|
+ model = cls.get_model(entry_type)
|
|
|
+ stmt = select(model).where(model.id == entry_id)
|
|
|
+ entry = (await db.execute(stmt)).scalar_one_or_none()
|
|
|
+ if not entry:
|
|
|
+ raise BizException(
|
|
|
+ code=40400,
|
|
|
+ message=f"Configuration entry ({entry_type} ID: {entry_id}) not found",
|
|
|
+ http_status=404,
|
|
|
+ )
|
|
|
+ return entry
|
|
|
|
|
|
@classmethod
|
|
|
- async def save_config(
|
|
|
+ async def create_entry(
|
|
|
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()
|
|
|
+ entry_type: str,
|
|
|
+ data: Dict[str, Any],
|
|
|
+ operator: str = "system",
|
|
|
+ ) -> Any:
|
|
|
+ model = cls.get_model(entry_type)
|
|
|
+ node_id = data.get("node_id") or "default"
|
|
|
+ identifier = data.get("identifier")
|
|
|
+ if not identifier:
|
|
|
+ raise BizException(
|
|
|
+ code=40000,
|
|
|
+ message="Field 'identifier' is required",
|
|
|
+ http_status=400,
|
|
|
+ )
|
|
|
|
|
|
+ # Check duplicate (node_id, identifier)
|
|
|
+ check_stmt = select(model).where(
|
|
|
+ model.node_id == node_id, model.identifier == identifier
|
|
|
+ )
|
|
|
+ existing = (await db.execute(check_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,
|
|
|
+ raise BizException(
|
|
|
+ code=40902,
|
|
|
+ message=f"Identifier '{identifier}' on node '{node_id}' already exists",
|
|
|
+ http_status=409,
|
|
|
)
|
|
|
- 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}",
|
|
|
+ # Prepare model payload
|
|
|
+ entry_data = data.copy()
|
|
|
+ entry_data["node_id"] = node_id
|
|
|
+ entry_data["enable"] = 0 # Force disabled upon creation
|
|
|
+ entry_data["updated_by"] = operator
|
|
|
+ entry_data["version"] = 1
|
|
|
+
|
|
|
+ # Instantiate
|
|
|
+ valid_cols = {c.name for c in model.__table__.columns}
|
|
|
+ filtered_data = {k: v for k, v in entry_data.items() if k in valid_cols}
|
|
|
+ entry = model(**filtered_data)
|
|
|
+ db.add(entry)
|
|
|
+ await db.flush()
|
|
|
+
|
|
|
+ # Record revision
|
|
|
+ snapshot = cls._to_snapshot(entry)
|
|
|
+ await cls._record_revision(
|
|
|
+ db=db,
|
|
|
+ entry_type=entry_type,
|
|
|
+ entry_id=entry.id,
|
|
|
+ version=entry.version,
|
|
|
+ action="create",
|
|
|
+ snapshot=snapshot,
|
|
|
+ updated_by=operator,
|
|
|
)
|
|
|
- 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
|
|
|
+ await db.refresh(entry)
|
|
|
+ return entry
|
|
|
|
|
|
@classmethod
|
|
|
- async def toggle_config(
|
|
|
+ async def sparse_update_entry(
|
|
|
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}",
|
|
|
+ entry_type: str,
|
|
|
+ entry_id: int,
|
|
|
+ set_data: Optional[Dict[str, Any]] = None,
|
|
|
+ clear_fields: Optional[List[str]] = None,
|
|
|
+ base_version: Optional[int] = None,
|
|
|
+ operator: str = "system",
|
|
|
+ ) -> Any:
|
|
|
+ entry = await cls.get_entry(db, entry_type, entry_id)
|
|
|
+
|
|
|
+ set_data = set_data or {}
|
|
|
+ clear_fields = clear_fields or []
|
|
|
+
|
|
|
+ # 1. Apply set_data with dot-path support
|
|
|
+ for path_key, val in set_data.items():
|
|
|
+ # Strip leading 'payload.' if present
|
|
|
+ clean_key = path_key[8:] if path_key.startswith("payload.") else path_key
|
|
|
+
|
|
|
+ if "." in clean_key:
|
|
|
+ root_field, *nested_keys = clean_key.split(".")
|
|
|
+ if hasattr(entry, root_field):
|
|
|
+ root_val = getattr(entry, root_field)
|
|
|
+ if not isinstance(root_val, dict):
|
|
|
+ root_val = {}
|
|
|
+ else:
|
|
|
+ root_val = copy.deepcopy(root_val)
|
|
|
+
|
|
|
+ curr = root_val
|
|
|
+ for nk in nested_keys[:-1]:
|
|
|
+ if nk not in curr or not isinstance(curr[nk], dict):
|
|
|
+ curr[nk] = {}
|
|
|
+ curr = curr[nk]
|
|
|
+ curr[nested_keys[-1]] = val
|
|
|
+
|
|
|
+ setattr(entry, root_field, root_val)
|
|
|
+ flag_modified(entry, root_field)
|
|
|
+ else:
|
|
|
+ if hasattr(entry, clean_key) and clean_key not in ("id", "created_at"):
|
|
|
+ if isinstance(val, (dict, list)):
|
|
|
+ val = copy.deepcopy(val)
|
|
|
+ setattr(entry, clean_key, val)
|
|
|
+ flag_modified(entry, clean_key)
|
|
|
+ else:
|
|
|
+ setattr(entry, clean_key, val)
|
|
|
+
|
|
|
+ # 2. Apply clear_fields
|
|
|
+ default_empty_map = {
|
|
|
+ "proxy_pool": [],
|
|
|
+ "appointment_types": [],
|
|
|
+ "booker": {},
|
|
|
+ "sentinel": {},
|
|
|
+ "account": {},
|
|
|
+ "query_wait": {},
|
|
|
+ "user_preferences": {},
|
|
|
+ "plugin_config": {},
|
|
|
+ "free_config": {},
|
|
|
+ "website": "",
|
|
|
+ "order_id": None,
|
|
|
+ }
|
|
|
+ for field in clear_fields:
|
|
|
+ clean_field = field[8:] if field.startswith("payload.") else field
|
|
|
+ if hasattr(entry, clean_field) and clean_field not in ("id", "created_at", "version"):
|
|
|
+ default_val = default_empty_map.get(clean_field, None)
|
|
|
+ setattr(entry, clean_field, default_val)
|
|
|
+ if isinstance(default_val, (dict, list)):
|
|
|
+ flag_modified(entry, clean_field)
|
|
|
+
|
|
|
+ # Increment version and update operator
|
|
|
+ entry.version = (entry.version or 0) + 1
|
|
|
+ entry.updated_by = operator
|
|
|
+ await db.flush()
|
|
|
+
|
|
|
+ # Record revision snapshot
|
|
|
+ snapshot = cls._to_snapshot(entry)
|
|
|
+ await cls._record_revision(
|
|
|
+ db=db,
|
|
|
+ entry_type=entry_type,
|
|
|
+ entry_id=entry.id,
|
|
|
+ version=entry.version,
|
|
|
+ action="update",
|
|
|
+ snapshot=snapshot,
|
|
|
+ updated_by=operator,
|
|
|
)
|
|
|
- db.add(audit_log)
|
|
|
|
|
|
await db.commit()
|
|
|
- await db.refresh(existing)
|
|
|
- return existing
|
|
|
+ await db.refresh(entry)
|
|
|
+ return entry
|
|
|
|
|
|
@classmethod
|
|
|
- async def clone_config(
|
|
|
+ async def toggle_enable(
|
|
|
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,
|
|
|
+ entry_type: str,
|
|
|
+ entry_id: int,
|
|
|
+ enable: bool,
|
|
|
+ base_version: Optional[int] = None,
|
|
|
+ operator: str = "system",
|
|
|
+ ) -> Any:
|
|
|
+ entry = await cls.get_entry(db, entry_type, entry_id)
|
|
|
+ entry.enable = 1 if enable else 0
|
|
|
+ entry.version = (entry.version or 0) + 1
|
|
|
+ entry.updated_by = operator
|
|
|
+ await db.flush()
|
|
|
+
|
|
|
+ snapshot = cls._to_snapshot(entry)
|
|
|
+ await cls._record_revision(
|
|
|
+ db=db,
|
|
|
+ entry_type=entry_type,
|
|
|
+ entry_id=entry.id,
|
|
|
+ version=entry.version,
|
|
|
+ action="enable" if enable else "disable",
|
|
|
+ snapshot=snapshot,
|
|
|
+ updated_by=operator,
|
|
|
)
|
|
|
- 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)
|
|
|
+
|
|
|
+ await db.commit()
|
|
|
+ await db.refresh(entry)
|
|
|
+ return entry
|
|
|
|
|
|
@classmethod
|
|
|
- async def delete_config(
|
|
|
+ async def delete_entry(
|
|
|
cls,
|
|
|
db: AsyncSession,
|
|
|
- req: NodeConfigurationDeleteRequest,
|
|
|
- operator: Optional[str] = None,
|
|
|
+ entry_type: str,
|
|
|
+ entry_id: int,
|
|
|
+ confirm_purge: bool = False,
|
|
|
) -> 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)
|
|
|
+ model = cls.get_model(entry_type)
|
|
|
+ entry = await cls.get_entry(db, entry_type, entry_id)
|
|
|
+
|
|
|
+ # Deletion guard: count remaining entries for this entry_type
|
|
|
+ total_count = await db.scalar(select(func.count(model.id))) or 0
|
|
|
+ if total_count <= 1 and not confirm_purge:
|
|
|
+ raise BizException(
|
|
|
+ code=40000,
|
|
|
+ message="Deleting the last entry requires confirm_purge=true",
|
|
|
+ http_status=400,
|
|
|
+ )
|
|
|
+
|
|
|
+ await db.delete(entry)
|
|
|
await db.commit()
|
|
|
return True
|
|
|
|
|
|
@classmethod
|
|
|
- async def get_audit_logs(
|
|
|
+ async def get_revisions(
|
|
|
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)
|
|
|
+ entry_type: str,
|
|
|
+ entry_id: int,
|
|
|
+ ) -> List[NodeConfigurationRevision]:
|
|
|
+ # Validate existence
|
|
|
+ await cls.get_entry(db, entry_type, entry_id)
|
|
|
+
|
|
|
+ stmt = (
|
|
|
+ select(NodeConfigurationRevision)
|
|
|
+ .where(
|
|
|
+ NodeConfigurationRevision.entry_type == entry_type,
|
|
|
+ NodeConfigurationRevision.entry_id == entry_id,
|
|
|
+ )
|
|
|
+ .order_by(desc(NodeConfigurationRevision.id))
|
|
|
+ )
|
|
|
+ result = await db.execute(stmt)
|
|
|
+ return list(result.scalars().all())
|
|
|
|
|
|
- total = (await db.execute(count_stmt)).scalar() or 0
|
|
|
+ @classmethod
|
|
|
+ async def rollback_revision(
|
|
|
+ cls,
|
|
|
+ db: AsyncSession,
|
|
|
+ entry_type: str,
|
|
|
+ entry_id: int,
|
|
|
+ revision_id: int,
|
|
|
+ base_version: Optional[int] = None,
|
|
|
+ operator: str = "system",
|
|
|
+ ) -> Any:
|
|
|
+ entry = await cls.get_entry(db, entry_type, entry_id)
|
|
|
+
|
|
|
+ rev_stmt = select(NodeConfigurationRevision).where(
|
|
|
+ NodeConfigurationRevision.id == revision_id,
|
|
|
+ NodeConfigurationRevision.entry_type == entry_type,
|
|
|
+ NodeConfigurationRevision.entry_id == entry_id,
|
|
|
+ )
|
|
|
+ rev = (await db.execute(rev_stmt)).scalar_one_or_none()
|
|
|
+ if not rev:
|
|
|
+ raise BizException(
|
|
|
+ code=40400,
|
|
|
+ message=f"Revision {revision_id} for {entry_type} entry {entry_id} not found",
|
|
|
+ http_status=404,
|
|
|
+ )
|
|
|
|
|
|
- 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()
|
|
|
+ snapshot = rev.snapshot or {}
|
|
|
+ model = cls.get_model(entry_type)
|
|
|
+ ignore_cols = {"id", "created_at", "updated_at", "version"}
|
|
|
+ for col in model.__table__.columns:
|
|
|
+ if col.name not in ignore_cols and col.name in snapshot:
|
|
|
+ val = snapshot[col.name]
|
|
|
+ if isinstance(val, (dict, list)):
|
|
|
+ val = copy.deepcopy(val)
|
|
|
+ setattr(entry, col.name, val)
|
|
|
+ flag_modified(entry, col.name)
|
|
|
+ else:
|
|
|
+ setattr(entry, col.name, val)
|
|
|
+
|
|
|
+ entry.version = (entry.version or 0) + 1
|
|
|
+ entry.updated_by = operator
|
|
|
+ await db.flush()
|
|
|
+
|
|
|
+ new_snapshot = cls._to_snapshot(entry)
|
|
|
+ await cls._record_revision(
|
|
|
+ db=db,
|
|
|
+ entry_type=entry_type,
|
|
|
+ entry_id=entry.id,
|
|
|
+ version=entry.version,
|
|
|
+ action="rollback",
|
|
|
+ snapshot=new_snapshot,
|
|
|
+ updated_by=operator,
|
|
|
+ )
|
|
|
|
|
|
- return total, list(result)
|
|
|
+ await db.commit()
|
|
|
+ await db.refresh(entry)
|
|
|
+ return entry
|