feat: 工参每周一一份并提前缓存,登录后自动补缺;评估按周一取工参,指标等平台同步三天后再查
- 工参从 2024-01-01 起每周一一份,排队任务一次补一份,新的周先补;一个地市同时只取一份 - 大数据平台账号登录成功后排补取,排队进程每 10 分钟检查缺的周;排队进程重启时放开没取完的快照 - 拆除前工参用拆除日上一周的周一,拆除后用当周的周一;待拆小区不参与周边站和指标匹配 - 一周的指标等周日过后第 3 天才查,没到时间在结果说明里写明哪天之后有数据 - AI 工作区没就绪时开通接口返回 200,改为等待重试,最多 150 秒 - 排任务加锁,避免多个线程同时排时用到已关闭的连接池 - 运行面板显示各地市工参缓存进度
This commit is contained in:
@@ -0,0 +1,137 @@
|
||||
"""工参按周缓存。
|
||||
|
||||
每个地市从 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"
|
||||
_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 fetched is None:
|
||||
return
|
||||
logger.info("工参缓存 %s 已补 %s,还缺 %s 周", city, fetched, remaining)
|
||||
if remaining:
|
||||
request_sync(city)
|
||||
|
||||
|
||||
def request_sync(city: str) -> bool:
|
||||
"""排一个补取任务;这个地市已经有一个在排队时不重复排。演示模式和没有队列时不排。"""
|
||||
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}", 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"])
|
||||
Reference in New Issue
Block a user