| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396 |
- import copy
- from typing import Dict, Any, List, Optional, Tuple, Type
- from sqlalchemy.ext.asyncio import AsyncSession
- 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,
- )
- 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
- @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 _record_revision(
- cls,
- db: AsyncSession,
- 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",
- )
- db.add(rev)
- await db.flush()
- return rev
- @classmethod
- async def list_entries(
- cls,
- db: AsyncSession,
- entry_type: str,
- page: int = 1,
- page_size: int = 20,
- 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(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.enable), 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
- @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 create_entry(
- cls,
- db: AsyncSession,
- 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:
- raise BizException(
- code=40902,
- message=f"Identifier '{identifier}' on node '{node_id}' already exists",
- http_status=409,
- )
- # 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,
- )
- await db.commit()
- await db.refresh(entry)
- return entry
- @classmethod
- async def sparse_update_entry(
- cls,
- db: AsyncSession,
- 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,
- )
- await db.commit()
- await db.refresh(entry)
- return entry
- @classmethod
- async def toggle_enable(
- cls,
- db: AsyncSession,
- 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,
- )
- await db.commit()
- await db.refresh(entry)
- return entry
- @classmethod
- async def delete_entry(
- cls,
- db: AsyncSession,
- entry_type: str,
- entry_id: int,
- confirm_purge: bool = False,
- ) -> bool:
- 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_revisions(
- cls,
- db: AsyncSession,
- 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())
- @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,
- )
- 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,
- )
- await db.commit()
- await db.refresh(entry)
- return entry
|