"""工参按周缓存。 每个地市从 HISTORY_START 起每周一一份快照。有人登录大数据平台账号、或定时检查发现缺了哪几周时排一个补取任务: 一次只取一份,取完还缺就接着排下一次,评估任务可以插在中间执行。 一个地市同一时间只取一份:已有快照正在取时补取任务直接结束,排队里同一个地市也只留一个任务。 凭证失效或平台出错时停下,下次登录或定时检查时从缺的那一周接着补。 """ from __future__ import annotations import asyncio import logging import os from collections.abc import Awaitable, Callable from datetime import date from sqlalchemy import select from app.collect.accounts import borrow_account, has_valid_account, release_account from app.collect.gongcan import ( GongcanError, GongcanStore, china_today, expected_mondays, fetch_snapshot, short_city, ) from app.config import postgres_conninfo from app.db import engine from app.models import GongcanSnapshot from app.nqi.client import NqiAuthError, NqiClient, NqiError from app.nqi.opencode import OpenCode logger = logging.getLogger("decom") TASK = "decom_gongcan_sync" WAIT_SECONDS = 60 _SNAPSHOT = GongcanSnapshot.__table__ def pooled_loader(city: str) -> Callable[[str, date], Awaitable[dict[str, list[dict]]]]: """用号池里的有效账号取一份快照,先用本地市的账号;账号的凭证失效就换下一个。""" async def load(_city: str, day: date) -> dict[str, list[dict]]: tried: set[int] = set() while True: borrowed = borrow_account(tried, prefer_city=city) if borrowed is None: raise GongcanError("号池里没有可用的大数据平台账号") account_id, cookies = borrowed tried.add(account_id) invalid = False client = NqiClient() client.import_cookies(cookies) try: return await fetch_snapshot(OpenCode(client), _city, day) except NqiAuthError: invalid = True logger.info("账号 %s 的凭证已失效,换一个账号取工参", account_id) finally: await client.aclose() release_account(account_id, invalid=invalid) return load def sync_cities() -> list[str]: """定时补取的地市:库里已经有就绪快照的。新地市由登录或评估取到第一份后加入。""" with engine().connect() as connection: return sorted(connection.execute(select(_SNAPSHOT.c.city).where(_SNAPSHOT.c.status == "ready").distinct()).scalars()) def sync_once(city: str, *, today: date | None = None, store: GongcanStore | None = None) -> tuple[date | None, int]: """补一份缺的周一快照,新的先补。返回(这次取到的日期,还缺几份)。""" store = store or GongcanStore(engine(), pooled_loader(city)) days = expected_mondays(today or china_today())[::-1] missing = len(store.missing_dates(city, days)) day = store.next_to_fill(city, days) if day is None or not asyncio.run(store.fill(city, day)): return None, missing return day, missing - 1 def execute_sync(city: str) -> None: try: fetched, remaining = sync_once(city) except (GongcanError, NqiError) as exc: logger.info("工参缓存 %s 这次没取成:%s", city, exc) return if not remaining: if fetched is not None: logger.info("工参缓存 %s 已补 %s,已补齐", city, fetched) return if fetched is None: # 评估任务正在取这个地市的某一份,或刚失败还在冷却:过一会儿再来,不等定时检查。 if has_valid_account(): request_sync(city, delay=WAIT_SECONDS) return logger.info("工参缓存 %s 已补 %s,还缺 %s 周", city, fetched, remaining) request_sync(city) def request_sync(city: str, *, delay: int = 0) -> bool: """排一个补取任务,delay 秒后执行;这个地市已经有一个在排队时不重复排。演示模式和没有队列时不排。""" name = short_city(city) if not name or not postgres_conninfo() or os.environ.get("DECOM_EVAL_SOURCE", "").strip().lower() == "mock": return False from app.tasks.queue import defer return defer(TASK, queueing_lock=f"gongcan-sync:{name}", delay=delay, city=name) def request_missing() -> None: """定时检查:已有快照的地市还缺哪几周就排补取。没有有效凭证、正在取、或刚取失败时不排。""" if not has_valid_account(): return days = expected_mondays(china_today()) for city in sync_cities(): if GongcanStore(engine(), pooled_loader(city)).next_to_fill(city, days) is not None: request_sync(city) def cache_status(today: date | None = None) -> list[dict]: """每个地市的缓存进度,给管理面板看。""" days = set(expected_mondays(today or china_today())) cities: dict[str, dict] = {} with engine().connect() as connection: rows = connection.execute( select(_SNAPSHOT.c.city, _SNAPSHOT.c.snapshot_date, _SNAPSHOT.c.status, _SNAPSHOT.c.error, _SNAPSHOT.c.updated_at).order_by(_SNAPSHOT.c.updated_at) ).all() for row in rows: if row.snapshot_date not in days: continue item = cities.setdefault(row.city, {"city": row.city, "expected": len(days), "ready": 0, "earliest": None, "latest": None, "loading": None, "error": "", "errorAt": None}) text = row.snapshot_date.isoformat() if row.status == "ready": item["ready"] += 1 item["earliest"] = min(item["earliest"] or text, text) item["latest"] = max(item["latest"] or text, text) elif row.status == "loading": item["loading"] = text elif row.status == "failed": item["error"] = f"{text} {row.error}"[:300] item["errorAt"] = row.updated_at.isoformat() if row.updated_at else None return sorted(cities.values(), key=lambda item: item["city"])