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
+4 -11
View File
@@ -12,6 +12,7 @@ from sqlalchemy import delete, select
from sqlalchemy.orm import Session
from app.api.deps import Actor, current_actor
from app.collect.gongcan import short_city
from app.db import get_session
from app.evaluate.compute import NEIGHBOR_SITES
from app.evaluate.demand import (
@@ -49,27 +50,19 @@ def _user(actor: Actor) -> Actor:
return actor
def _short_city(name: str) -> str:
text = (name or "").strip()
for suffix in ("分公司", "市"):
if text.endswith(suffix) and len(text) > len(suffix):
text = text[: -len(suffix)]
return text
def _default_city(session: Session, actor: Actor) -> str:
if actor.kind == "nqi":
account = session.scalar(select(NqiAccount).where(NqiAccount.login_id == actor.id))
if account is not None and account.city_name:
return _short_city(account.city_name)
return short_city(account.city_name)
pooled = session.scalar(select(NqiAccount.city_name).where(NqiAccount.city_name != "").order_by(NqiAccount.saved_at.desc()))
if pooled:
return _short_city(pooled)
return short_city(pooled)
return session.scalar(select(GongcanSnapshot.city).order_by(GongcanSnapshot.id.desc())) or ""
def _check_city(value: object) -> str:
city = _short_city(str(value or ""))
city = short_city(value)
if not city:
raise _bad("请填写地市")
if len(city) > 32:
+15 -1
View File
@@ -2,6 +2,7 @@ from __future__ import annotations
import asyncio
import base64
import logging
import re
from datetime import date, datetime, timedelta, timezone
@@ -15,6 +16,7 @@ from app.config import env_database, hosted, installed
from app.install import InstallError, perform_install
from app.db import get_session, session_scope
from app.models import AppSetting, CollectionSource, NqiAccount, User, utcnow
from app.collect.gongcan_sync import cache_status, request_sync
from app.collect.schedule import next_run_at, parse_schedule
from app.nqi.adhoc import TIME_MODES, catalog_tree, categories, search_by_field, table_fields, tables, time_window
from app.nqi.client import NqiAuthError, NqiClient, NqiError
@@ -22,6 +24,7 @@ from app.nqi.flows import drop, purge, remember, take
from app.security import hash_password, issue_token, verify_password
from app.tasks.runner import check_concurrency, check_refresh, enqueue_collection
logger = logging.getLogger("decom")
router = APIRouter(prefix="/api")
# 在响应发出前提交,客户端紧接着发出的请求才能读到刚写入的内容。
db_session = Depends(get_session, scope="function")
@@ -282,6 +285,9 @@ async def nqi_finish(body: dict) -> dict:
account.credential_valid = adhoc_ready
login_id = account.login_id
name = account.user_name or account.login_id
city = account.city_name
if adhoc_ready:
await asyncio.to_thread(_cache_gongcan, city)
if purpose == "pool":
return {"status": "ok"}
return _token_for("nqi", login_id, "user", name)
@@ -400,7 +406,7 @@ def update_user_password(user_id: int, body: dict, actor: Actor = Depends(curren
def admin_dashboard(actor: Actor = Depends(current_actor), session: Session = db_session) -> dict:
require_admin(actor)
rows = session.scalars(select(NqiAccount)).all()
return {"pool": _pool_dashboard(rows)}
return {"pool": _pool_dashboard(rows), "gongcan": cache_status()}
@router.get("/admin/pool")
@@ -723,6 +729,14 @@ def _pool_dashboard(rows: list[NqiAccount]) -> dict:
}
def _cache_gongcan(city: str) -> None:
"""有新凭证了,补取这个地市缺的工参。排不上只记日志,不影响登录。"""
try:
request_sync(city)
except Exception as exc:
logger.info("登录后排工参补取未完成: %s", exc)
def _save_pool(session: Session, user: dict, cookies: list) -> NqiAccount:
login_id = str(user.get("loginId") or "").strip()
if not login_id:
+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"])
+29 -12
View File
@@ -10,7 +10,7 @@ from collections.abc import Callable
from dataclasses import replace
from datetime import date, timedelta
from app.collect.gongcan import GongcanMissing, Target, evaluable, nearest_sites, target_center
from app.collect.gongcan import SYNC_LAG_DAYS, GongcanMissing, Target, after_monday, evaluable, monday_of, nearest_sites, target_center
from app.evaluate.demand import DemandRow, SiteGroup
from app.evaluate.sources import GongcanSource, MetricSource
@@ -24,15 +24,20 @@ class EvalFailure(Exception):
def week_of(day: date) -> tuple[date, date]:
"""拆除日所在的自然周,周一到周日。"""
monday = day - timedelta(days=day.weekday())
monday = monday_of(day)
return monday, monday + timedelta(days=6)
def ready_day(week_end: date) -> date:
"""这一周的指标从哪天起可以查:平台数据约三天同步好,周日之后再等 SYNC_LAG_DAYS 天。"""
return week_end + timedelta(days=SYNC_LAG_DAYS)
def windows(removal: date, today: date) -> tuple[tuple[date, date], tuple[date, date] | None]:
"""停闭前是拆除日所在周的上一周,停闭后是拆除日所在的那一周。当周周日还没过就没有停闭后。"""
"""停闭前是拆除日所在周的上一周,停闭后是拆除日所在的那一周。当周的数据平台还没同步好时没有停闭后。"""
after_start, after_end = week_of(removal)
before = (after_start - timedelta(days=7), after_end - timedelta(days=7))
if today <= after_end:
if today < ready_day(after_end):
return before, None
return before, (after_start, after_end)
@@ -91,7 +96,7 @@ def evaluate_site(
target = Target(site=group.site) if group.site else Target(cgis=tuple(group.cgis))
stage("确定拆除前工参")
try:
before_day = gongcan.before_day(city, target, group.removal)
before_day = gongcan.before_day(city, target, group.removal, today)
except GongcanMissing as exc:
raise EvalFailure(str(exc)) from exc
stage("确定拆除后工参")
@@ -112,7 +117,12 @@ def evaluate_site(
missing = [cgi for cgi in group.cgis if cgi not in {cell["cgi"] for cell in targets}]
if missing:
notes.append(f"{before_day} 的工参里没有 {'、'.join(missing)}")
pool = gongcan.cells(city, after.day) if after is not None and after.day != before_day else before_cells
wanted_after = after_monday(group.removal, today)
if after is None and wanted_after is not None:
notes.append(f"{wanted_after} 的工参没取到,周边站按拆除前工参算")
# 拆除后工参是拆除当周周一的,待拆小区通常还在里面;算周边站和取指标时去掉它们。
own = {cell["cgi"] for cell in targets} | set(group.cgis)
pool = [cell for cell in (gongcan.cells(city, after.day) if after is not None and after.day != before_day else before_cells) if cell["cgi"] not in own]
center = target_center(targets)
neighbors: list[tuple[str, float]] = []
if center is None:
@@ -125,8 +135,12 @@ def evaluate_site(
stage("查询停闭前后指标")
before_window, after_window = windows(group.removal, today)
if after_window is None:
notes.append("拆除当周还没结束,没有停闭后的指标")
before_ready = today >= ready_day(before_window[1])
if not before_ready:
notes.append(f"停闭前一周({before_window[0]} 至 {before_window[1]})的指标平台要到 {ready_day(before_window[1])} 才同步好,现在没有停闭前后的指标")
elif after_window is None:
after_week = week_of(group.removal)
notes.append(f"停闭后一周({after_week[0]} 至 {after_week[1]})的指标平台要到 {ready_day(after_week[1])} 才同步好,现在没有停闭后的指标")
by_site: dict[str, list[dict]] = {}
for cell in pool:
name = cell.get("cell_name") or ""
@@ -137,7 +151,7 @@ def evaluate_site(
for cell in sorted(by_site.get(site, []), key=lambda item: (item.get("tech") != "4G", item.get("cell_name") or "")):
picked.append((site, distance, cell))
picked_cells = [cell for _site, _distance, cell in picked]
before_metrics = metrics.window(picked_cells, *before_window) if picked_cells else {}
before_metrics = metrics.window(picked_cells, *before_window) if picked_cells and before_ready else {}
after_metrics = metrics.window(picked_cells, *after_window) if picked_cells and after_window else {}
item2 = [
{
@@ -173,7 +187,7 @@ def evaluate_site(
}
if group.kind == "dixiao":
stage("查询扇区指标")
section1, sectors, sector_notes = _dixiao_sections(rows, targets, before_cells, metrics, before_window, after_window)
section1, sectors, sector_notes = _dixiao_sections(rows, targets, before_cells, metrics, before_window if before_ready else None, after_window)
payload["section1"] = section1
payload["sectors"] = sectors
notes.extend(sector_notes)
@@ -199,11 +213,12 @@ def _dixiao_sections(
targets: list[dict],
pool: list[dict],
metrics: MetricSource,
before_window: tuple[date, date],
before_window: tuple[date, date] | None,
after_window: tuple[date, date] | None,
) -> tuple[list[dict], list[dict], list[str]]:
"""before_window 为空表示停闭前一周的指标还没同步好:第 1 节只留名称,第 2 节不出。"""
notes: list[str] = []
own = metrics.profile(targets, *before_window)
own = metrics.profile(targets, *before_window) if before_window else {}
section1 = []
for row in rows:
item = own.get(row.cgi, {})
@@ -239,6 +254,8 @@ def _dixiao_sections(
"评估结果": "通过",
}
)
if before_window is None:
return section1, [], notes
own_cgis = {row.cgi for row in rows}
by_sector: dict[str, list[DemandRow]] = {}
+33 -14
View File
@@ -1,7 +1,7 @@
"""评估取数。
工参:本系统的工参快照(CellData_4G/5G),拆除前后按 pick_before / pick_after 选日期,库里没有的日期
用提交人的大数据平台凭证经 OpenCode 补取;本系统账号没有凭证时借号池里的账号。
工参:本系统的工参快照(CellData_4G/5G),每周一一份。拆除前用拆除日上一周的周一,拆除后用拆除日当周的周一;
库里还没有的周一用提交人的大数据平台凭证经 OpenCode 补取,本系统账号没有凭证时借号池里的账号。
指标按周(周一到周日)取。4G 小区的流量、质量、扇区和频段取即席查询「[管理视图]重要场景-小区周粒度」;
MR 覆盖、竞对和 5G 小区还没接,先用模拟数据,同一小区同一时间段每次结果相同。
环境变量 DECOM_EVAL_SOURCE=mock 时工参和指标都用模拟数据,便于本地演示。
@@ -11,23 +11,35 @@ from __future__ import annotations
import asyncio
import hashlib
import logging
import math
import os
from collections.abc import Callable, Iterator
from contextlib import contextmanager
from datetime import date, datetime, time, timedelta
from datetime import date, datetime, time
from typing import Protocol
from sqlalchemy import select
from app.collect.accounts import borrow_account, release_account
from app.collect.gongcan import AfterPick, GongcanError, GongcanStore, Target, fetch_snapshot, month_start, pick_after, pick_before
from app.collect.gongcan import (
AfterPick,
GongcanError,
GongcanStore,
Target,
after_monday,
before_monday,
fetch_snapshot,
pick_after,
pick_before,
)
from app.db import engine, session_scope
from app.models import NqiAccount
from app.nqi import adhoc
from app.nqi.client import NqiAuthError, NqiClient, NqiError
from app.nqi.opencode import OpenCode
logger = logging.getLogger("decom")
METRIC_KEYS = ("traffic_gb", "rrc_max", "high_load", "mr_weak_pct", "access_rate", "drop_rate", "util_peak")
MR_PROFILE_KEYS = ("mr_total", "mr_good_cnt", "mr_cover_pct", "unicom_cov", "telecom_cov", "weak_cell", "worse_unicom", "worse_telecom")
WEEK_TABLE = "appdbv3.a_overview_ispm_lte_cell_w"
@@ -44,9 +56,11 @@ class MetricError(Exception):
class GongcanSource(Protocol):
def before_day(self, city: str, target: Target, removal: date) -> date: ...
def before_day(self, city: str, target: Target, removal: date, today: date) -> date:
"""拆除前工参的日期。里面必须有目标,找不到时抛 GongcanMissing。"""
def after_pick(self, city: str, target: Target, removal: date, today: date) -> AfterPick | None: ...
def after_pick(self, city: str, target: Target, removal: date, today: date) -> AfterPick | None:
"""拆除后工参的日期,以及目标是否还在里面;还没有这份工参时返回 None。"""
def cells(self, city: str, day: date) -> list[dict]: ...
@@ -123,11 +137,16 @@ class StoreGongcan:
finally:
await client.aclose()
def before_day(self, city: str, target: Target, removal: date) -> date:
return asyncio.run(pick_before(self.store, city, target, removal))
def before_day(self, city: str, target: Target, removal: date, today: date) -> date:
return asyncio.run(pick_before(self.store, city, target, removal, today))
def after_pick(self, city: str, target: Target, removal: date, today: date) -> AfterPick | None:
return asyncio.run(pick_after(self.store, city, target, removal, today))
"""拆除后工参取不到不算失败,周边站改用拆除前工参。"""
try:
return asyncio.run(pick_after(self.store, city, target, removal, today))
except GongcanError as exc:
logger.info("%s 拆除后工参没取到,改用拆除前工参:%s", city, exc)
return None
def cells(self, city: str, day: date) -> list[dict]:
return self.store.cells(city, day)
@@ -143,23 +162,23 @@ def _between(low: float, high: float, *parts: object) -> float:
class MockGongcan:
"""演示用工参:待拆小区放在一处,周围散布模拟站点,拆除前取上个月 1 号、拆除后取昨天。"""
"""演示用工参:待拆小区放在一处,周围散布模拟站点。日期和实际规则一样取周一。"""
SITES = 24
def __init__(self):
self.targets: dict[str, str] = {}
def before_day(self, city: str, target: Target, removal: date) -> date:
def before_day(self, city: str, target: Target, removal: date, today: date) -> date:
for cgi in target.cgis:
self.targets.setdefault(cgi, target.site)
if target.site:
self.targets.setdefault(f"site:{target.site}", target.site)
return month_start(removal, -1)
return before_monday(removal, today)
def after_pick(self, city: str, target: Target, removal: date, today: date) -> AfterPick | None:
yesterday = today - timedelta(days=1)
return None if yesterday <= removal else AfterPick(yesterday, False)
day = after_monday(removal, today)
return None if day is None else AfterPick(day, True)
def cells(self, city: str, day: date) -> list[dict]:
seed = sorted(self.targets)[0] if self.targets else city
+41 -21
View File
@@ -23,6 +23,7 @@ from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from dataclasses import dataclass, field
from datetime import date
from urllib.parse import urlsplit
import httpx
@@ -33,6 +34,7 @@ logger = logging.getLogger("decom")
OPENCODE = f"{ORIGIN}/pro-opencode"
PROVISION_PID = "LXWXYWGZT"
PROVISION_WAIT = 150.0
WORKSPACE = "/workspace"
TASKS_DIR = "tasks"
MODEL_ID = "DeepSeek-V4-Flash-0731-w8a8"
@@ -267,38 +269,56 @@ def ascending_id(prefix: str) -> str:
class OpenCode:
def __init__(self, nqi: NqiClient, *, model: str = MODEL_ID, poll_seconds: float = 3.0):
def __init__(self, nqi: NqiClient, *, model: str = MODEL_ID, poll_seconds: float = 3.0, provision_wait: float = PROVISION_WAIT):
self.nqi = nqi
self.model = model
self.poll_seconds = poll_seconds
self.provision_wait = provision_wait
self.ticket = nqi.ticket()
self.base = ""
self.headers = {"Accept": "*/*", "Origin": ORIGIN, "x-opencode-directory": "%2Fworkspace"}
async def provision(self) -> str:
"""provision 会下发 opencode_route,会话页会下发 oc_castgc,之后接口才认。"""
"""打开账号的 AI 工作区。provision 会下发 opencode_route,会话页会下发 oc_castgc,之后接口才认。
工作区没开过或被平台收回时,provision 返回的是 200 的页面而不是跳转,平台这时才开始准备工作区;
所以没跳转就隔几秒再请求,直到跳转或超过 provision_wait。跳转到哪个目录都行,后面的接口一律指定 /workspace。
"""
if not self.ticket:
raise NqiAuthError("登录已失效,请重新登录")
page = {"Accept": "text/html,application/xhtml+xml,*/*;q=0.8", "Referer": f"{ORIGIN}/pro-portal/struts/portal/index.html"}
response = await self.nqi._request(
"GET",
f"{OPENCODE}/api/provision",
params={"random": str(random.random()), "__PID": PROVISION_PID, "token": self.ticket},
headers=page,
follow_redirects=False,
)
location = response.headers.get("location", "")
if "/cas/login" in location:
raise NqiAuthError("登录已失效,请重新登录")
found = re.match(r"^/pro-opencode/([^/]+)/", location)
if response.status_code not in (301, 302, 303, 307, 308) or not found:
raise OpenCodeError("没有打开大数据平台的 AI 工作区")
self.base = f"{OPENCODE}/{found.group(1)}"
self.headers["Referer"] = f"{self.base}/L3dvcmtzcGFjZQ/session"
response = await self.nqi._request("GET", f"{ORIGIN}{location}", headers=page, follow_redirects=False)
if response.status_code != 200:
raise OpenCodeError("没有打开大数据平台的 AI 工作区")
return found.group(1)
deadline = time.monotonic() + self.provision_wait
seen = ""
while True:
response = await self.nqi._request(
"GET",
f"{OPENCODE}/api/provision",
params={"random": str(random.random()), "__PID": PROVISION_PID, "token": self.ticket},
headers=page,
follow_redirects=False,
)
location = response.headers.get("location", "")
if "/cas/login" in location:
raise NqiAuthError("登录已失效,请重新登录")
target = urlsplit(location)
found = re.match(r"^/pro-opencode/([^/]+)/", target.path)
if response.status_code in (301, 302, 303, 307, 308) and found and found.group(1) != "api":
opened = await self.nqi._request(
"GET", f"{ORIGIN}{target.path}" + (f"?{target.query}" if target.query else ""), headers=page, follow_redirects=False
)
if opened.status_code == 200:
self.base = f"{OPENCODE}/{found.group(1)}"
self.headers["Referer"] = f"{self.base}/L3dvcmtzcGFjZQ/session"
return found.group(1)
state = f"工作区页面返回 {opened.status_code}"
else:
state = f"开通接口返回 {response.status_code},没有跳转到工作区"
if state != seen:
seen = state
logger.info("OpenCode 工作区还没就绪:%s", state)
if time.monotonic() >= deadline:
raise OpenCodeError(f"平台没有为这个账号打开 AI 工作区({state})")
await asyncio.sleep(self.poll_seconds)
async def _call(self, method: str, path: str, *, params: dict | None = None, body: dict | None = None, tickets: bool = True) -> httpx.Response:
if not self.base:
+23 -1
View File
@@ -8,8 +8,10 @@ import threading
import time
from app.collect.accounts import reset_active_tasks
from app.collect.gongcan import release_loading
from app.collect.gongcan_sync import request_missing
from app.config import installed
from app.db import session_scope
from app.db import engine, session_scope
from app.tasks.runner import refresh_accounts, scan_sources
logger = logging.getLogger("decom")
@@ -25,8 +27,15 @@ def start_background() -> None:
reset_active_tasks()
except Exception as exc:
logger.info("重置账号占用未完成: %s", exc)
try:
released = release_loading(engine())
if released:
logger.info("上次没取完的工参快照 %s 份,已放开重取", released)
except Exception as exc:
logger.info("放开没取完的工参快照未完成: %s", exc)
threading.Thread(target=_refresh_loop, name="decom-refresh", daemon=True).start()
threading.Thread(target=_collect_loop, name="decom-collect", daemon=True).start()
threading.Thread(target=_gongcan_loop, name="decom-gongcan", daemon=True).start()
def _refresh_loop() -> None:
@@ -58,3 +67,16 @@ def _collect_loop() -> None:
except Exception as exc:
logger.info("采集调度未完成: %s", exc)
time.sleep(60)
def _gongcan_loop() -> None:
"""工参每周一一份。新的一周到了、或者之前没补完,就排补取任务。"""
while True:
if not installed():
time.sleep(2)
continue
try:
request_missing()
except Exception as exc:
logger.info("工参缓存检查未完成: %s", exc)
time.sleep(600)
+18 -3
View File
@@ -5,10 +5,12 @@ from __future__ import annotations
import asyncio
import contextlib
import logging
import threading
import procrastinate
from procrastinate.worker import Worker
from app.collect.gongcan_sync import execute_sync
from app.config import postgres_conninfo
from app.evaluate.runner import execute_task, finalize_job
from app.tasks.runner import current_concurrency, execute_collection
@@ -18,6 +20,7 @@ logger = logging.getLogger("decom")
conninfo = postgres_conninfo() or "postgresql://invalid"
queue = procrastinate.App(connector=procrastinate.PsycopgConnector(conninfo=conninfo))
defer_queue = procrastinate.App(connector=procrastinate.PsycopgConnector(conninfo=conninfo))
_defer_lock = threading.Lock()
@queue.task(name="decom_eval_task", queue="decom")
@@ -35,11 +38,23 @@ def decom_collect(source_id: int, force: bool = False) -> None:
execute_collection(source_id, force=force)
def defer(name: str, **kwargs) -> None:
@queue.task(name="decom_gongcan_sync", queue="decom")
def decom_gongcan_sync(city: str) -> None:
execute_sync(city)
def defer(name: str, *, queueing_lock: str | None = None, **kwargs) -> bool:
"""排一个任务。queueing_lock 相同的任务已有一个在排队时不再排,返回 False。"""
# API 和 worker 是两个进程;worker 自己还会从后台线程提交采集任务。
# 使用独立的同步连接,避免与 worker 持有的异步连接互相关闭。
with defer_queue.open():
defer_queue.configure_task(name, queue="decom").defer(**kwargs)
# 几个线程会同时来排任务;连接池由先到的打开、退出时关闭,不加锁后到的会用到已关闭的池。
options = {"queueing_lock": queueing_lock} if queueing_lock else {}
with _defer_lock, defer_queue.open():
try:
defer_queue.configure_task(name, queue="decom", **options).defer(**kwargs)
except procrastinate.exceptions.AlreadyEnqueued:
return False
return True
class DynamicGate: