"""用户任务只读库里已有的数据,再写成表格。采集和导出共用排队进程的并行数量。""" from __future__ import annotations import logging import threading from datetime import date, datetime, timedelta, timezone from sqlalchemy import select from app.collect.io import parse_upload, write_table from app.collect.remote import fetch_nqi from app.collect.schedule import next_run_at from app.collect.store import replace_batch from app.config import inline_worker_allowed, postgres_conninfo, result_dir from app.db import session_scope from app.models import CellData, CollectionSource, ExportTask, NqiAccount, utcnow from app.nqi.adhoc import export_table, time_window from app.nqi.client import NqiAuthError, NqiClient, NqiError logger = logging.getLogger("decom") MIN_CONCURRENCY = 1 MAX_CONCURRENCY = 32 DEFAULT_CONCURRENCY = 4 def check_period(days: int) -> int: if days < 1 or days > 31: raise ValueError("周期最短一天,最长一个月") return days def check_refresh(seconds: int) -> int: if seconds < 60 or seconds > 24 * 60 * 60: raise ValueError("刷新间隔需要在 1 分钟到 1 天之间") return seconds def check_concurrency(value: int) -> int: if value < MIN_CONCURRENCY or value > MAX_CONCURRENCY: raise ValueError("并行数量需要在 1 到 32 之间") return value def current_concurrency() -> int: from app.config import installed if not installed(): return DEFAULT_CONCURRENCY from app.models import AppSetting with session_scope() as session: setting = session.get(AppSetting, 1) if setting is None: return DEFAULT_CONCURRENCY try: return check_concurrency(int(setting.worker_concurrency)) except (TypeError, ValueError): return DEFAULT_CONCURRENCY def upsert_rows(session, source: str, rows: list[dict]) -> int: count = 0 for row in rows: existing = session.scalar( select(CellData).where( CellData.cell_key == row["cell_key"], CellData.observed_at == row["observed_at"], CellData.source == source, ) ) if existing is None: session.add( CellData( cell_key=row["cell_key"], observed_at=row["observed_at"], source=source, metrics=row["metrics"], ) ) count += 1 else: existing.metrics = row["metrics"] return count def query_cells(session, params: dict) -> list[dict]: statement = select(CellData).order_by(CellData.observed_at, CellData.cell_key) cell_key = str(params.get("cellKey") or "").strip() if cell_key: statement = statement.where(CellData.cell_key == cell_key) start = _optional_time(params.get("start")) end = _optional_time(params.get("end")) if start is not None: statement = statement.where(CellData.observed_at >= start) if end is not None: statement = statement.where(CellData.observed_at <= end) rows = session.scalars(statement).all() return [ {"cell_key": row.cell_key, "observed_at": row.observed_at, "metrics": row.metrics or {}} for row in rows ] def _optional_time(value) -> datetime | None: if not value: return None text = str(value).replace("/", "-").replace("T", " ") for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"): try: return datetime.strptime(text, fmt).replace(tzinfo=timezone.utc) except ValueError: continue return None def execute_export(task_id: int) -> None: with session_scope() as session: task = session.get(ExportTask, task_id) if task is None or task.status not in {"queued", "running"}: return task.status = "running" params = dict(task.params or {}) file_format = task.file_format try: with session_scope() as session: rows = query_cells(session, params) name, content = write_table(file_format, rows) result_dir().mkdir(parents=True, exist_ok=True) path = result_dir() / f"{task_id}-{name}" path.write_bytes(content) with session_scope() as session: task = session.get(ExportTask, task_id) if task is None: return task.status = "done" task.result_name = path.name task.finished_at = utcnow() except Exception as exc: logger.info("导出失败: %s", exc) with session_scope() as session: task = session.get(ExportTask, task_id) if task is None: return task.status = "failed" task.error = str(exc) or "导出失败" task.finished_at = utcnow() def execute_collection(source_id: int) -> None: with session_scope() as session: source = session.get(CollectionSource, source_id) if source is None or not source.enabled: return kind = source.kind config = dict(source.config or {}) source_name = source.name account = None if kind == "nqi": account = session.scalar( select(NqiAccount).where(NqiAccount.credential_valid.is_(True)).order_by(NqiAccount.saved_at.desc()) ) cookies = list(account.cookies or []) if account is not None else [] else: cookies = [] try: if kind == "nqi": if not cookies: raise ValueError("账号池里没有可用凭证") if config.get("tables"): _save_nqi_tables(cookies, config, source_id, source_name) with session_scope() as session: source = session.get(CollectionSource, source_id) if source is not None: source.last_error = "" return name, content = _fetch_nqi_sync(cookies, config) else: raise ValueError("未知的采集来源") rows = parse_upload(name, content) with session_scope() as session: source = session.get(CollectionSource, source_id) if source is None: return upsert_rows(session, kind, rows) source.last_error = "" except Exception as exc: logger.info("采集失败: %s", exc) with session_scope() as session: source = session.get(CollectionSource, source_id) if source is not None: source.last_error = str(exc) or "采集失败" def _save_nqi_tables(cookies: list, config: dict, source_id: int, source_name: str) -> None: import asyncio from app.db import engine tables = list(config.get("tables") or []) mode = str(config.get("timeMode") or "") count = int(config.get("timeCount") or 1) city = str(config.get("city") or "") schedule = config.get("schedule") if isinstance(config.get("schedule"), dict) else {} start, end = time_window(mode, count, date.today()) async def run() -> list[tuple[str, list[dict], list[dict]]]: client = NqiClient() try: client.import_cookies(cookies) try: await client.current_user() except NqiAuthError as exc: raise ValueError("账号池凭证已失效") from exc saved: list[tuple[str, list[dict], list[dict]]] = [] for table in tables: tablename = str(table.get("tablename") or "") _title, columns, rows = await export_table(client, tablename, start, end, city) saved.append((tablename, columns, rows)) return saved finally: await client.aclose() batches = asyncio.run(run()) with engine().begin() as connection: for tablename, columns, rows in batches: replace_batch( connection, tablename, columns, rows, task_id=source_id, task_name=source_name, time_mode=mode, time_count=count, window_start=start, window_end=end, city=city, schedule=schedule, ) def _fetch_nqi_sync(cookies: list, config: dict) -> tuple[str, bytes]: import asyncio async def run() -> tuple[str, bytes]: client = NqiClient() try: client.import_cookies(cookies) try: await client.current_user() except NqiAuthError as exc: raise ValueError("账号池凭证已失效") from exc return await fetch_nqi(client, config) finally: await client.aclose() return asyncio.run(run) def enqueue_export(task_id: int) -> None: if _defer("decom_export", task_id=task_id): return _run_inline(execute_export, task_id) def enqueue_collection(source_id: int) -> None: if _defer("decom_collect", source_id=source_id): return _run_inline(execute_collection, source_id) def _run_inline(target, item_id: int) -> None: if not inline_worker_allowed(): logger.info("没有排队数据库,任务 %s 留在排队中", item_id) return threading.Thread(target=target, args=(item_id,), daemon=True).start() def _defer(name: str, **kwargs) -> bool: if not postgres_conninfo(): return False from app.tasks.queue import defer defer(name, **kwargs) return True def scan_sources() -> None: now = utcnow() due_ids: list[int] = [] with session_scope() as session: sources = session.scalars(select(CollectionSource).where(CollectionSource.enabled.is_(True))).all() for source in sources: if source.kind != "nqi": source.enabled = False source.last_error = "不再从 FTP 采集" continue schedule = (source.config or {}).get("schedule") if not isinstance(schedule, dict) or not schedule.get("mode"): if source.next_run_at is not None and source.next_run_at > now: continue source.next_run_at = now + timedelta(days=source.period_days) due_ids.append(source.id) continue if source.next_run_at is None: source.next_run_at = next_run_at(schedule, now) continue if source.next_run_at > now: continue source.next_run_at = next_run_at(schedule, now) due_ids.append(source.id) for source_id in due_ids: enqueue_collection(source_id) async def refresh_accounts() -> None: with session_scope() as session: accounts = session.scalars(select(NqiAccount)).all() snapshots = [(item.id, list(item.cookies or [])) for item in accounts] for account_id, cookies in snapshots: if not cookies: continue outcome = await _touch(cookies) with session_scope() as session: account = session.get(NqiAccount, account_id) if account is None or outcome is None: continue valid, user, refreshed = outcome account.credential_valid = valid if user is not None: account.user_name = user.get("userName") or account.user_name account.city_name = user.get("cityName") or account.city_name account.org_name = user.get("orgName") or account.org_name account.cookies = refreshed account.saved_at = utcnow() async def _touch(cookies: list): client = NqiClient() try: client.import_cookies(cookies) user = await client.touch_session() renewed = await client.renew_ticket() if not renewed: logger.info("门户登录仍有效,单点票据没有续上") return renewed, user, client.export_cookies() except NqiAuthError: return False, None, cookies except (NqiError, OSError): return None finally: await client.aclose()