"""Persist key Douyu role API responses for production diagnosis.""" from __future__ import annotations from collections.abc import Mapping, Sequence from datetime import UTC, datetime from typing import Any from sqlalchemy.orm import Session from ..models import DouyuRoleApiLog from .account_binding import binding_snapshot _SENSITIVE_KEY_MARKERS = ( "cookie", "authorization", "csrf", "acf_ccn", "token", "password", ) def _redact(value: Any, *, depth: int = 0) -> Any: if depth > 12: return "" if isinstance(value, Mapping): cleaned: dict[str, Any] = {} for raw_key, raw_value in value.items(): key = str(raw_key) if any(marker in key.casefold() for marker in _SENSITIVE_KEY_MARKERS): cleaned[key] = "" else: cleaned[key] = _redact(raw_value, depth=depth + 1) return cleaned if isinstance(value, (list, tuple, set)): return [_redact(item, depth=depth + 1) for item in value] if isinstance(value, datetime): moment = value if value.tzinfo else value.replace(tzinfo=UTC) return moment.isoformat() if value is None or isinstance(value, (str, int, float, bool)): return value return str(value) def record_role_api_candidates( db: Session, *, account_id: int | None, candidates: Sequence[Mapping[str, Any]], scope: str, stage: str, source: str, task_id: int | None = None, ) -> int: """Append successful role query responses; callers decide when they matter.""" if account_id is None: return 0 rows: list[DouyuRoleApiLog] = [] for candidate in candidates: info = dict(candidate) snapshot = binding_snapshot(info) act_alias = str(info.get("act_alias") or "") rows.append( DouyuRoleApiLog( account_id=int(account_id), task_id=int(task_id) if task_id is not None else None, scope=str(scope or "elite")[:16], stage=str(stage or "")[:48], source=str(source or "")[:64], act_alias=act_alias[:64], api_version=str(info.get("api_version") or "")[:16], role_name=str(snapshot["role_name"] or "")[:128], area_name=str(snapshot["area_name"] or "")[:128], plat_name=str(snapshot["plat_name"] or "")[:128], is_bound_act=bool(snapshot["is_bound_act"]), is_bound_role=bool(snapshot["is_bound_role"]), need_bind_act=bool(snapshot["need_bind_act"]), need_bind_role=bool(snapshot["need_bind_role"]), change_role_wait_time=_to_int(snapshot["change_role_wait_time"]), can_change_time=_to_int(snapshot["can_change_time"]), request_json=_redact( { "scope": scope, "stage": stage, "act_alias": act_alias, "api_version": info.get("api_version"), } ), response_json=_redact(info.get("raw") or info), ) ) if not rows: return 0 db.add_all(rows) return len(rows) def record_role_api_response( db: Session, *, account_id: int | None, response: Mapping[str, Any] | None, scope: str, stage: str, source: str, act_alias: str = "", task_id: int | None = None, ) -> int: """Append a write/confirm response that has no normalized role candidate.""" if account_id is None: return 0 db.add( DouyuRoleApiLog( account_id=int(account_id), task_id=int(task_id) if task_id is not None else None, scope=str(scope or "elite")[:16], stage=str(stage or "")[:48], source=str(source or "")[:64], act_alias=str(act_alias or "")[:64], request_json=_redact({"scope": scope, "act_alias": act_alias}), response_json=_redact(dict(response or {})), ) ) return 1 def _to_int(value: Any) -> int | None: if value is None or value == "": return None try: return int(float(value)) except (TypeError, ValueError): return None __all__ = [ "record_role_api_candidates", "record_role_api_response", ]