feat: 工参每周一一份并提前缓存,登录后自动补缺;评估按周一取工参,指标等平台同步三天后再查

- 工参从 2024-01-01 起每周一一份,排队任务一次补一份,新的周先补;一个地市同时只取一份
- 大数据平台账号登录成功后排补取,排队进程每 10 分钟检查缺的周;排队进程重启时放开没取完的快照
- 拆除前工参用拆除日上一周的周一,拆除后用当周的周一;待拆小区不参与周边站和指标匹配
- 一周的指标等周日过后第 3 天才查,没到时间在结果说明里写明哪天之后有数据
- AI 工作区没就绪时开通接口返回 200,改为等待重试,最多 150 秒
- 排任务加锁,避免多个线程同时排时用到已关闭的连接池
- 运行面板显示各地市工参缓存进度
This commit is contained in:
2026-11-12 12:31:03 +08:00
parent 452b01498f
commit 3a7a5b39b4
20 changed files with 814 additions and 180 deletions
+11 -2
View File
@@ -18,7 +18,8 @@ class AccountUnavailable(Exception):
self.invalid = invalid
def borrow_account(exclude: set[int] | None = None) -> tuple[int, list] | None:
def borrow_account(exclude: set[int] | None = None, prefer_city: str = "") -> tuple[int, list] | None:
"""prefer_city 给出时,先用这个地市的账号,没有再用别的。"""
skipped = exclude or set()
with _lock:
with session_scope() as session:
@@ -32,7 +33,10 @@ def borrow_account(exclude: set[int] | None = None) -> tuple[int, list] | None:
NqiAccount.id,
)
).all()
account = next((row for row in rows if row.id not in skipped and row.cookies), None)
usable = [row for row in rows if row.id not in skipped and row.cookies]
if prefer_city:
usable.sort(key=lambda row: not (row.city_name or "").startswith(prefer_city))
account = usable[0] if usable else None
if account is None:
return None
account.active_tasks += 1
@@ -53,6 +57,11 @@ def release_account(account_id: int, *, invalid: bool = False) -> None:
account.credential_valid = False
def has_valid_account() -> bool:
with session_scope() as session:
return session.scalar(select(NqiAccount.id).where(NqiAccount.credential_valid.is_(True)).limit(1)) is not None
def reset_active_tasks() -> None:
with session_scope() as session:
session.execute(update(NqiAccount).values(active_tasks=0))
+108 -34
View File
@@ -3,6 +3,9 @@
一份快照由 OpenCode 在一条提示词里导出:全市当天有效(eff_from_date <= 当天 < eff_to_date)的 4G、5G 工参,
CGI、经纬度和属性在同一条 SQL 里,没有有效坐标的小区经纬度留空。
即席查询的工参表没有日期列,4G 只有当前记录,取不到历史日,所以工参不走即席查询。
快照只取每周一的:从 HISTORY_START 起每周一一份,提前缓存进库(见 gongcan_sync),评估按周一取用。
平台数据约三天同步好,所以最新能取的是三天前所在那一周的周一。
"""
from __future__ import annotations
@@ -38,12 +41,44 @@ CELL_TABLES = {"4G": CellData4G.__table__, "5G": CellData5G.__table__}
COORDS = ("longitude", "latitude")
FAILED_COOLDOWN = timedelta(minutes=10)
STALE_LOADING = timedelta(minutes=40)
SYNC_LAG_DAYS = 3
HISTORY_START = date(2024, 1, 1)
BEFORE_LOOKBACK_WEEKS = 4
class GongcanError(Exception):
pass
def short_city(name: object) -> str:
"""平台账号里的地市带「市」「分公司」,工参和即席查询用不带后缀的名字。"""
text = str(name or "").strip()
for suffix in ("分公司", "市"):
if text.endswith(suffix) and len(text) > len(suffix):
text = text[: -len(suffix)]
return text
def monday_of(day: date) -> date:
return day - timedelta(days=day.weekday())
def latest_monday(today: date) -> date:
"""现在能取的最新一个周一。周一的工参要到周四才取。"""
return monday_of(today - timedelta(days=SYNC_LAG_DAYS))
def expected_mondays(today: date) -> list[date]:
"""库里应该有的全部周一,从早到晚。"""
last = latest_monday(today)
days = []
day = HISTORY_START
while day <= last:
days.append(day)
day += timedelta(days=7)
return days
class GongcanMissing(GongcanError):
pass
@@ -217,6 +252,12 @@ def fail_snapshot(engine: Engine, snapshot_id: int, error: str, now: datetime) -
connection.execute(update(_SNAPSHOT).where(_SNAPSHOT.c.id == snapshot_id).values(status="failed", error=error[:500], updated_at=now))
def release_loading(engine: Engine) -> int:
"""排队进程启动时调用:上一个进程没取完的快照行删掉,后面的任务可以马上重新取,不用等它过期。"""
with engine.begin() as connection:
return connection.execute(delete(_SNAPSHOT).where(_SNAPSHOT.c.status == "loading")).rowcount
def _has_target(target: Target):
found = []
for tech, table in CELL_TABLES.items():
@@ -260,6 +301,45 @@ class GongcanStore:
def has_target(self, city: str, day: date, target: Target) -> bool:
return bool(self.dates_with_target(city, target, day, day + timedelta(days=1)))
def missing_dates(self, city: str, days: list[date]) -> list[date]:
"""days 里库中还没有就绪快照的日期,顺序不变。"""
if not days:
return []
ready = set(self.ready_dates(city, min(days), max(days) + timedelta(days=1)))
return [day for day in days if day not in ready]
def next_to_fill(self, city: str, days: list[date]) -> date | None:
"""days 里下一份该补的日期,按 days 的顺序挑,取失败过的排到最后。
这个地市有快照正在取、或刚取失败还在冷却时返回 None:一个地市一次只取一份,平台出错时不连着打。
"""
missing = self.missing_dates(city, days)
if not missing:
return None
now = self.clock()
failed: set[date] = set()
with self.engine.connect() as connection:
rows = connection.execute(
select(_SNAPSHOT.c.snapshot_date, _SNAPSHOT.c.status, _SNAPSHOT.c.updated_at).where(_SNAPSHOT.c.city == city, _SNAPSHOT.c.status != "ready")
).all()
for row in rows:
age = now - _aware(row.updated_at)
if row.status == "loading" and age < STALE_LOADING:
return None
if row.status == "failed":
if age < FAILED_COOLDOWN:
return None
failed.add(row.snapshot_date)
return next((day for day in missing if day not in failed), missing[0])
async def fill(self, city: str, day: date) -> bool:
"""取回这一天入库。别人抢先在取时返回 False。"""
snapshot_id = claim_snapshot(self.engine, city, day, self.clock())
if snapshot_id is None:
return False
await self._load(snapshot_id, city, day)
return True
def cells(self, city: str, day: date) -> list[dict]:
"""当天快照里 4G、5G 的全部小区,字段见 unified。"""
with self.engine.connect() as connection:
@@ -319,57 +399,51 @@ def china_today() -> date:
return (datetime.now(timezone.utc) + timedelta(hours=8)).date()
def month_start(day: date, offset: int = 0) -> date:
index = day.year * 12 + day.month - 1 + offset
return date(index // 12, index % 12 + 1, 1)
@dataclass(frozen=True)
class AfterPick:
day: date
target_present: bool
async def pick_before(store: GongcanStore, city: str, target: Target, removal: date, months: int = 3) -> date:
"""拆除前用的工参日期。
def before_monday(removal: date, today: date) -> date:
"""拆除前工参:拆除日上一周的周一。那一天还取不到时用现在能取的最新一个周一。"""
return min(monday_of(removal) - timedelta(days=7), latest_monday(today))
库里拆除日前、近 months 个月(从 months 个月前的 1 号算起)有目标的快照,取最晚的一份;
没有就从拆除日上个月 1 号起逐月往前,库里没有的那天才去平台取,取到有目标的为止。
def after_monday(removal: date, today: date) -> date | None:
"""拆除后工参:拆除日当周的周一。那一天还取不到时没有拆除后工参。"""
day = monday_of(removal)
return day if day <= latest_monday(today) else None
async def pick_before(store: GongcanStore, city: str, target: Target, removal: date, today: date) -> date:
"""拆除前用的工参日期:拆除日上一周的周一;那份里没有目标就再往前一周,最多往前 BEFORE_LOOKBACK_WEEKS 周。
库里没有的周一才去平台取。
"""
earliest = month_start(removal, -months)
found = store.dates_with_target(city, target, earliest, removal)
if found:
return found[-1]
stored = set(store.ready_dates(city, earliest, removal))
for back in range(1, months + 1):
day = month_start(removal, -back)
if day in stored:
continue
first = before_monday(removal, today)
if first < HISTORY_START:
raise GongcanMissing(f"拆除日期 {removal} 太早,工参只从 {HISTORY_START} 起缓存")
for back in range(BEFORE_LOOKBACK_WEEKS + 1):
day = first - timedelta(days=7 * back)
if day < HISTORY_START:
break
await store.ensure(city, day)
if store.has_target(city, day, target):
return day
raise GongcanMissing(f"拆除前 {months} 个月的工参里都没有{target.label}")
raise GongcanMissing(f"{first} 及之前 {BEFORE_LOOKBACK_WEEKS} 周的工参里都没有{target.label}")
async def pick_after(store: GongcanStore, city: str, target: Target, removal: date, today: date) -> AfterPick | None:
"""拆除后用的工参日期,越接近今天越好。
"""拆除后用的工参日期:拆除日当周的周一。
库里拆除日之后、目标已经不在的快照取最晚的一份;都还在时,最晚那份是昨天就直接用,
不是就去平台取昨天的。目标仍在只做标记,不算失败。拆除日还没过去时返回 None。
这一天通常还在拆除日之前,目标仍在工参里是正常的,只做标记。还取不到这一天时返回 None。
"""
yesterday = today - timedelta(days=1)
if yesterday <= removal:
day = after_monday(removal, today)
if day is None:
return None
start = removal + timedelta(days=1)
stored = store.ready_dates(city, start, today)
present = set(store.dates_with_target(city, target, start, today))
absent = [day for day in stored if day not in present]
if absent:
return AfterPick(absent[-1], False)
if stored and stored[-1] == yesterday:
return AfterPick(yesterday, True)
await store.ensure(city, yesterday)
return AfterPick(yesterday, store.has_target(city, yesterday, target))
await store.ensure(city, day)
return AfterPick(day, store.has_target(city, day, target))
def is_indoor(cell: dict) -> bool:
+137
View File
@@ -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"])