mum / api_server /admin_console_router.py
muzi
Add workspace create and trial activation
0c76d87
Raw History Blame Contribute Delete
89.2 kB
import os import json import signal import time from collections import deque from datetime import datetime, timedelta, timezone from pathlib import Path from threading import Lock, Thread from typing import Any, Callable, Dict, List, Optional from fastapi import APIRouter, Header, HTTPException, Request from app.services.bootstrap_settings_service import ( BOOTSTRAP_SETTING_SPECS, RUNTIME_SETTING_SPECS, apply_settings, snapshot_settings, ) _USAGE_MAX_LINES_CAP = 50000 _USAGE_EVENTS_CACHE_LOCK = Lock() _USAGE_EVENTS_CACHE: Dict[str, Any] = { "path": "", "max_keep": 0, "mtime_ns": -1, "size": -1, "built_at": 0.0, "result": None, } _READY_ACCOUNT_STATUSES = {"ready", "oauth_ok", "verified"} def _to_bool(v: Any, default: bool = False) -> bool: if v is None: return default if isinstance(v, bool): return v return str(v).strip().lower() in ("1", "true", "yes", "y", "on") def _runtime_settings_snapshot(settings) -> Dict[str, Any]: return snapshot_settings(settings, RUNTIME_SETTING_SPECS) def _trigger_self_restart(delay_sec: float = 0.3) -> None: def _worker() -> None: try: time.sleep(max(float(delay_sec), 0.05)) except Exception: pass try: os.kill(os.getpid(), signal.SIGTERM) except Exception: os._exit(0) Thread(target=_worker, daemon=True).start() def _parse_emails_text(text: str) -> List[Dict[str, str]]: out: List[Dict[str, str]] = [] seen = set() for raw in str(text or "").splitlines(): line = raw.strip().lstrip("\ufeff") if not line or line.startswith("#"): continue if "," in line: email, password = line.split(",", 1) elif "\t" in line: email, password = line.split("\t", 1) else: email, password = line, "" email = email.strip() password = password.strip() if not email: continue key = email.lower() if key in seen: continue seen.add(key) out.append({"email": email, "password": password}) return out def _parse_items(payload: Dict[str, Any]) -> List[Dict[str, str]]: if isinstance(payload.get("emails_text"), str) and payload.get("emails_text", "").strip(): return _parse_emails_text(str(payload.get("emails_text"))) rows = payload.get("items") out: List[Dict[str, str]] = [] seen = set() if isinstance(rows, list): for item in rows: if isinstance(item, str): email = item.strip() password = "" elif isinstance(item, dict): email = str(item.get("email") or "").strip() password = str(item.get("password") or "").strip() else: continue if not email: continue key = email.lower() if key in seen: continue seen.add(key) out.append({"email": email, "password": password}) return out def _jsonl_log_path(filename: str) -> Path: base = Path(str(filename or "").strip() or "openai_adapter_run.jsonl").name log_dir = str(os.getenv("JSONL_LOG_DIR", "") or "").strip() if log_dir: return Path(log_dir) / base return Path(base) def _safe_int(v: Any) -> Optional[int]: try: if v is None: return None return int(v) except Exception: return None def _safe_float(v: Any) -> Optional[float]: try: if v is None: return None return float(v) except Exception: return None def _parse_iso_utc(ts: Any) -> Optional[datetime]: if not isinstance(ts, str): return None raw = ts.strip() if not raw: return None try: dt = datetime.fromisoformat(raw.replace("Z", "+00:00")) except Exception: return None if dt.tzinfo is None: dt = dt.replace(tzinfo=timezone.utc) return dt.astimezone(timezone.utc) def _normalize_usage_event(row: Dict[str, Any], source: str) -> Optional[Dict[str, Any]]: dt = _parse_iso_utc(row.get("ts")) if dt is None: return None prompt_tokens = max(_safe_int(row.get("prompt_tokens")) or 0, 0) completion_tokens = max(_safe_int(row.get("completion_tokens")) or 0, 0) total_tokens = _safe_int(row.get("total_tokens")) if total_tokens is None: total_tokens = prompt_tokens + completion_tokens total_tokens = max(total_tokens, 0) cached_tokens = max(_safe_int(row.get("cached_tokens")) or 0, 0) reasoning_tokens = max(_safe_int(row.get("reasoning_tokens")) or 0, 0) model = str(row.get("model") or "").strip() or "unknown" status = str(row.get("status") or "").strip().lower() success = _to_bool(row.get("success"), default=(status not in ("failed", "canceled", "timeout"))) runtime = _safe_float(row.get("runtime")) credits_used = _safe_float(row.get("credits_used")) return { "ts": dt.isoformat().replace("+00:00", "Z"), "dt": dt, "source": source, "model": model, "success": bool(success), "status": status or ("success" if success else "failed"), "prompt_tokens": prompt_tokens, "completion_tokens": completion_tokens, "total_tokens": total_tokens, "cached_tokens": cached_tokens, "reasoning_tokens": reasoning_tokens, "tokens_estimated": _to_bool(row.get("tokens_estimated"), default=(source != "usage_event")), "stream": _to_bool(row.get("stream"), default=False), "conversation_id": str(row.get("conversation_id") or ""), "account_email": str(row.get("account_email") or row.get("email") or ""), "execution_id": row.get("execution_id"), "app_id": row.get("app_id"), "runtime": runtime, "credits_used": credits_used, "error": str(row.get("error") or ""), } def _collect_usage_events(max_lines: int = 200000) -> Dict[str, Any]: path = _jsonl_log_path("openai_adapter_run.jsonl") if not path.exists(): return {"source": "none", "events": [], "path": str(path)} try: st = path.stat() mtime_ns = int(st.st_mtime_ns) size = int(st.st_size) except OSError: return {"source": "none", "events": [], "path": str(path)} ttl_raw = _safe_int(os.getenv("USAGE_CACHE_TTL_SEC", "5")) cache_ttl = max(ttl_raw if ttl_raw is not None else 5, 0) max_keep = min(max(int(max_lines), 1), _USAGE_MAX_LINES_CAP) cache_now = time.time() with _USAGE_EVENTS_CACHE_LOCK: cached = _USAGE_EVENTS_CACHE.get("result") if ( cache_ttl > 0 and isinstance(cached, dict) and _USAGE_EVENTS_CACHE.get("path") == str(path) and _USAGE_EVENTS_CACHE.get("max_keep") == max_keep and _USAGE_EVENTS_CACHE.get("mtime_ns") == mtime_ns and _USAGE_EVENTS_CACHE.get("size") == size and (cache_now - float(_USAGE_EVENTS_CACHE.get("built_at") or 0.0)) <= cache_ttl ): return cached usage_rows: List[Dict[str, Any]] = [] legacy_rows: List[Dict[str, Any]] = [] # Keep the latest N lines instead of the oldest N lines. # Otherwise stats will appear "stuck" once the log grows beyond max_lines. tail_lines = deque(maxlen=max_keep) with path.open("r", encoding="utf-8", errors="ignore") as f: for raw in f: tail_lines.append(raw) for raw in tail_lines: text = raw.strip() if not text: continue try: row = json.loads(text) except Exception: continue if not isinstance(row, dict): continue event = str(row.get("event") or "").strip() if event == "usage_event": normalized = _normalize_usage_event(row, source="usage_event") if normalized is not None: usage_rows.append(normalized) continue if event in ( "app_created_no_reuse", "app_created_for_conversation", "app_reused_for_conversation", "app_recreated_for_conversation", ): normalized = _normalize_usage_event( { "ts": row.get("ts"), "model": "unknown", "success": True, "status": "success", "prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0, "tokens_estimated": True, "stream": False, "conversation_id": row.get("conversation_id"), "account_email": row.get("email", ""), "app_id": row.get("app_id"), }, source="legacy_log", ) if normalized is not None: legacy_rows.append(normalized) continue if event in ("account_chat_failed", "account_stream_failed"): normalized = _normalize_usage_event( { "ts": row.get("ts"), "model": "unknown", "success": False, "status": "failed", "prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0, "tokens_estimated": True, "stream": event == "account_stream_failed", "conversation_id": row.get("conversation_id"), "account_email": row.get("email", ""), "error": row.get("error", ""), }, source="legacy_log", ) if normalized is not None: legacy_rows.append(normalized) result = {"source": "usage_event", "events": usage_rows, "path": str(path)} if usage_rows else { "source": "legacy_log", "events": legacy_rows, "path": str(path), } with _USAGE_EVENTS_CACHE_LOCK: _USAGE_EVENTS_CACHE["path"] = str(path) _USAGE_EVENTS_CACHE["max_keep"] = max_keep _USAGE_EVENTS_CACHE["mtime_ns"] = mtime_ns _USAGE_EVENTS_CACHE["size"] = size _USAGE_EVENTS_CACHE["built_at"] = time.time() _USAGE_EVENTS_CACHE["result"] = result return result def _build_usage_snapshot( rows: List[Dict[str, Any]], *, source: str, log_path: str, days: int = 14, hours: int = 24, model_limit: int = 30, events_limit: int = 200, ) -> Dict[str, Any]: days = max(int(days), 1) hours = max(int(hours), 1) model_limit = max(int(model_limit), 1) events_limit = max(int(events_limit), 1) now = datetime.now(timezone.utc) day_floor = (now - timedelta(days=days - 1)).replace(hour=0, minute=0, second=0, microsecond=0) hour_floor = (now - timedelta(hours=hours - 1)).replace(minute=0, second=0, microsecond=0) rows_sorted = sorted((r for r in rows if isinstance(r.get("dt"), datetime)), key=lambda x: x["dt"]) rows_window = [r for r in rows_sorted if r["dt"] >= day_floor] rows_hour_window = [r for r in rows_sorted if r["dt"] >= hour_floor] summary = { "total_requests": 0, "success_count": 0, "failure_count": 0, "success_rate": 0.0, "prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0, "cached_tokens": 0, "reasoning_tokens": 0, "unique_models": 0, "avg_tokens_per_request": 0.0, "last_event_at": "", } by_model: Dict[str, Dict[str, Any]] = {} model_set = set() for r in rows_window: summary["total_requests"] += 1 if r.get("success"): summary["success_count"] += 1 else: summary["failure_count"] += 1 summary["prompt_tokens"] += int(r.get("prompt_tokens") or 0) summary["completion_tokens"] += int(r.get("completion_tokens") or 0) summary["total_tokens"] += int(r.get("total_tokens") or 0) summary["cached_tokens"] += int(r.get("cached_tokens") or 0) summary["reasoning_tokens"] += int(r.get("reasoning_tokens") or 0) summary["last_event_at"] = r["ts"] model = str(r.get("model") or "unknown") model_set.add(model) stat = by_model.get(model) if stat is None: stat = { "model": model, "requests": 0, "success_count": 0, "failure_count": 0, "prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0, "last_seen_at": "", } by_model[model] = stat stat["requests"] += 1 if r.get("success"): stat["success_count"] += 1 else: stat["failure_count"] += 1 stat["prompt_tokens"] += int(r.get("prompt_tokens") or 0) stat["completion_tokens"] += int(r.get("completion_tokens") or 0) stat["total_tokens"] += int(r.get("total_tokens") or 0) stat["last_seen_at"] = r["ts"] if summary["total_requests"] > 0: summary["success_rate"] = round(100.0 * summary["success_count"] / summary["total_requests"], 2) summary["avg_tokens_per_request"] = round(summary["total_tokens"] / summary["total_requests"], 2) summary["unique_models"] = len(model_set) day_buckets: Dict[str, Dict[str, Any]] = {} cursor = day_floor while cursor <= now: key = cursor.strftime("%Y-%m-%d") day_buckets[key] = { "bucket": key, "requests": 0, "success_count": 0, "failure_count": 0, "prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0, } cursor += timedelta(days=1) for r in rows_window: key = r["dt"].strftime("%Y-%m-%d") b = day_buckets.get(key) if b is None: continue b["requests"] += 1 if r.get("success"): b["success_count"] += 1 else: b["failure_count"] += 1 b["prompt_tokens"] += int(r.get("prompt_tokens") or 0) b["completion_tokens"] += int(r.get("completion_tokens") or 0) b["total_tokens"] += int(r.get("total_tokens") or 0) hour_buckets: Dict[str, Dict[str, Any]] = {} cursor = hour_floor while cursor <= now: key = cursor.strftime("%Y-%m-%d %H:00") hour_buckets[key] = { "bucket": key, "requests": 0, "success_count": 0, "failure_count": 0, "prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0, } cursor += timedelta(hours=1) for r in rows_hour_window: key = r["dt"].strftime("%Y-%m-%d %H:00") b = hour_buckets.get(key) if b is None: continue b["requests"] += 1 if r.get("success"): b["success_count"] += 1 else: b["failure_count"] += 1 b["prompt_tokens"] += int(r.get("prompt_tokens") or 0) b["completion_tokens"] += int(r.get("completion_tokens") or 0) b["total_tokens"] += int(r.get("total_tokens") or 0) models = sorted( by_model.values(), key=lambda x: (int(x.get("requests") or 0), int(x.get("total_tokens") or 0)), reverse=True, ) for m in models: req = int(m.get("requests") or 0) m["success_rate"] = round(100.0 * int(m.get("success_count") or 0) / req, 2) if req else 0.0 m["avg_tokens_per_request"] = round(int(m.get("total_tokens") or 0) / req, 2) if req else 0.0 recent_events = sorted(rows_window, key=lambda x: x["dt"], reverse=True)[:events_limit] recent_events_out = [] for r in recent_events: out = {k: v for k, v in r.items() if k != "dt"} recent_events_out.append(out) return { "source": source, "log_path": log_path, "generated_at": now.isoformat().replace("+00:00", "Z"), "window_days": days, "hour_window": hours, "summary": summary, "trends": { "by_day": list(day_buckets.values()), "by_hour": list(hour_buckets.values()), }, "models": models[:model_limit], "recent_events": recent_events_out, "raw_events_in_window": len(rows_window), } def _build_cpa_usage_payload( rows: List[Dict[str, Any]], *, source: str, log_path: str, event_limit: int = 20000, ) -> Dict[str, Any]: event_limit = max(int(event_limit), 1) now = datetime.now(timezone.utc) rows_sorted = sorted((r for r in rows if isinstance(r.get("dt"), datetime)), key=lambda x: x["dt"]) if len(rows_sorted) > event_limit: rows_sorted = rows_sorted[-event_limit:] usage: Dict[str, Any] = { "source": source, "log_path": log_path, "generated_at": now.isoformat().replace("+00:00", "Z"), "total_requests": 0, "success_count": 0, "failure_count": 0, "total_tokens": 0, "apis": {}, } apis = usage["apis"] endpoint_key = "POST /v1/chat/completions" for r in rows_sorted: model_name = str(r.get("model") or "unknown") success = bool(r.get("success")) prompt_tokens = max(_safe_int(r.get("prompt_tokens")) or 0, 0) completion_tokens = max(_safe_int(r.get("completion_tokens")) or 0, 0) total_tokens = _safe_int(r.get("total_tokens")) if total_tokens is None: total_tokens = prompt_tokens + completion_tokens total_tokens = max(total_tokens, 0) cached_tokens = max(_safe_int(r.get("cached_tokens")) or 0, 0) reasoning_tokens = max(_safe_int(r.get("reasoning_tokens")) or 0, 0) account_email = str(r.get("account_email") or "").strip() conversation_id = str(r.get("conversation_id") or "").strip() source_id = account_email or conversation_id or "unknown" api_entry = apis.get(endpoint_key) if not isinstance(api_entry, dict): api_entry = { "total_requests": 0, "success_count": 0, "failure_count": 0, "total_tokens": 0, "models": {}, } apis[endpoint_key] = api_entry models = api_entry.get("models") if not isinstance(models, dict): models = {} api_entry["models"] = models model_entry = models.get(model_name) if not isinstance(model_entry, dict): model_entry = { "total_requests": 0, "success_count": 0, "failure_count": 0, "total_tokens": 0, "details": [], } models[model_name] = model_entry detail = { "timestamp": str(r.get("ts") or ""), "source": source_id, "auth_index": 0, "failed": not success, "tokens": { "input_tokens": prompt_tokens, "output_tokens": completion_tokens, "reasoning_tokens": reasoning_tokens, "cached_tokens": cached_tokens, "total_tokens": total_tokens, }, "status": str(r.get("status") or ("success" if success else "failed")), "runtime": _safe_float(r.get("runtime")), "conversation_id": conversation_id, "account_email": account_email, "error": str(r.get("error") or ""), } details = model_entry.get("details") if not isinstance(details, list): details = [] model_entry["details"] = details details.append(detail) usage["total_requests"] += 1 usage["total_tokens"] += total_tokens api_entry["total_requests"] += 1 api_entry["total_tokens"] += total_tokens model_entry["total_requests"] += 1 model_entry["total_tokens"] += total_tokens if success: usage["success_count"] += 1 api_entry["success_count"] += 1 model_entry["success_count"] += 1 else: usage["failure_count"] += 1 api_entry["failure_count"] += 1 model_entry["failure_count"] += 1 return usage def _extract_usage_rows_from_cpa_payload(payload: Dict[str, Any]) -> List[Dict[str, Any]]: if not isinstance(payload, dict): return [] root = payload.get("usage") if isinstance(payload.get("usage"), dict) else payload if not isinstance(root, dict): return [] apis = root.get("apis") if not isinstance(apis, dict): return [] out: List[Dict[str, Any]] = [] for _endpoint, api_entry in apis.items(): if not isinstance(api_entry, dict): continue models = api_entry.get("models") if not isinstance(models, dict): continue for model_name, model_entry in models.items(): if not isinstance(model_entry, dict): continue details = model_entry.get("details") if not isinstance(details, list): continue for d in details: if not isinstance(d, dict): continue timestamp = str(d.get("timestamp") or "").strip() if not timestamp: continue tokens = d.get("tokens") tokens_obj = tokens if isinstance(tokens, dict) else {} prompt_tokens = max(_safe_int(tokens_obj.get("input_tokens")) or 0, 0) completion_tokens = max(_safe_int(tokens_obj.get("output_tokens")) or 0, 0) total_tokens = _safe_int(tokens_obj.get("total_tokens")) if total_tokens is None: total_tokens = prompt_tokens + completion_tokens total_tokens = max(total_tokens, 0) cached_tokens = max(_safe_int(tokens_obj.get("cached_tokens")) or 0, 0) reasoning_tokens = max(_safe_int(tokens_obj.get("reasoning_tokens")) or 0, 0) failed = _to_bool(d.get("failed"), default=False) success = not failed account_email = str(d.get("account_email") or "").strip() conversation_id = str(d.get("conversation_id") or "").strip() source_text = str(d.get("source") or "").strip() if not account_email and source_text and "@" in source_text: account_email = source_text out.append( { "ts": timestamp, "model": str(model_name or "unknown"), "conversation_id": conversation_id, "stream": False, "success": success, "status": str(d.get("status") or ("failed" if failed else "success")), "error": str(d.get("error") or ""), "account_email": account_email, "execution_id": d.get("execution_id"), "app_id": d.get("app_id"), "prompt_tokens": prompt_tokens, "completion_tokens": completion_tokens, "total_tokens": total_tokens, "cached_tokens": cached_tokens, "reasoning_tokens": reasoning_tokens, "tokens_estimated": _to_bool(d.get("tokens_estimated"), default=False), "runtime": _safe_float(d.get("runtime")), "credits_used": _safe_float(d.get("credits_used")), } ) return out def _append_usage_rows_to_log(rows: List[Dict[str, Any]]) -> Dict[str, int]: if not rows: return {"added": 0, "skipped": 0, "failed_requests": 0} log_path = _jsonl_log_path("openai_adapter_run.jsonl") added = 0 skipped = 0 failed_requests = 0 with log_path.open("a", encoding="utf-8") as f: for row in rows: normalized = _normalize_usage_event(row, source="usage_event") if normalized is None: skipped += 1 continue if not normalized.get("success"): failed_requests += 1 to_write = { "ts": normalized.get("ts"), "event": "usage_event", "model": normalized.get("model"), "conversation_id": normalized.get("conversation_id"), "stream": normalized.get("stream"), "success": normalized.get("success"), "status": normalized.get("status"), "error": normalized.get("error"), "account_email": normalized.get("account_email"), "execution_id": normalized.get("execution_id"), "app_id": normalized.get("app_id"), "prompt_tokens": normalized.get("prompt_tokens"), "completion_tokens": normalized.get("completion_tokens"), "total_tokens": normalized.get("total_tokens"), "cached_tokens": normalized.get("cached_tokens"), "reasoning_tokens": normalized.get("reasoning_tokens"), "tokens_estimated": normalized.get("tokens_estimated"), "runtime": normalized.get("runtime"), "credits_used": normalized.get("credits_used"), } f.write(json.dumps(to_write, ensure_ascii=False) + "\n") added += 1 return {"added": added, "skipped": skipped, "failed_requests": failed_requests} def _list_accounts_for_backup(account_store, limit: int = 20000) -> List[Dict[str, Any]]: n = max(int(limit), 1) if hasattr(account_store, "list_accounts_full"): rows = account_store.list_accounts_full(limit=n) if isinstance(rows, list): return [r for r in rows if isinstance(r, dict)] # Compatibility fallback for custom stores without list_accounts_full. out: List[Dict[str, Any]] = [] base = account_store.list_accounts(limit=n) if hasattr(account_store, "list_accounts") else [] if not isinstance(base, list): return out for row in base: if not isinstance(row, dict): continue email = str(row.get("email") or "").strip() if not email: continue full = account_store.get_by_email(email) if hasattr(account_store, "get_by_email") else None if isinstance(full, dict): merged = dict(row) merged["password"] = full.get("password") out.append(merged) else: out.append(dict(row)) return out def _list_conversations_for_backup(conv_store, limit: int = 20000) -> List[Dict[str, Any]]: n = max(int(limit), 1) if hasattr(conv_store, "list_items"): rows = conv_store.list_items(limit=n) if isinstance(rows, list): return [r for r in rows if isinstance(r, dict)] return [] def _bool_payload(payload: Dict[str, Any], key: str, default: bool) -> bool: return _to_bool(payload.get(key), default=default) def _quota_tier_counts(rows: List[Dict[str, Any]]) -> Dict[str, int]: out: Dict[str, int] = {} for row in rows: if not isinstance(row, dict): continue tier = str(row.get("quota_tier") or "unknown").strip() or "unknown" out[tier] = int(out.get(tier, 0) or 0) + 1 return out def _workspace_sort_key(v: str): raw = str(v or "").strip() n = _safe_int(raw) if n is not None: return (0, n, raw) return (1, raw.lower(), raw) def _list_workspace_summaries(account_store, limit: int = 5000) -> List[Dict[str, Any]]: n = max(int(limit), 1) rows = account_store.list_accounts(limit=n) if hasattr(account_store, "list_accounts") else [] if not isinstance(rows, list): return [] groups: Dict[str, Dict[str, Any]] = {} for row in rows: if not isinstance(row, dict): continue workspace_id = str(row.get("workspace_id") or "").strip() if not workspace_id: continue email = str(row.get("email") or "").strip() status = str(row.get("status") or "").strip() updated_at = str(row.get("updated_at") or "").strip() retryable = row.get("retryable") failure_code = str(row.get("failure_code") or "").strip() item = groups.get(workspace_id) if item is None: item = { "workspace_id": workspace_id, "account_count": 0, "ready_account_count": 0, "preferred_email": "", "latest_updated_at": "", "_picked_ready": False, "accounts": [], } groups[workspace_id] = item item["account_count"] = int(item.get("account_count", 0) or 0) + 1 if status.lower() in _READY_ACCOUNT_STATUSES: item["ready_account_count"] = int(item.get("ready_account_count", 0) or 0) + 1 if updated_at: last = str(item.get("latest_updated_at") or "") if not last or updated_at > last: item["latest_updated_at"] = updated_at if email: item["accounts"].append( { "email": email, "status": status, "updated_at": updated_at, "retryable": retryable, "failure_code": failure_code, } ) if not item.get("preferred_email"): item["preferred_email"] = email if status.lower() in _READY_ACCOUNT_STATUSES and not bool(item.get("_picked_ready")): item["preferred_email"] = email item["_picked_ready"] = True out = sorted(groups.values(), key=lambda x: _workspace_sort_key(str(x.get("workspace_id") or ""))) for row in out: row.pop("_picked_ready", None) return out def _pick_workspace_account_email(workspace_row: Dict[str, Any], preferred_email: str = "") -> str: target = str(preferred_email or "").strip().lower() accounts = workspace_row.get("accounts") if not isinstance(accounts, list): accounts = [] if target: for row in accounts: if not isinstance(row, dict): continue email = str(row.get("email") or "").strip() if email and email.lower() == target: return email for row in accounts: if not isinstance(row, dict): continue email = str(row.get("email") or "").strip() status = str(row.get("status") or "").strip().lower() if email and status in _READY_ACCOUNT_STATUSES: return email for row in accounts: if not isinstance(row, dict): continue email = str(row.get("email") or "").strip() if email: return email return "" def _workspace_for_email(workspaces: List[Dict[str, Any]], email: str) -> str: target = str(email or "").strip().lower() if not target: return "" for ws in workspaces: accounts = ws.get("accounts") if not isinstance(accounts, list): continue for row in accounts: if not isinstance(row, dict): continue acc_email = str(row.get("email") or "").strip().lower() if acc_email and acc_email == target: return str(ws.get("workspace_id") or "").strip() return "" def _merge_runtime_workspace_rows( runtime_rows: List[Dict[str, Any]], summary_rows: List[Dict[str, Any]], account_email: str = "", include_summary_only: bool = True, ) -> List[Dict[str, Any]]: summary_map = { str(row.get("workspace_id") or "").strip(): row for row in (summary_rows or []) if isinstance(row, dict) and str(row.get("workspace_id") or "").strip() } out: List[Dict[str, Any]] = [] seen = set() for raw in runtime_rows or []: if not isinstance(raw, dict): continue ws_id = str(raw.get("workspace_id") or raw.get("id") or "").strip() if not ws_id or ws_id in seen: continue seen.add(ws_id) summary = summary_map.get(ws_id) or {} out.append( { "workspace_id": ws_id, "workspace_slug": str(raw.get("workspace_slug") or raw.get("slug") or "").strip(), "workspace_name": str(raw.get("workspace_name") or raw.get("name") or "").strip(), "workspace_tier": str(raw.get("workspace_tier") or raw.get("tier") or "").strip(), "account_email": str(raw.get("account_email") or account_email or "").strip(), "account_count": int(summary.get("account_count") or 0), "ready_account_count": int(summary.get("ready_account_count") or 0), "preferred_email": str(summary.get("preferred_email") or "").strip(), "latest_updated_at": str(summary.get("latest_updated_at") or "").strip(), "accounts": summary.get("accounts") if isinstance(summary.get("accounts"), list) else [], } ) if include_summary_only: for summary in summary_rows or []: if not isinstance(summary, dict): continue ws_id = str(summary.get("workspace_id") or "").strip() if not ws_id or ws_id in seen: continue out.append( { "workspace_id": ws_id, "workspace_slug": "", "workspace_name": "", "workspace_tier": "", "account_email": str(account_email or "").strip(), "account_count": int(summary.get("account_count") or 0), "ready_account_count": int(summary.get("ready_account_count") or 0), "preferred_email": str(summary.get("preferred_email") or "").strip(), "latest_updated_at": str(summary.get("latest_updated_at") or "").strip(), "accounts": summary.get("accounts") if isinstance(summary.get("accounts"), list) else [], } ) return sorted(out, key=lambda x: _workspace_sort_key(str(x.get("workspace_id") or ""))) def _import_accounts_rows(account_store, rows: Any) -> Dict[str, int]: added = 0 skipped = 0 if not isinstance(rows, list): return {"added": 0, "skipped": 0} for row in rows: if not isinstance(row, dict): skipped += 1 continue email = str(row.get("email") or "").strip() password = str(row.get("password") or "").strip() if not email or not password: skipped += 1 continue status = str(row.get("status") or "ready").strip() or "ready" workspace_id = str(row.get("workspace_id") or "").strip() or None retryable = row.get("retryable") retryable_bool = None if retryable is not None: retryable_bool = _to_bool(retryable, default=False) account_store.upsert( email=email, password=password, status=status, workspace_id=workspace_id, last_error=str(row.get("last_error") or "") or None, failure_code=str(row.get("failure_code") or "") or None, retryable=retryable_bool, ) added += 1 return {"added": added, "skipped": skipped} def _delete_accounts_by_statuses(account_store, statuses: List[str]) -> int: clean = [str(s).strip() for s in (statuses or []) if str(s).strip()] if not clean: return 0 if hasattr(account_store, "delete_by_statuses"): try: return int(account_store.delete_by_statuses(clean) or 0) except Exception: return 0 if not hasattr(account_store, "delete_by_email"): return 0 rows = account_store.list_accounts(limit=50000) if hasattr(account_store, "list_accounts") else [] if not isinstance(rows, list): return 0 bag = {x.lower() for x in clean} deleted = 0 for row in rows: if not isinstance(row, dict): continue status = str(row.get("status") or "").strip().lower() if status not in bag: continue email = str(row.get("email") or "").strip() if not email: continue try: if account_store.delete_by_email(email): deleted += 1 except Exception: continue return deleted class _BootstrapAttemptGuard: def __init__(self, max_attempts: int = 5, window_sec: int = 300, lock_sec: int = 900): self.max_attempts = max(int(max_attempts), 1) self.window_sec = max(int(window_sec), 10) self.lock_sec = max(int(lock_sec), 10) self._lock = Lock() self._state: Dict[str, Dict[str, Any]] = {} def check(self, key: str) -> Dict[str, Any]: now = time.time() k = (key or "unknown").strip() or "unknown" with self._lock: row = self._state.get(k, {"failures": [], "locked_until": 0.0}) failures = [float(ts) for ts in row.get("failures", []) if now - float(ts) <= self.window_sec] locked_until = float(row.get("locked_until") or 0.0) if locked_until <= now: locked_until = 0.0 row["failures"] = failures row["locked_until"] = locked_until self._state[k] = row return { "blocked": bool(locked_until and locked_until > now), "retry_after_sec": int(max(0.0, locked_until - now)) if locked_until > now else 0, "failures_in_window": len(failures), } def mark_failure(self, key: str) -> Dict[str, Any]: now = time.time() k = (key or "unknown").strip() or "unknown" with self._lock: row = self._state.get(k, {"failures": [], "locked_until": 0.0}) failures = [float(ts) for ts in row.get("failures", []) if now - float(ts) <= self.window_sec] failures.append(now) locked_until = float(row.get("locked_until") or 0.0) if len(failures) >= self.max_attempts: locked_until = now + self.lock_sec failures = [] row["failures"] = failures row["locked_until"] = locked_until self._state[k] = row return { "blocked": bool(locked_until and locked_until > now), "retry_after_sec": int(max(0.0, locked_until - now)) if locked_until > now else 0, "failures_in_window": len(failures), } def clear(self, key: str): k = (key or "unknown").strip() or "unknown" with self._lock: self._state.pop(k, None) def _extract_bearer_token(auth_header: Optional[str]) -> str: raw = str(auth_header or "").strip() if not raw.lower().startswith("bearer "): return "" return raw.split(" ", 1)[1].strip() def _client_key(req: Optional[Request]) -> str: if req is None: return "unknown" xff = str(req.headers.get("x-forwarded-for") or "").strip() if xff: return xff.split(",", 1)[0].strip() or "unknown" if req.client and req.client.host: return str(req.client.host).strip() or "unknown" return "unknown" def _build_bootstrap_config_payload(settings, runtime=None) -> Dict[str, Any]: payload = { "version": 1, "updated_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"), "settings": snapshot_settings(settings, BOOTSTRAP_SETTING_SPECS), } if runtime is not None and hasattr(runtime, "workspace_selection_snapshot"): try: selection = runtime.workspace_selection_snapshot() except Exception: selection = {} if isinstance(selection, dict) and str(selection.get("workspace_id") or "").strip(): payload["workspace_selection"] = selection return payload def build_admin_router( runtime, settings, conv_store, account_store, register_jobs, check_auth: Callable[[Optional[str]], None], bootstrap_store=None, bootstrap_initialized: bool = False, bootstrap_defaults: Optional[Dict[str, Any]] = None, ): router = APIRouter() bootstrap_state = {"initialized": bool(bootstrap_initialized)} bootstrap_defaults_rows = dict(bootstrap_defaults or snapshot_settings(settings, BOOTSTRAP_SETTING_SPECS)) bootstrap_guard = _BootstrapAttemptGuard( max_attempts=getattr(settings, "bootstrap_max_attempts", 5), window_sec=getattr(settings, "bootstrap_window_sec", 300), lock_sec=getattr(settings, "bootstrap_lock_sec", 900), ) def _persist_bootstrap_settings() -> bool: if bootstrap_store is None: return False try: bootstrap_store.save(_build_bootstrap_config_payload(settings, runtime=runtime)) return True except Exception: return False @router.get("/admin/bootstrap/status") def admin_bootstrap_status(request: Request): key = _client_key(request) guard = bootstrap_guard.check(key) return { "ok": True, "initialized": bool(bootstrap_state["initialized"]), "bootstrap_token_configured": bool(getattr(settings, "bootstrap_token", "")), "rate_limit": { "blocked": bool(guard.get("blocked")), "retry_after_sec": int(guard.get("retry_after_sec") or 0), "failures_in_window": int(guard.get("failures_in_window") or 0), "max_attempts": int(getattr(settings, "bootstrap_max_attempts", 5)), "window_sec": int(getattr(settings, "bootstrap_window_sec", 300)), "lock_sec": int(getattr(settings, "bootstrap_lock_sec", 900)), }, } @router.get("/admin/bootstrap/export") def admin_bootstrap_export(authorization: Optional[str] = Header(None)): check_auth(authorization) return {"ok": True, "bootstrap": _build_bootstrap_config_payload(settings)} @router.post("/admin/bootstrap/import") def admin_bootstrap_import(payload: Dict[str, Any], request: Request, authorization: Optional[str] = Header(None)): if bootstrap_state["initialized"]: raise HTTPException(status_code=409, detail="bootstrap already initialized") token = str(getattr(settings, "bootstrap_token", "") or "").strip() if not token: raise HTTPException(status_code=503, detail="BOOTSTRAP_TOKEN is not configured") key = _client_key(request) guard = bootstrap_guard.check(key) if guard.get("blocked"): raise HTTPException( status_code=429, detail=f"too many invalid bootstrap attempts, retry after {int(guard.get('retry_after_sec') or 0)}s", ) got = _extract_bearer_token(authorization) if not got or got != token: after = bootstrap_guard.mark_failure(key) if after.get("blocked"): raise HTTPException( status_code=429, detail=f"too many invalid bootstrap attempts, retry after {int(after.get('retry_after_sec') or 0)}s", ) raise HTTPException(status_code=401, detail="invalid bootstrap token") raw_body = payload if isinstance(payload, dict) else {} body = raw_body nested_bootstrap = body.get("bootstrap") if isinstance(nested_bootstrap, dict): body = nested_bootstrap rows = body.get("settings") if not isinstance(rows, dict): rows = body if not isinstance(rows, dict) or not rows: raise HTTPException(status_code=400, detail="settings payload required") try: updated, ignored = apply_settings(settings, rows, BOOTSTRAP_SETTING_SPECS) except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) if not updated: raise HTTPException(status_code=400, detail="no valid settings to apply") persisted = _persist_bootstrap_settings() reset_runtime = _to_bool(raw_body.get("reset_runtime"), default=True) warmup = _to_bool(raw_body.get("warmup"), default=False) warmup_ok = False warmup_error = "" if reset_runtime: runtime.reset() if warmup: try: runtime.ensure_ready(conversation_id="__bootstrap_warmup__") warmup_ok = True except Exception as e: warmup_error = str(e) bootstrap_guard.clear(key) bootstrap_state["initialized"] = True out = { "ok": True, "initialized": True, "persisted": bool(persisted), "updated": updated, "ignored": ignored, "runtime_reset": bool(reset_runtime), "warmup": {"enabled": warmup, "ok": warmup_ok, "error": warmup_error}, "health": runtime.health_snapshot(), } return out @router.post("/admin/bootstrap/revoke") def admin_bootstrap_revoke(authorization: Optional[str] = Header(None)): check_auth(authorization) try: apply_settings(settings, bootstrap_defaults_rows, BOOTSTRAP_SETTING_SPECS) except Exception: pass cleared = bool(bootstrap_store.clear()) if bootstrap_store is not None else False bootstrap_state["initialized"] = False runtime.reset() return { "ok": True, "initialized": False, "store_cleared": cleared, "health": runtime.health_snapshot(), } @router.get("/admin/overview") def admin_overview(authorization: Optional[str] = Header(None)): check_auth(authorization) snap = runtime.health_snapshot() return { "ok": True, "health": { "ready": snap.get("ready"), "workspace_id": snap.get("workspace_id"), "workspace_slug": snap.get("workspace_slug"), "workspace_name": snap.get("workspace_name"), "workspace_tier": snap.get("workspace_tier"), "active_account_email": snap.get("active_account_email"), "manual_active_account_email": snap.get("manual_active_account_email"), "account_pool_size": snap.get("pool_size"), "conversation_bindings": snap.get("conversation_bindings"), "last_error": snap.get("last_error"), "conversation_store_items": conv_store.count(), "stream_transport": settings.stream_transport, "pusher_key_loaded": bool(getattr(settings, "pusher_app_key", "")), "bootstrap_initialized": bool(bootstrap_state["initialized"]), "bootstrap_token_configured": bool(getattr(settings, "bootstrap_token", "")), }, "runtime_settings": _runtime_settings_snapshot(settings), "accounts": { "status_counts": account_store.status_counts(), "recent": account_store.list_accounts(limit=15), }, "jobs": register_jobs.list_jobs(limit=10), } @router.get("/admin/accounts") def admin_accounts(limit: int = 200, authorization: Optional[str] = Header(None)): check_auth(authorization) rows = account_store.list_accounts(limit=max(int(limit), 1)) return { "ok": True, "accounts": rows, "status_counts": account_store.status_counts(), "quota_tier_counts": _quota_tier_counts(rows if isinstance(rows, list) else []), } @router.get("/admin/workspaces") def admin_workspaces(limit: int = 1000, refresh: bool = False, authorization: Optional[str] = Header(None)): check_auth(authorization) n = max(min(int(limit), 5000), 1) summary_rows = _list_workspace_summaries(account_store, limit=n) snap = runtime.health_snapshot() current_workspace_id = str((snap or {}).get("workspace_id") or "").strip() current_workspace_slug = str((snap or {}).get("workspace_slug") or "").strip() active_account_email = str((snap or {}).get("active_account_email") or "").strip() manual_active_account_email = str((snap or {}).get("manual_active_account_email") or "").strip() active_workspace = _workspace_for_email(summary_rows, active_account_email) manual_workspace = _workspace_for_email(summary_rows, manual_active_account_email) runtime_rows: List[Dict[str, Any]] = [] runtime_account_email = "" source = "account_store" if hasattr(runtime, "list_workspaces"): try: runtime_payload = runtime.list_workspaces(force_refresh=bool(refresh)) runtime_rows = runtime_payload.get("workspaces") if isinstance(runtime_payload, dict) else [] if not isinstance(runtime_rows, list): runtime_rows = [] runtime_account_email = str((runtime_payload or {}).get("account_email") or "").strip() selection = (runtime_payload or {}).get("selection") if isinstance(runtime_payload, dict) else {} if isinstance(selection, dict): selected_id = str(selection.get("workspace_id") or "").strip() selected_slug = str(selection.get("workspace_slug") or "").strip() if selected_id: current_workspace_id = selected_id if selected_slug: current_workspace_slug = selected_slug source = "runtime" except Exception as e: source = "account_store_fallback" runtime_rows = [] runtime_account_email = "" if str((snap or {}).get("last_error") or "").strip() == "": snap["last_error"] = str(e) if not current_workspace_id: current_workspace_id = manual_workspace or active_workspace if not current_workspace_slug: current_workspace_slug = "" ws_rows = _merge_runtime_workspace_rows( runtime_rows, summary_rows, account_email=runtime_account_email, include_summary_only=source != "runtime", ) row_map = {str(row.get("workspace_id") or "").strip(): row for row in ws_rows} if current_workspace_id and current_workspace_id not in row_map: ws_rows.append( { "workspace_id": current_workspace_id, "workspace_slug": current_workspace_slug, "workspace_name": "", "workspace_tier": "", "account_email": runtime_account_email, "account_count": 0, "ready_account_count": 0, "preferred_email": "", "latest_updated_at": "", "accounts": [], } ) ws_rows = sorted(ws_rows, key=lambda x: _workspace_sort_key(str(x.get("workspace_id") or ""))) out_rows: List[Dict[str, Any]] = [] for row in ws_rows: ws_id = str(row.get("workspace_id") or "").strip() out_rows.append( { "workspace_id": ws_id, "workspace_slug": str(row.get("workspace_slug") or "").strip(), "workspace_name": str(row.get("workspace_name") or "").strip(), "workspace_tier": str(row.get("workspace_tier") or "").strip(), "account_email": str(row.get("account_email") or "").strip(), "account_count": int(row.get("account_count") or 0), "ready_account_count": int(row.get("ready_account_count") or 0), "preferred_email": str(row.get("preferred_email") or "").strip(), "latest_updated_at": str(row.get("latest_updated_at") or "").strip(), "is_current_workspace": bool(current_workspace_id and ws_id == current_workspace_id), "contains_active_account": bool(active_workspace and ws_id == active_workspace), "contains_manual_active_account": bool(manual_workspace and ws_id == manual_workspace), } ) return { "ok": True, "source": source, "current_workspace_id": current_workspace_id, "current_workspace_slug": current_workspace_slug, "active_account_email": active_account_email, "manual_active_account_email": manual_active_account_email, "workspaces": out_rows, } @router.post("/admin/workspaces") def admin_create_workspace(payload: Dict[str, Any], authorization: Optional[str] = Header(None)): check_auth(authorization) body = payload if isinstance(payload, dict) else {} workspace_name = str(body.get("workspace_name") or body.get("name") or "").strip() preferred_email = str(body.get("email") or "").strip() clear_bindings = _bool_payload(body, "clear_bindings", True) if not workspace_name: raise HTTPException(status_code=400, detail="workspace_name required") if not hasattr(runtime, "create_workspace"): raise HTTPException(status_code=400, detail="runtime does not support workspace creation") try: result = runtime.create_workspace(workspace_name=workspace_name, email=preferred_email, clear_bindings=clear_bindings) if bootstrap_store is not None: _persist_bootstrap_settings() except Exception as e: raise HTTPException(status_code=500, detail=f"create workspace failed: {e}") workspace = result.get("workspace") if isinstance(result, dict) else {} if not isinstance(workspace, dict): workspace = {} return { "ok": True, "workspace": workspace, "selected_email": str((result or {}).get("account_email") or "").strip(), "health": (result or {}).get("health") if isinstance(result, dict) else runtime.health_snapshot(), "raw": (result or {}).get("raw") if isinstance(result, dict) else {}, } @router.post("/admin/workspaces/trial") def admin_activate_workspace_trial(payload: Dict[str, Any], authorization: Optional[str] = Header(None)): check_auth(authorization) body = payload if isinstance(payload, dict) else {} workspace_id = str(body.get("workspace_id") or "").strip() workspace_slug = str(body.get("workspace_slug") or "").strip() preferred_email = str(body.get("email") or "").strip() clear_bindings = _bool_payload(body, "clear_bindings", True) if not hasattr(runtime, "activate_workspace_trial"): raise HTTPException(status_code=400, detail="runtime does not support workspace trial activation") snap = runtime.health_snapshot() if hasattr(runtime, "health_snapshot") else {} selected_email = preferred_email or str( (snap or {}).get("manual_active_account_email") or (snap or {}).get("active_account_email") or "" ).strip() if workspace_id: current_workspace_id = str((snap or {}).get("workspace_id") or "").strip() if not workspace_slug and current_workspace_id == workspace_id: workspace_slug = str((snap or {}).get("workspace_slug") or "").strip() if not selected_email and hasattr(runtime, "workspace_selection_snapshot"): current_selection = runtime.workspace_selection_snapshot() if isinstance(current_selection, dict) and str(current_selection.get("workspace_id") or "").strip() == workspace_id: selected_email = str(current_selection.get("account_email") or "").strip() if not workspace_slug: workspace_slug = str(current_selection.get("workspace_slug") or "").strip() if not selected_email: summary_rows = _list_workspace_summaries(account_store, limit=20000) target = None for row in summary_rows: if str(row.get("workspace_id") or "").strip() == workspace_id: target = row break if isinstance(target, dict): if not workspace_slug: workspace_slug = str(target.get("workspace_slug") or "").strip() selected_email = str(target.get("account_email") or "").strip() or _pick_workspace_account_email( target, preferred_email=preferred_email, ) if not selected_email: raise HTTPException(status_code=404, detail="no account available for this workspace") else: workspace_id = str((snap or {}).get("workspace_id") or "").strip() if not workspace_id: raise HTTPException(status_code=400, detail="workspace_id required") if not workspace_slug: workspace_slug = str((snap or {}).get("workspace_slug") or "").strip() if not selected_email: raise HTTPException(status_code=404, detail="no account available for current workspace") try: result = runtime.activate_workspace_trial( workspace_id=workspace_id, workspace_slug=workspace_slug, email=selected_email, clear_bindings=clear_bindings, ) if bootstrap_store is not None: _persist_bootstrap_settings() except Exception as e: raise HTTPException(status_code=500, detail=f"activate workspace trial failed: {e}") workspace = result.get("workspace") if isinstance(result, dict) else {} if not isinstance(workspace, dict): workspace = {} return { "ok": True, "success": bool((result or {}).get("success", True)) if isinstance(result, dict) else True, "workspace": workspace, "selected_email": str((result or {}).get("account_email") or selected_email or "").strip(), "health": (result or {}).get("health") if isinstance(result, dict) else runtime.health_snapshot(), "raw": (result or {}).get("raw") if isinstance(result, dict) else {}, } @router.post("/admin/workspaces/active") def admin_set_active_workspace(payload: Dict[str, Any], authorization: Optional[str] = Header(None)): check_auth(authorization) body = payload if isinstance(payload, dict) else {} workspace_id = str(body.get("workspace_id") or "").strip() preferred_email = str(body.get("email") or "").strip() clear_bindings = _bool_payload(body, "clear_bindings", True) if not workspace_id: raise HTTPException(status_code=400, detail="workspace_id required") if not hasattr(runtime, "set_active_workspace"): raise HTTPException(status_code=400, detail="runtime does not support manual active account") runtime_payload = runtime.list_workspaces(force_refresh=True) if hasattr(runtime, "list_workspaces") else {} runtime_rows = runtime_payload.get("workspaces") if isinstance(runtime_payload, dict) else [] runtime_account_email = str((runtime_payload or {}).get("account_email") or "").strip() summary_rows = _list_workspace_summaries(account_store, limit=20000) ws_rows = _merge_runtime_workspace_rows( runtime_rows if isinstance(runtime_rows, list) else [], summary_rows, account_email=runtime_account_email, include_summary_only=not bool(runtime_rows), ) target = None for row in ws_rows: if str(row.get("workspace_id") or "").strip() == workspace_id: target = row break if not isinstance(target, dict): raise HTTPException(status_code=404, detail="workspace not found") selected_email = str(target.get("account_email") or "").strip() if preferred_email: selected_email = preferred_email if not selected_email: selected_email = _pick_workspace_account_email(target, preferred_email=preferred_email) if not selected_email: raise HTTPException(status_code=404, detail="no account available for this workspace") try: snap = runtime.set_active_workspace( workspace_id=workspace_id, workspace_slug=str(target.get("workspace_slug") or "").strip(), workspace_name=str(target.get("workspace_name") or "").strip(), workspace_tier=str(target.get("workspace_tier") or "").strip(), email=selected_email, clear_bindings=clear_bindings, ) if bootstrap_store is not None: _persist_bootstrap_settings() except Exception as e: raise HTTPException(status_code=500, detail=f"set active workspace failed: {e}") return { "ok": True, "workspace_id": workspace_id, "workspace_slug": str(target.get("workspace_slug") or "").strip(), "workspace_tier": str(target.get("workspace_tier") or "").strip(), "selected_email": selected_email, "health": snap, } @router.post("/admin/workspaces/active/clear") def admin_clear_active_workspace(payload: Dict[str, Any], authorization: Optional[str] = Header(None)): check_auth(authorization) body = payload if isinstance(payload, dict) else {} clear_bindings = _bool_payload(body, "clear_bindings", False) if not hasattr(runtime, "clear_active_workspace"): raise HTTPException(status_code=400, detail="runtime does not support clearing manual active account") try: snap = runtime.clear_active_workspace(clear_bindings=clear_bindings) if bootstrap_store is not None: _persist_bootstrap_settings() except Exception as e: raise HTTPException(status_code=500, detail=f"clear active workspace failed: {e}") return {"ok": True, "health": snap} @router.post("/admin/accounts") def admin_add_account(payload: Dict[str, Any], authorization: Optional[str] = Header(None)): check_auth(authorization) email = str(payload.get("email") or "").strip() password = str(payload.get("password") or "").strip() workspace_id = str(payload.get("workspace_id") or "").strip() status = str(payload.get("status") or "ready").strip() if not email or not password: raise HTTPException(status_code=400, detail="email/password required") account_store.upsert( email=email, password=password, status=status, workspace_id=workspace_id or None, last_error=None, failure_code=None, retryable=None, ) row = account_store.get_by_email(email) return {"ok": True, "account": row} @router.post("/admin/accounts/{email}/status") def admin_update_account_status(email: str, payload: Dict[str, Any], authorization: Optional[str] = Header(None)): check_auth(authorization) key = str(email or "").strip() if not key: raise HTTPException(status_code=400, detail="email required") row = account_store.get_by_email(key) if hasattr(account_store, "get_by_email") else None if not isinstance(row, dict): raise HTTPException(status_code=404, detail="account not found") status = str(payload.get("status") or "").strip() if not status: raise HTTPException(status_code=400, detail="status required") workspace_id = str(payload.get("workspace_id") or row.get("workspace_id") or "").strip() or None password = str(row.get("password") or "").strip() if not password: raise HTTPException(status_code=400, detail="account password missing") failure_code = payload.get("failure_code") last_error = payload.get("last_error") retryable = payload.get("retryable") if status in ("ready", "oauth_ok", "verified"): failure_code = None last_error = None retryable = None else: failure_code = str(failure_code) if failure_code is not None else row.get("failure_code") last_error = str(last_error) if last_error is not None else row.get("last_error") retryable = _to_bool(retryable, default=False) if retryable is not None else row.get("retryable") try: account_store.upsert( email=key, password=password, status=status, workspace_id=workspace_id, last_error=last_error, failure_code=failure_code, retryable=retryable, ) updated = account_store.get_by_email(key) except Exception as e: raise HTTPException(status_code=500, detail=f"update account status failed: {e}") return {"ok": True, "account": updated} @router.delete("/admin/accounts/{email}") def admin_delete_account(email: str, authorization: Optional[str] = Header(None)): check_auth(authorization) key = str(email or "").strip() if not key: raise HTTPException(status_code=400, detail="email required") if not hasattr(account_store, "delete_by_email"): raise HTTPException(status_code=400, detail="account store does not support delete_by_email") try: deleted = bool(account_store.delete_by_email(key)) if deleted: runtime.reset() except Exception as e: raise HTTPException(status_code=500, detail=f"delete account failed: {e}") if not deleted: raise HTTPException(status_code=404, detail="account not found") return {"ok": True} @router.post("/admin/accounts/active") def admin_set_active_account(payload: Dict[str, Any], authorization: Optional[str] = Header(None)): check_auth(authorization) email = str(payload.get("email") or "").strip() clear_bindings = _bool_payload(payload, "clear_bindings", True) if not email: raise HTTPException(status_code=400, detail="email required") if not hasattr(runtime, "set_active_account"): raise HTTPException(status_code=400, detail="runtime does not support manual active account") try: snap = runtime.set_active_account(email=email, clear_bindings=clear_bindings) except Exception as e: raise HTTPException(status_code=500, detail=f"set active account failed: {e}") return {"ok": True, "health": snap} @router.post("/admin/accounts/active/clear") def admin_clear_active_account(payload: Dict[str, Any], authorization: Optional[str] = Header(None)): check_auth(authorization) clear_bindings = _bool_payload(payload, "clear_bindings", False) if not hasattr(runtime, "clear_active_account"): raise HTTPException(status_code=400, detail="runtime does not support clearing manual active account") try: snap = runtime.clear_active_account(clear_bindings=clear_bindings) except Exception as e: raise HTTPException(status_code=500, detail=f"clear active account failed: {e}") return {"ok": True, "health": snap} @router.get("/admin/accounts/export") def admin_export_accounts(limit: int = 20000, authorization: Optional[str] = Header(None)): check_auth(authorization) try: rows = _list_accounts_for_backup(account_store, limit=max(int(limit), 1)) except Exception as e: raise HTTPException(status_code=500, detail=f"accounts export failed: {e}") return { "ok": True, "exported_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"), "count": len(rows), "accounts": rows, } @router.post("/admin/accounts/import") def admin_import_accounts(payload: Dict[str, Any], authorization: Optional[str] = Header(None)): check_auth(authorization) body = payload if isinstance(payload, dict) else {} rows = body.get("accounts") if not isinstance(rows, list): rows = body.get("items") clear_before_import = _bool_payload(body, "clear_before_import", False) reset_runtime = _bool_payload(body, "reset_runtime", True) cleared = 0 try: if clear_before_import and hasattr(account_store, "clear_all"): cleared = int(account_store.clear_all() or 0) ret = _import_accounts_rows(account_store, rows) added = int(ret.get("added") or 0) skipped = int(ret.get("skipped") or 0) runtime_reset = bool(reset_runtime and added > 0) if runtime_reset: runtime.reset() except Exception as e: raise HTTPException(status_code=500, detail=f"accounts import failed: {e}") return { "ok": True, "summary": { "accounts_added": added, "accounts_skipped": skipped, "cleared_accounts": cleared, "runtime_reset": runtime_reset, }, } @router.post("/admin/accounts/delete-invalid") def admin_delete_invalid_accounts(payload: Dict[str, Any], authorization: Optional[str] = Header(None)): check_auth(authorization) body = payload if isinstance(payload, dict) else {} custom_statuses = body.get("statuses") if isinstance(custom_statuses, list) and custom_statuses: statuses = [str(x).strip() for x in custom_statuses if str(x).strip()] else: statuses = [] if _bool_payload(body, "include_retryable", True): statuses.append("failed_retryable") if _bool_payload(body, "include_permanent", True): statuses.append("failed_permanent") reset_runtime = _bool_payload(body, "reset_runtime", True) try: deleted = _delete_accounts_by_statuses(account_store, statuses) runtime_reset = bool(reset_runtime and deleted > 0) if runtime_reset: runtime.reset() except Exception as e: raise HTTPException(status_code=500, detail=f"delete invalid accounts failed: {e}") return { "ok": True, "summary": { "statuses": statuses, "deleted_accounts": int(deleted), "runtime_reset": runtime_reset, }, } @router.post("/admin/accounts/quotas/refresh") def admin_refresh_account_quotas(payload: Dict[str, Any], authorization: Optional[str] = Header(None)): check_auth(authorization) body = payload if isinstance(payload, dict) else {} try: limit = max(int(body.get("limit") or 13), 1) except Exception: limit = 13 try: account_limit = max(int(body.get("account_limit") or 200), 1) except Exception: account_limit = 200 try: sleep_sec = max(float(body.get("sleep_sec") or 0), 0.0) except Exception: sleep_sec = 0.0 raw_statuses = body.get("statuses") if isinstance(raw_statuses, list): statuses = [str(x).strip() for x in raw_statuses if str(x).strip()] elif isinstance(raw_statuses, str) and raw_statuses.strip().lower() == "all": statuses = [] else: statuses = [] try: ret = runtime.refresh_account_quotas( limit=limit, account_limit=account_limit, statuses=statuses, sleep_sec=sleep_sec, ) except Exception as e: raise HTTPException(status_code=500, detail=f"account quota refresh failed: {e}") return { "ok": True, "summary": { "limit": limit, "account_limit": account_limit, "statuses": statuses, "total": int(ret.get("total") or 0), "updated": int(ret.get("updated") or 0), "failed": int(ret.get("failed") or 0), "skipped": int(ret.get("skipped") or 0), }, "rows": ret.get("rows") or [], } @router.post("/admin/register-jobs") def admin_create_register_job(payload: Dict[str, Any], authorization: Optional[str] = Header(None)): check_auth(authorization) items = _parse_items(payload) if not items: raise HTTPException(status_code=400, detail="no email items") with_chat_test = _to_bool(payload.get("with_chat_test"), default=False) skip_ready = _to_bool(payload.get("skip_ready"), default=True) sleep_sec = float(payload.get("sleep_sec") or 0) try: job = register_jobs.create_job( items, with_chat_test=with_chat_test, skip_ready=skip_ready, sleep_sec=sleep_sec, ) except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) return {"ok": True, "job": job} @router.get("/admin/register-jobs") def admin_list_register_jobs(limit: int = 20, authorization: Optional[str] = Header(None)): check_auth(authorization) return {"ok": True, "jobs": register_jobs.list_jobs(limit=max(int(limit), 1))} @router.get("/admin/register-jobs/{job_id}") def admin_get_register_job(job_id: str, authorization: Optional[str] = Header(None)): check_auth(authorization) row = register_jobs.get_job(job_id) if not row: raise HTTPException(status_code=404, detail="job not found") return {"ok": True, "job": row} @router.post("/admin/register-jobs/{job_id}/cancel") def admin_cancel_register_job(job_id: str, authorization: Optional[str] = Header(None)): check_auth(authorization) ok = register_jobs.cancel_job(job_id) if not ok: raise HTTPException(status_code=404, detail="job not found") return {"ok": True} @router.get("/admin/settings") def admin_get_settings(authorization: Optional[str] = Header(None)): check_auth(authorization) return { "ok": True, "settings": _runtime_settings_snapshot(settings), } @router.post("/admin/settings") def admin_update_settings(payload: Dict[str, Any], authorization: Optional[str] = Header(None)): check_auth(authorization) rows = payload.get("settings") if not isinstance(rows, dict): rows = payload if isinstance(payload, dict) else {} try: updated, ignored = apply_settings( settings, rows, RUNTIME_SETTING_SPECS, allowed_keys=RUNTIME_SETTING_SPECS.keys(), ) except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) reset_runtime = _to_bool(payload.get("reset_runtime"), default=True) if reset_runtime and updated: runtime.reset() persisted = False if updated and bootstrap_state["initialized"]: persisted = _persist_bootstrap_settings() return { "ok": True, "updated": updated, "ignored": ignored, "runtime_reset": bool(reset_runtime and updated), "persisted": bool(persisted), "settings": _runtime_settings_snapshot(settings), } @router.post("/admin/runtime/reset") def admin_reset_runtime(authorization: Optional[str] = Header(None)): check_auth(authorization) runtime.reset() return {"ok": True} @router.post("/admin/runtime/warmup") def admin_warmup_runtime(authorization: Optional[str] = Header(None)): check_auth(authorization) try: runtime.ensure_ready(conversation_id="__admin_warmup__") except Exception as e: raise HTTPException(status_code=500, detail=f"runtime warmup failed: {e}") return { "ok": True, "health": runtime.health_snapshot(), } @router.post("/admin/runtime/restart") def admin_restart_runtime(authorization: Optional[str] = Header(None)): check_auth(authorization) _trigger_self_restart(delay_sec=0.3) return { "ok": True, "restarting": True, "message": "service is restarting", } @router.get("/admin/quota") def admin_get_quota(limit: int = 13, authorization: Optional[str] = Header(None)): check_auth(authorization) try: quota = runtime.quota_snapshot(limit=max(int(limit), 1), conversation_id="__admin_quota__") except Exception as e: raise HTTPException(status_code=500, detail=f"quota fetch failed: {e}") return { "ok": True, "quota": quota, } @router.get("/admin/models") def admin_get_models(include_disabled: bool = False, authorization: Optional[str] = Header(None)): check_auth(authorization) try: data = runtime.available_models( conversation_id="__admin_models__", include_disabled=bool(include_disabled), ) except Exception as e: raise HTTPException(status_code=500, detail=f"models fetch failed: {e}") return { "ok": True, "default_model": getattr(settings, "default_model", ""), "models": data, } @router.get("/admin/usage/stats") def admin_usage_stats( days: int = 14, hours: int = 24, model_limit: int = 30, events_limit: int = 200, max_lines: int = 200000, authorization: Optional[str] = Header(None), ): check_auth(authorization) try: usage_data = _collect_usage_events(max_lines=max_lines) usage = _build_usage_snapshot( usage_data.get("events") or [], source=str(usage_data.get("source") or "none"), log_path=str(usage_data.get("path") or ""), days=days, hours=hours, model_limit=model_limit, events_limit=events_limit, ) except Exception as e: raise HTTPException(status_code=500, detail=f"usage stats build failed: {e}") return {"ok": True, "usage": usage} @router.get("/usage") def usage_compat( event_limit: int = 20000, max_lines: int = 200000, authorization: Optional[str] = Header(None), ): check_auth(authorization) try: usage_data = _collect_usage_events(max_lines=max_lines) usage = _build_cpa_usage_payload( usage_data.get("events") or [], source=str(usage_data.get("source") or "none"), log_path=str(usage_data.get("path") or ""), event_limit=event_limit, ) except Exception as e: raise HTTPException(status_code=500, detail=f"usage payload build failed: {e}") return {"ok": True, "usage": usage} @router.get("/usage/export") def usage_export( event_limit: int = 20000, max_lines: int = 200000, authorization: Optional[str] = Header(None), ): check_auth(authorization) try: usage_data = _collect_usage_events(max_lines=max_lines) usage = _build_cpa_usage_payload( usage_data.get("events") or [], source=str(usage_data.get("source") or "none"), log_path=str(usage_data.get("path") or ""), event_limit=event_limit, ) except Exception as e: raise HTTPException(status_code=500, detail=f"usage export failed: {e}") return { "version": 1, "exported_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"), "usage": usage, } @router.get("/admin/backup/export") def admin_backup_export( include_accounts: bool = True, include_settings: bool = True, include_conversations: bool = True, include_usage: bool = True, account_limit: int = 20000, conversation_limit: int = 20000, usage_event_limit: int = 20000, usage_max_lines: int = 200000, authorization: Optional[str] = Header(None), ): check_auth(authorization) try: backup: Dict[str, Any] = { "version": 1, "exported_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"), } if include_settings: backup["settings"] = _runtime_settings_snapshot(settings) if include_accounts: backup["accounts"] = _list_accounts_for_backup(account_store, limit=account_limit) if include_conversations: backup["conversations"] = _list_conversations_for_backup(conv_store, limit=conversation_limit) if include_usage: usage_data = _collect_usage_events(max_lines=usage_max_lines) backup["usage"] = _build_cpa_usage_payload( usage_data.get("events") or [], source=str(usage_data.get("source") or "none"), log_path=str(usage_data.get("path") or ""), event_limit=usage_event_limit, ) summary = { "settings": (1 if isinstance(backup.get("settings"), dict) else 0), "accounts": len(backup.get("accounts") or []), "conversations": len(backup.get("conversations") or []), "usage_requests": int(((backup.get("usage") or {}) if isinstance(backup.get("usage"), dict) else {}).get("total_requests") or 0), } except Exception as e: raise HTTPException(status_code=500, detail=f"backup export failed: {e}") return {"ok": True, "backup": backup, "summary": summary} @router.post("/admin/backup/import") def admin_backup_import( payload: Dict[str, Any], authorization: Optional[str] = Header(None), ): check_auth(authorization) body = payload if isinstance(payload, dict) else {} backup_obj = body.get("backup") backup = backup_obj if isinstance(backup_obj, dict) else body apply_settings_flag = _bool_payload(body, "apply_settings", True) import_accounts = _bool_payload(body, "import_accounts", True) import_conversations = _bool_payload(body, "import_conversations", True) import_usage = _bool_payload(body, "import_usage", True) clear_before_import = _bool_payload(body, "clear_before_import", False) reset_runtime = _bool_payload(body, "reset_runtime", True) settings_updated = 0 accounts_added = 0 accounts_skipped = 0 conversations_added = 0 conversations_skipped = 0 usage_added = 0 usage_skipped = 0 usage_failed = 0 cleared_accounts = 0 cleared_conversations = 0 try: if clear_before_import: if import_conversations and hasattr(conv_store, "clear_all"): cleared_conversations = int(conv_store.clear_all() or 0) if import_accounts and hasattr(account_store, "clear_all"): cleared_accounts = int(account_store.clear_all() or 0) if apply_settings_flag: settings_rows = backup.get("settings") if isinstance(settings_rows, dict): updated, _ignored = apply_settings( settings, settings_rows, RUNTIME_SETTING_SPECS, allowed_keys=RUNTIME_SETTING_SPECS.keys(), ) settings_updated += len(updated) if import_accounts: rows = backup.get("accounts") ret = _import_accounts_rows(account_store, rows) accounts_added = int(ret.get("added") or 0) accounts_skipped = int(ret.get("skipped") or 0) if import_conversations: rows = backup.get("conversations") if isinstance(rows, list): for row in rows: if not isinstance(row, dict): conversations_skipped += 1 continue conversation_id = str(row.get("conversation_id") or "").strip() messages = row.get("messages") if not conversation_id or not isinstance(messages, list): conversations_skipped += 1 continue safe_messages = [m for m in messages if isinstance(m, dict)] conv_store.set(conversation_id, safe_messages) conversations_added += 1 if import_usage: usage_rows = _extract_usage_rows_from_cpa_payload(backup.get("usage") if isinstance(backup.get("usage"), dict) else {}) usage_ret = _append_usage_rows_to_log(usage_rows) usage_added = int(usage_ret.get("added") or 0) usage_skipped = int(usage_ret.get("skipped") or 0) usage_failed = int(usage_ret.get("failed_requests") or 0) if reset_runtime and (settings_updated > 0 or accounts_added > 0 or conversations_added > 0): runtime.reset() if settings_updated > 0 and bootstrap_state["initialized"]: _persist_bootstrap_settings() except Exception as e: raise HTTPException(status_code=500, detail=f"backup import failed: {e}") return { "ok": True, "summary": { "settings_updated": settings_updated, "accounts_added": accounts_added, "accounts_skipped": accounts_skipped, "conversations_added": conversations_added, "conversations_skipped": conversations_skipped, "usage_added": usage_added, "usage_skipped": usage_skipped, "usage_failed_requests": usage_failed, "cleared_accounts": cleared_accounts, "cleared_conversations": cleared_conversations, "runtime_reset": bool(reset_runtime and (settings_updated > 0 or accounts_added > 0 or conversations_added > 0)), }, } @router.post("/usage/import") def usage_import( payload: Dict[str, Any], authorization: Optional[str] = Header(None), ): check_auth(authorization) rows = _extract_usage_rows_from_cpa_payload(payload) if not rows: return {"ok": True, "added": 0, "skipped": 0, "total_requests": 0, "failed_requests": 0} try: usage_ret = _append_usage_rows_to_log(rows) except Exception as e: raise HTTPException(status_code=500, detail=f"usage import failed: {e}") return { "ok": True, "added": int(usage_ret.get("added") or 0), "skipped": int(usage_ret.get("skipped") or 0), "total_requests": len(rows), "failed_requests": int(usage_ret.get("failed_requests") or 0), } return router
import os
import json
import signal
import time
from collections import deque
from datetime import datetime, timedelta, timezone
from pathlib import Path
from threading import Lock, Thread
from typing import Any, Callable, Dict, List, Optional
from fastapi import APIRouter, Header, HTTPException, Request
from app.services.bootstrap_settings_service import (
BOOTSTRAP_SETTING_SPECS,
RUNTIME_SETTING_SPECS,
apply_settings,
snapshot_settings,
)
_USAGE_MAX_LINES_CAP = 50000
_USAGE_EVENTS_CACHE_LOCK = Lock()
_USAGE_EVENTS_CACHE: Dict[str, Any] = {
"path": "",
"max_keep": 0,
"mtime_ns": -1,
"size": -1,
"built_at": 0.0,
"result": None,
}
_READY_ACCOUNT_STATUSES = {"ready", "oauth_ok", "verified"}
def _to_bool(v: Any, default: bool = False) -> bool:
if v is None:
return default
if isinstance(v, bool):
return v
return str(v).strip().lower() in ("1", "true", "yes", "y", "on")
def _runtime_settings_snapshot(settings) -> Dict[str, Any]:
return snapshot_settings(settings, RUNTIME_SETTING_SPECS)
def _trigger_self_restart(delay_sec: float = 0.3) -> None:
def _worker() -> None:
try:
time.sleep(max(float(delay_sec), 0.05))
except Exception:
pass
try:
os.kill(os.getpid(), signal.SIGTERM)
except Exception:
os._exit(0)
Thread(target=_worker, daemon=True).start()
def _parse_emails_text(text: str) -> List[Dict[str, str]]:
out: List[Dict[str, str]] = []
seen = set()
for raw in str(text or "").splitlines():
line = raw.strip().lstrip("\ufeff")
if not line or line.startswith("#"):
continue
if "," in line:
email, password = line.split(",", 1)
elif "\t" in line:
email, password = line.split("\t", 1)
else:
email, password = line, ""
email = email.strip()
password = password.strip()
if not email:
continue
key = email.lower()
if key in seen:
continue
seen.add(key)
out.append({"email": email, "password": password})
return out
def _parse_items(payload: Dict[str, Any]) -> List[Dict[str, str]]:
if isinstance(payload.get("emails_text"), str) and payload.get("emails_text", "").strip():
return _parse_emails_text(str(payload.get("emails_text")))
rows = payload.get("items")
out: List[Dict[str, str]] = []
seen = set()
if isinstance(rows, list):
for item in rows:
if isinstance(item, str):
email = item.strip()
password = ""
elif isinstance(item, dict):
email = str(item.get("email") or "").strip()
password = str(item.get("password") or "").strip()
else:
continue