feat: 工参每周一一份并提前缓存,登录后自动补缺;评估按周一取工参,指标等平台同步三天后再查
- 工参从 2024-01-01 起每周一一份,排队任务一次补一份,新的周先补;一个地市同时只取一份 - 大数据平台账号登录成功后排补取,排队进程每 10 分钟检查缺的周;排队进程重启时放开没取完的快照 - 拆除前工参用拆除日上一周的周一,拆除后用当周的周一;待拆小区不参与周边站和指标匹配 - 一周的指标等周日过后第 3 天才查,没到时间在结果说明里写明哪天之后有数据 - AI 工作区没就绪时开通接口返回 200,改为等待重试,最多 150 秒 - 排任务加锁,避免多个线程同时排时用到已关闭的连接池 - 运行面板显示各地市工参缓存进度
This commit is contained in:
+1
-1
@@ -20,7 +20,7 @@ Vue 3、TypeScript、Naive UI。Node.js 只用于安装依赖、本地开发和
|
||||
|
||||
## Positioning
|
||||
|
||||
工参按地市、日期存成快照。评估先用库里的快照,缺的日期用提交人的大数据平台凭证实时补取。4G 小区的流量、质量和扇区按拆除前一周和拆除当周从即席查询周表取实际数据;MR、竞对和 5G 小区的指标仍为模拟数据。
|
||||
工参按地市存成每周一一份的快照,从 2024 年起提前缓存,有人用大数据平台账号登录后自动补缺。评估先用库里的快照,缺的那一份用提交人的大数据平台凭证实时补取。4G 小区的流量、质量和扇区按拆除前一周和拆除当周从即席查询周表取实际数据;MR、竞对和 5G 小区的指标仍为模拟数据。
|
||||
|
||||
## Operating Context
|
||||
|
||||
|
||||
@@ -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
@@ -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:
|
||||
|
||||
@@ -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
@@ -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:
|
||||
|
||||
@@ -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"])
|
||||
@@ -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]] = {}
|
||||
|
||||
@@ -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:
|
||||
"""拆除后工参取不到不算失败,周边站改用拆除前工参。"""
|
||||
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
|
||||
|
||||
@@ -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,19 +269,27 @@ 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"}
|
||||
deadline = time.monotonic() + self.provision_wait
|
||||
seen = ""
|
||||
while True:
|
||||
response = await self.nqi._request(
|
||||
"GET",
|
||||
f"{OPENCODE}/api/provision",
|
||||
@@ -290,15 +300,25 @@ class OpenCode:
|
||||
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 工作区")
|
||||
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"
|
||||
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)
|
||||
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
@@ -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)
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -91,6 +91,9 @@ def test_frequency_rules_and_windows():
|
||||
assert before == (date(2026, 10, 5), date(2026, 10, 11))
|
||||
assert after == (date(2026, 10, 12), date(2026, 10, 18))
|
||||
assert windows(date(2026, 11, 10), TODAY)[1] is None
|
||||
# 平台数据约三天同步好:11-02 这一周周日是 11-08,到 11-11 才能查。
|
||||
assert windows(date(2026, 11, 4), TODAY)[1] == (date(2026, 11, 2), date(2026, 11, 8))
|
||||
assert windows(date(2026, 11, 4), date(2026, 11, 10))[1] is None
|
||||
|
||||
|
||||
class _WeekStub:
|
||||
@@ -152,30 +155,50 @@ def test_evaluate_site_finds_neighbors_and_sectors_with_mock_sources():
|
||||
group = groups[0]
|
||||
stages: list[str] = []
|
||||
payload = evaluate_site(group, "江门", TODAY, MockGongcan(), MockMetrics(), stage=stages.append)
|
||||
assert payload["beforeDay"] == "2026-09-01" and payload["afterDay"] == "2026-11-10"
|
||||
# 拆除前工参是拆除日上一周的周一,拆除后工参是拆除日当周的周一。
|
||||
assert payload["beforeDay"] == "2026-10-05" and payload["afterDay"] == "2026-10-12" and payload["afterPresent"] is True
|
||||
assert len(payload["neighbors"]) == 3 and payload["locatable"]
|
||||
assert all(item["site"] != "模拟待拆站点" for item in payload["item2"])
|
||||
assert not {"460-00-5001-1", "460-00-5001-2"} & {item["cgi"] for item in payload["item2"]}
|
||||
assert all(item["before"] and item["after"] for item in payload["item2"])
|
||||
techs = [item["tech"] for item in payload["item2"] if item["site"] == payload["neighbors"][0]["site"]]
|
||||
assert techs == sorted(techs, key=lambda tech: tech != "4G")
|
||||
assert payload["rows"][1]["cellName"] == "模拟待拆站点-2"
|
||||
assert stages[0] == "确定拆除前工参" and stages[-1] == "完成"
|
||||
|
||||
low = SiteGroup(key="低效站", kind="dixiao", order_type="低效拆除", removal=date(2026, 12, 20), rows=[demand("460-00-6001-1", "低效站E-ZLW-1", "低效拆除", date(2026, 12, 20))])
|
||||
result = evaluate_site(low, "江门", TODAY, MockGongcan(), MockMetrics())
|
||||
assert result["afterDay"] is None and "拆除当周还没结束,没有停闭后的指标" in result["notes"]
|
||||
assert len(result["section1"]) == 1 and result["section1"][0]["站点类型"] == "室分"
|
||||
assert result["sectors"] and result["sectors"][0]["base"] >= 1
|
||||
assert all(item["after"] == {} for item in result["item2"])
|
||||
|
||||
def low_site(when: date) -> SiteGroup:
|
||||
return SiteGroup(key="低效站", kind="dixiao", order_type="低效拆除", removal=when, rows=[demand("460-00-6001-1", "低效站E-ZLW-1", "低效拆除", when)])
|
||||
|
||||
|
||||
def test_evaluate_site_waits_for_weeks_the_platform_has_not_synced():
|
||||
done = evaluate_site(low_site(date(2026, 10, 15)), "江门", TODAY, MockGongcan(), MockMetrics())
|
||||
assert done["windows"]["after"] == ["2026-10-12", "2026-10-18"] and not any("同步好" in note for note in done["notes"])
|
||||
assert len(done["section1"]) == 1 and done["section1"][0]["站点类型"] == "室分" and done["section1"][0]["扇区名称"]
|
||||
assert done["sectors"] and done["sectors"][0]["base"] >= 1
|
||||
|
||||
# 拆除日在本周:上一周的数据今天刚同步好,当周的要等到 11-18。
|
||||
this_week = evaluate_site(low_site(date(2026, 11, 10)), "江门", TODAY, MockGongcan(), MockMetrics())
|
||||
assert this_week["beforeDay"] == "2026-11-02" and this_week["afterDay"] is None and this_week["windows"]["after"] is None
|
||||
assert any("2026-11-09 至 2026-11-15" in note and "2026-11-18" in note for note in this_week["notes"])
|
||||
assert this_week["sectors"] and all(item["before"] and item["after"] == {} for item in this_week["item2"])
|
||||
|
||||
# 拆除日还远:上一周的数据也没有,不去查,结果里说明哪天之后再评估。
|
||||
later = evaluate_site(low_site(date(2026, 12, 20)), "江门", TODAY, MockGongcan(), MockMetrics())
|
||||
assert later["beforeDay"] == "2026-11-02" and later["afterDay"] is None
|
||||
assert any("2026-12-07 至 2026-12-13" in note and "2026-12-16" in note for note in later["notes"])
|
||||
assert later["sectors"] == [] and later["section1"][0]["扇区名称"] is None
|
||||
assert all(item["before"] == {} and item["after"] == {} for item in later["item2"])
|
||||
|
||||
|
||||
class NoGongcan:
|
||||
def before_day(self, city, target, removal):
|
||||
raise GongcanMissing("拆除前 3 个月的工参里都没有小区 460-00-1-1")
|
||||
def before_day(self, city, target, removal, today):
|
||||
raise GongcanMissing("2026-10-05 及之前 4 周的工参里都没有小区 460-00-1-1")
|
||||
|
||||
|
||||
def test_evaluate_site_fails_when_target_missing_from_gongcan():
|
||||
group = group_rows([demand("460-00-1-1", "x")])[0]
|
||||
with pytest.raises(EvalFailure, match="3 个月"):
|
||||
with pytest.raises(EvalFailure, match="4 周"):
|
||||
evaluate_site(group, "江门", TODAY, NoGongcan(), MockMetrics())
|
||||
|
||||
|
||||
@@ -306,7 +329,7 @@ def test_eval_api_end_to_end(client: TestClient):
|
||||
assert [result["kind"] for result in detail["job"]["results"]] == ["pinduan", "dixiao"]
|
||||
assert detail["job"]["warnings"][0].startswith("模拟数据:")
|
||||
assert [task["status"] for task in detail["tasks"]] == ["done", "done"]
|
||||
assert detail["tasks"][0]["beforeDate"] == "2026-09-01" and len(detail["tasks"][0]["neighbors"]) == 3
|
||||
assert detail["tasks"][0]["beforeDate"] == "2026-10-05" and len(detail["tasks"][0]["neighbors"]) == 3
|
||||
for result in detail["job"]["results"]:
|
||||
downloaded = client.get(f"/api/eval/jobs/{created['id']}/files/{result['kind']}", headers=user)
|
||||
assert downloaded.status_code == 200 and downloaded.content[:2] == b"PK"
|
||||
|
||||
@@ -7,6 +7,7 @@ from sqlalchemy import create_engine
|
||||
|
||||
from app.collect import gongcan
|
||||
from app.collect.gongcan import (
|
||||
HISTORY_START,
|
||||
AfterPick,
|
||||
GongcanError,
|
||||
GongcanMissing,
|
||||
@@ -14,13 +15,16 @@ from app.collect.gongcan import (
|
||||
Target,
|
||||
build_cells,
|
||||
claim_snapshot,
|
||||
expected_mondays,
|
||||
fetch_snapshot,
|
||||
month_start,
|
||||
latest_monday,
|
||||
nearest_sites,
|
||||
pick_after,
|
||||
pick_before,
|
||||
platform_files,
|
||||
release_loading,
|
||||
save_snapshot,
|
||||
short_city,
|
||||
snapshot_task_name,
|
||||
target_center,
|
||||
)
|
||||
@@ -84,10 +88,16 @@ def make_store(platform, stored=None, clock=None):
|
||||
return GongcanStore(db, platform, poll_seconds=0.01, clock=clock)
|
||||
|
||||
|
||||
def test_month_start_crosses_year():
|
||||
assert month_start(date(2026, 1, 10), -1) == date(2025, 12, 1)
|
||||
assert month_start(date(2026, 1, 10), -3) == date(2025, 10, 1)
|
||||
assert month_start(date(2026, 11, 30)) == date(2026, 11, 1)
|
||||
def test_snapshots_are_mondays_and_wait_three_days_for_the_platform():
|
||||
# 2026-11-09 是周一,它的工参要到周四 11-12 才取。
|
||||
assert latest_monday(date(2026, 11, 11)) == date(2026, 11, 2)
|
||||
assert latest_monday(date(2026, 11, 12)) == date(2026, 11, 9)
|
||||
assert latest_monday(date(2026, 11, 18)) == date(2026, 11, 9)
|
||||
days = expected_mondays(date(2026, 11, 12))
|
||||
assert days[0] == HISTORY_START == date(2024, 1, 1) and days[-1] == date(2026, 11, 9) and len(days) == 150
|
||||
assert all(day.weekday() == 0 for day in days)
|
||||
assert expected_mondays(date(2024, 1, 3)) == []
|
||||
assert short_city("江门市") == "江门" and short_city("江门分公司") == "江门" and short_city(" 江门 ") == "江门" and short_city("市") == "市"
|
||||
|
||||
|
||||
def test_platform_files_use_make_date_and_keep_commas_out_of_text_columns():
|
||||
@@ -217,67 +227,97 @@ def test_stale_loading_is_taken_over():
|
||||
assert claim_snapshot(store.engine, CITY, date(2026, 11, 1), clock() + timedelta(minutes=41)) is not None
|
||||
|
||||
|
||||
REMOVAL = date(2026, 11, 15)
|
||||
def test_release_loading_frees_snapshots_left_by_a_dead_worker():
|
||||
clock = Clock()
|
||||
store = make_store(Platform({date(2026, 11, 2): with_target()}), {date(2026, 10, 26): with_target()}, clock=clock)
|
||||
assert claim_snapshot(store.engine, CITY, date(2026, 11, 2), clock()) is not None
|
||||
assert store.next_to_fill(CITY, [date(2026, 11, 2)]) is None
|
||||
assert release_loading(store.engine) == 1
|
||||
assert store.next_to_fill(CITY, [date(2026, 11, 2)]) == date(2026, 11, 2)
|
||||
assert store.ready_dates(CITY, date(2026, 10, 1), date(2026, 12, 1)) == [date(2026, 10, 26)]
|
||||
|
||||
|
||||
def test_before_uses_latest_stored_snapshot_with_target():
|
||||
def test_next_to_fill_takes_one_at_a_time_and_backs_off_after_a_failure():
|
||||
clock = Clock()
|
||||
newest_first = [date(2026, 11, 2), date(2026, 10, 26), date(2026, 10, 19)]
|
||||
platform = Platform({date(2026, 10, 26): with_target(), date(2026, 10, 19): with_target()})
|
||||
store = make_store(platform, {date(2026, 10, 19): with_target()}, clock=clock)
|
||||
assert store.missing_dates(CITY, newest_first) == [date(2026, 11, 2), date(2026, 10, 26)]
|
||||
assert store.missing_dates(CITY, []) == []
|
||||
assert store.next_to_fill(CITY, newest_first) == date(2026, 11, 2)
|
||||
with pytest.raises(GongcanError):
|
||||
asyncio.run(store.fill(CITY, date(2026, 11, 2)))
|
||||
# 刚失败:冷却期内整个地市都不再取。
|
||||
assert store.next_to_fill(CITY, newest_first) is None
|
||||
clock.now += timedelta(minutes=11)
|
||||
# 冷却过后先补没失败过的,失败过的排到最后。
|
||||
assert store.next_to_fill(CITY, newest_first) == date(2026, 10, 26)
|
||||
assert asyncio.run(store.fill(CITY, date(2026, 10, 26))) is True
|
||||
assert store.next_to_fill(CITY, newest_first) == date(2026, 11, 2)
|
||||
assert asyncio.run(store.fill(CITY, date(2026, 10, 26))) is False
|
||||
assert store.next_to_fill(CITY, [date(2026, 10, 26), date(2026, 10, 19)]) is None
|
||||
assert platform.fetched == [date(2026, 11, 2), date(2026, 10, 26)]
|
||||
|
||||
|
||||
# 拆除日 2026-10-15 是周四:上一周的周一是 10-05,当周的周一是 10-12。
|
||||
REMOVAL = date(2026, 10, 15)
|
||||
TODAY = date(2026, 11, 12)
|
||||
|
||||
|
||||
def test_before_is_the_monday_of_the_week_before_removal():
|
||||
platform = Platform({})
|
||||
store = make_store(platform, {date(2026, 9, 1): with_target(), date(2026, 10, 20): with_target(), date(2026, 11, 14): without_target()})
|
||||
assert asyncio.run(pick_before(store, CITY, SITE, REMOVAL)) == date(2026, 10, 20)
|
||||
store = make_store(platform, {date(2026, 9, 28): with_target(), date(2026, 10, 5): with_target(), date(2026, 10, 12): with_target()})
|
||||
assert asyncio.run(pick_before(store, CITY, SITE, REMOVAL, TODAY)) == date(2026, 10, 5)
|
||||
assert platform.fetched == []
|
||||
|
||||
|
||||
def test_before_fetches_previous_month_when_stored_data_is_too_old():
|
||||
platform = Platform({date(2026, 10, 1): with_target()})
|
||||
store = make_store(platform, {date(2026, 7, 1): with_target()})
|
||||
assert asyncio.run(pick_before(store, CITY, SITE, REMOVAL)) == date(2026, 10, 1)
|
||||
assert platform.fetched == [date(2026, 10, 1)]
|
||||
def test_before_fetches_the_monday_when_it_is_not_cached():
|
||||
platform = Platform({date(2026, 10, 5): with_target()})
|
||||
store = make_store(platform, {date(2026, 9, 28): with_target()})
|
||||
assert asyncio.run(pick_before(store, CITY, SITE, REMOVAL, TODAY)) == date(2026, 10, 5)
|
||||
assert platform.fetched == [date(2026, 10, 5)]
|
||||
|
||||
|
||||
def test_before_walks_back_month_by_month():
|
||||
platform = Platform({date(2026, 10, 1): without_target(), date(2026, 9, 1): with_target()})
|
||||
store = make_store(platform)
|
||||
assert asyncio.run(pick_before(store, CITY, SITE, REMOVAL)) == date(2026, 9, 1)
|
||||
assert platform.fetched == [date(2026, 10, 1), date(2026, 9, 1)]
|
||||
def test_before_walks_back_week_by_week_when_target_is_missing():
|
||||
platform = Platform({date(2026, 9, 28): without_target(), date(2026, 9, 21): with_target()})
|
||||
store = make_store(platform, {date(2026, 10, 5): without_target()})
|
||||
assert asyncio.run(pick_before(store, CITY, SITE, REMOVAL, TODAY)) == date(2026, 9, 21)
|
||||
assert platform.fetched == [date(2026, 9, 28), date(2026, 9, 21)]
|
||||
|
||||
|
||||
def test_before_fails_after_three_months_and_skips_stored_months():
|
||||
platform = Platform({date(2026, 9, 1): without_target(), date(2026, 8, 1): without_target()})
|
||||
store = make_store(platform, {date(2026, 10, 1): without_target()})
|
||||
def test_before_fails_after_four_more_weeks():
|
||||
mondays = [date(2026, 10, 5), date(2026, 9, 28), date(2026, 9, 21), date(2026, 9, 14), date(2026, 9, 7)]
|
||||
platform = Platform({})
|
||||
store = make_store(platform, {day: without_target() for day in mondays} | {date(2026, 8, 31): with_target()})
|
||||
with pytest.raises(GongcanMissing, match="站点 T"):
|
||||
asyncio.run(pick_before(store, CITY, SITE, REMOVAL))
|
||||
assert platform.fetched == [date(2026, 9, 1), date(2026, 8, 1)]
|
||||
|
||||
|
||||
AFTER_REMOVAL = date(2026, 11, 1)
|
||||
TODAY = date(2026, 11, 11)
|
||||
|
||||
|
||||
def test_after_prefers_latest_snapshot_without_target():
|
||||
platform = Platform({})
|
||||
stored = {date(2026, 11, 3): without_target(), date(2026, 11, 5): with_target(), date(2026, 11, 8): without_target(), date(2026, 10, 30): without_target()}
|
||||
store = make_store(platform, stored)
|
||||
assert asyncio.run(pick_after(store, CITY, SITE, AFTER_REMOVAL, TODAY)) == AfterPick(date(2026, 11, 8), False)
|
||||
asyncio.run(pick_before(store, CITY, SITE, REMOVAL, TODAY))
|
||||
assert platform.fetched == []
|
||||
|
||||
|
||||
def test_after_uses_yesterday_when_target_is_still_there():
|
||||
def test_before_uses_latest_available_monday_for_a_future_removal():
|
||||
platform = Platform({})
|
||||
store = make_store(platform, {date(2026, 11, 5): with_target(), date(2026, 11, 10): with_target()})
|
||||
assert asyncio.run(pick_after(store, CITY, SITE, AFTER_REMOVAL, TODAY)) == AfterPick(date(2026, 11, 10), True)
|
||||
store = make_store(platform, {date(2026, 11, 9): with_target()})
|
||||
assert asyncio.run(pick_before(store, CITY, SITE, date(2026, 12, 20), TODAY)) == date(2026, 11, 9)
|
||||
with pytest.raises(GongcanMissing, match="太早"):
|
||||
asyncio.run(pick_before(store, CITY, SITE, date(2024, 1, 5), TODAY))
|
||||
assert platform.fetched == []
|
||||
|
||||
|
||||
def test_after_fetches_yesterday_when_stored_data_still_has_target():
|
||||
platform = Platform({date(2026, 11, 10): without_target()})
|
||||
store = make_store(platform, {date(2026, 11, 5): with_target(), date(2026, 10, 1): without_target()})
|
||||
assert asyncio.run(pick_after(store, CITY, SITE, AFTER_REMOVAL, TODAY)) == AfterPick(date(2026, 11, 10), False)
|
||||
assert platform.fetched == [date(2026, 11, 10)]
|
||||
def test_after_is_the_monday_of_the_removal_week_and_target_may_still_be_there():
|
||||
platform = Platform({date(2026, 10, 12): with_target()})
|
||||
store = make_store(platform, {date(2026, 10, 19): without_target()})
|
||||
assert asyncio.run(pick_after(store, CITY, SITE, REMOVAL, TODAY)) == AfterPick(date(2026, 10, 12), True)
|
||||
assert asyncio.run(pick_after(store, CITY, SITE, date(2026, 10, 19), TODAY)) == AfterPick(date(2026, 10, 19), False)
|
||||
assert platform.fetched == [date(2026, 10, 12)]
|
||||
|
||||
|
||||
def test_after_is_empty_until_removal_day_has_passed():
|
||||
def test_after_is_empty_until_that_monday_can_be_fetched():
|
||||
store = make_store(Platform({}))
|
||||
assert asyncio.run(pick_after(store, CITY, SITE, date(2026, 11, 10), TODAY)) is None
|
||||
# 11-09 这个周一 11-12 起可取;11-16 的还不行。
|
||||
assert asyncio.run(pick_after(store, CITY, SITE, date(2026, 11, 10), date(2026, 11, 11))) is None
|
||||
assert asyncio.run(pick_after(store, CITY, SITE, date(2026, 11, 17), TODAY)) is None
|
||||
with pytest.raises(GongcanError, match="平台没有这一天"):
|
||||
asyncio.run(pick_after(store, CITY, SITE, date(2026, 11, 10), TODAY))
|
||||
|
||||
|
||||
def test_target_needs_cgis_or_site():
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
|
||||
from app.collect import gongcan_sync
|
||||
from app.collect.gongcan import GongcanError, GongcanStore, claim_snapshot, save_snapshot
|
||||
from app.models import Base, CellData4G, CellData5G, GongcanSnapshot
|
||||
|
||||
CITY = "江门"
|
||||
TODAY = date(2024, 1, 25) # 可取的周一:01-01、01-08、01-15、01-22
|
||||
CELLS = {
|
||||
"4G": [{"cgi": "c1", "cell_name": "A", "station_name": "S", "latitude": 22.0, "longitude": 113.0}],
|
||||
"5G": [{"ncgi": "n1", "nrcell_name": "N", "station_name": "S", "latitude": 22.0, "longitude": 113.0}],
|
||||
}
|
||||
|
||||
|
||||
class Clock:
|
||||
def __init__(self):
|
||||
self.now = datetime(2024, 1, 25, 2, 0, tzinfo=timezone.utc)
|
||||
|
||||
def __call__(self):
|
||||
return self.now
|
||||
|
||||
|
||||
class Platform:
|
||||
def __init__(self, broken=()):
|
||||
self.broken = set(broken)
|
||||
self.fetched = []
|
||||
|
||||
async def __call__(self, city, day):
|
||||
self.fetched.append(day)
|
||||
if day in self.broken:
|
||||
raise GongcanError("平台出错")
|
||||
return CELLS
|
||||
|
||||
|
||||
def make_store(platform, stored=(), clock=None):
|
||||
db = create_engine("sqlite://")
|
||||
Base.metadata.create_all(db, tables=[GongcanSnapshot.__table__, CellData4G.__table__, CellData5G.__table__])
|
||||
clock = clock or Clock()
|
||||
for day in stored:
|
||||
save_snapshot(db, claim_snapshot(db, CITY, day, clock()), CELLS, clock())
|
||||
return GongcanStore(db, platform, poll_seconds=0.01, clock=clock)
|
||||
|
||||
|
||||
def test_sync_fills_missing_mondays_newest_first_one_per_run():
|
||||
platform = Platform()
|
||||
store = make_store(platform, stored=[date(2024, 1, 15)])
|
||||
runs = [gongcan_sync.sync_once(CITY, today=TODAY, store=store) for _ in range(4)]
|
||||
assert runs == [(date(2024, 1, 22), 2), (date(2024, 1, 8), 1), (date(2024, 1, 1), 0), (None, 0)]
|
||||
assert platform.fetched == [date(2024, 1, 22), date(2024, 1, 8), date(2024, 1, 1)]
|
||||
|
||||
|
||||
def test_sync_stops_while_another_snapshot_is_loading_or_just_failed():
|
||||
clock = Clock()
|
||||
platform = Platform(broken=[date(2024, 1, 22)])
|
||||
store = make_store(platform, clock=clock)
|
||||
# 评估任务正在取 01-08:补取任务不再开第二个。
|
||||
claim_snapshot(store.engine, CITY, date(2024, 1, 8), clock())
|
||||
assert gongcan_sync.sync_once(CITY, today=TODAY, store=store) == (None, 4)
|
||||
save_snapshot(store.engine, 1, CELLS, clock())
|
||||
try:
|
||||
gongcan_sync.sync_once(CITY, today=TODAY, store=store)
|
||||
except GongcanError as exc:
|
||||
assert "平台出错" in str(exc)
|
||||
else:
|
||||
raise AssertionError("失败应当抛出")
|
||||
assert gongcan_sync.sync_once(CITY, today=TODAY, store=store) == (None, 3)
|
||||
clock.now += timedelta(minutes=11)
|
||||
# 冷却后先补别的周,失败过的 01-22 留到最后再试。
|
||||
assert gongcan_sync.sync_once(CITY, today=TODAY, store=store) == (date(2024, 1, 15), 2)
|
||||
assert gongcan_sync.sync_once(CITY, today=TODAY, store=store) == (date(2024, 1, 1), 1)
|
||||
assert platform.fetched == [date(2024, 1, 22), date(2024, 1, 15), date(2024, 1, 1)]
|
||||
|
||||
|
||||
def test_cache_status_counts_mondays_only(monkeypatch):
|
||||
clock = Clock()
|
||||
store = make_store(Platform(broken=[date(2024, 1, 22)]), stored=[date(2024, 1, 8), date(2024, 1, 15), date(2024, 1, 10)], clock=clock)
|
||||
try:
|
||||
gongcan_sync.sync_once(CITY, today=TODAY, store=store)
|
||||
except GongcanError:
|
||||
pass
|
||||
monkeypatch.setattr(gongcan_sync, "engine", lambda: store.engine)
|
||||
assert gongcan_sync.sync_cities() == [CITY]
|
||||
status = gongcan_sync.cache_status(TODAY)
|
||||
assert len(status) == 1
|
||||
item = status[0]
|
||||
assert (item["city"], item["expected"], item["ready"], item["earliest"], item["latest"], item["loading"]) == (CITY, 4, 2, "2024-01-08", "2024-01-15", None)
|
||||
assert item["error"].startswith("2024-01-22 GongcanError: 平台出错") and item["errorAt"]
|
||||
|
||||
|
||||
def test_request_sync_does_nothing_without_a_queue(monkeypatch):
|
||||
monkeypatch.setattr(gongcan_sync, "postgres_conninfo", lambda: None)
|
||||
assert gongcan_sync.request_sync("江门市") is False
|
||||
monkeypatch.setattr(gongcan_sync, "postgres_conninfo", lambda: "postgresql://x")
|
||||
monkeypatch.setenv("DECOM_EVAL_SOURCE", "mock")
|
||||
assert gongcan_sync.request_sync("江门市") is False
|
||||
assert gongcan_sync.request_sync("") is False
|
||||
@@ -180,6 +180,53 @@ def test_export_accepts_empty_result_and_gives_up_after_retries():
|
||||
assert len(never.prompts) == 3
|
||||
|
||||
|
||||
class Reply:
|
||||
def __init__(self, status, location=""):
|
||||
self.status_code = status
|
||||
self.headers = {"location": location} if location else {}
|
||||
|
||||
|
||||
class FakeNqi:
|
||||
"""按顺序回放平台对开通接口和工作区页面的响应。"""
|
||||
|
||||
def __init__(self, replies):
|
||||
self.replies = list(replies)
|
||||
self.urls = []
|
||||
|
||||
def ticket(self):
|
||||
return "ticket"
|
||||
|
||||
async def _request(self, method, url, **kwargs):
|
||||
self.urls.append(url.split("/pro-opencode", 1)[1])
|
||||
return self.replies.pop(0)
|
||||
|
||||
|
||||
def test_provision_waits_until_the_platform_opens_the_workspace():
|
||||
# 工作区没开时开通接口先返回 200 的页面,过一会儿才跳转;跳到别的目录也照样用 /workspace。
|
||||
other_dir = "/pro-opencode/someone/L2hvbWU/session?isApp=1&tickets=x"
|
||||
nqi = FakeNqi([Reply(200), Reply(200), Reply(307, other_dir), Reply(502), Reply(307, f"https://elsewhere.example{other_dir}"), Reply(200)])
|
||||
oc = OpenCode(nqi, poll_seconds=0, provision_wait=5)
|
||||
assert asyncio.run(oc.provision()) == "someone"
|
||||
assert oc.base.endswith("/pro-opencode/someone") and oc.headers["Referer"].endswith("/someone/L3dvcmtzcGFjZQ/session")
|
||||
assert nqi.urls == ["/api/provision", "/api/provision", "/api/provision", "/someone/L2hvbWU/session?isApp=1&tickets=x", "/api/provision", "/someone/L2hvbWU/session?isApp=1&tickets=x"]
|
||||
assert oc.headers["x-opencode-directory"] == "%2Fworkspace"
|
||||
|
||||
|
||||
def test_provision_gives_up_or_reports_expired_login():
|
||||
from app.nqi.client import NqiAuthError
|
||||
|
||||
never = OpenCode(FakeNqi([Reply(200)] * 3), poll_seconds=0, provision_wait=0)
|
||||
with pytest.raises(OpenCodeError, match="开通接口返回 200"):
|
||||
asyncio.run(never.provision())
|
||||
expired = OpenCode(FakeNqi([Reply(302, "https://nqi.gmcc.net:20443/cas/login?service=x")]), poll_seconds=0)
|
||||
with pytest.raises(NqiAuthError):
|
||||
asyncio.run(expired.provision())
|
||||
# 跳转到 /pro-opencode/api/ 下面不是工作区。
|
||||
looping = OpenCode(FakeNqi([Reply(307, "/pro-opencode/api/provision?x=1")]), poll_seconds=0, provision_wait=0)
|
||||
with pytest.raises(OpenCodeError, match="没有跳转到工作区"):
|
||||
asyncio.run(looping.provision())
|
||||
|
||||
|
||||
class FakeSession(OpenCode):
|
||||
def __init__(self, base=""):
|
||||
self.base = base
|
||||
|
||||
+8
-4
@@ -43,11 +43,15 @@
|
||||
|
||||
页面显示的阶段:确定拆除前工参 → 确定拆除后工参 → 定位待拆站点 → 查询停闭前后指标 →(低效拆除)查询扇区指标 → 完成。
|
||||
|
||||
1. **工参日期**:规则见 [评估工参的数据来源](gongcan-source.md)。拆除前取不到时这个站点失败;拆除日还没过就没有拆除后工参。
|
||||
1. **工参日期**:每周一一份。拆除前用拆除日上一周的周一,拆除后用拆除日当周的周一,细则见 [评估工参的数据来源](gongcan-source.md)。
|
||||
拆除前取不到时这个站点失败;拆除后那一份还取不到时没有拆除后工参。
|
||||
2. **定位**:在拆除前工参里找目标小区(按小区)或站点名(按站点)。清单没写小区名的从工参补上;部分 CGI 不在工参里只记说明。
|
||||
3. **周边站**:离待拆小区中心最近的 3 个物理站,用拆除后工参(没有就用拆除前的)。排除待拆站本身、室分(小区名含 `W-`)、NB-IoT、
|
||||
3. **周边站**:离待拆小区中心最近的 3 个物理站,用拆除后工参(没有就用拆除前的)。排除待拆小区和待拆站本身、室分(小区名含 `W-`)、NB-IoT、
|
||||
名称含「微小」的小区。站内 4G 在前、再按小区名排。待拆小区没有经纬度时算不了周边站,结果表第 1 部分标红。
|
||||
4. **时间段**:停闭前是拆除日所在周的上一周(周一到周日),停闭后是拆除日所在的那一周。拆除当周的周日还没过,就没有停闭后,结果表判断列显示「拆除后再评估」。
|
||||
4. **时间段**:停闭前是拆除日所在周的上一周(周一到周日),停闭后是拆除日所在的那一周。
|
||||
平台数据约三天同步好,一周的指标要等周日过后第 3 天(周三)才查,没到时间不查:
|
||||
- 停闭后那一周还没到时间:没有停闭后,结果表判断列显示「拆除后再评估」,结果说明里写明哪天之后有数据。
|
||||
- 停闭前那一周也没到时间(拆除日在本周头两天或以后):停闭前后都不查,结果说明里写明哪天之后再评估。
|
||||
5. **低效拆除另算两节**:第 1 节用停闭前那一周的小区属性;第 2 节按共站同覆盖区域(扇区)汇总除待拆小区外的其余小区,停闭后覆盖率用拆除当周。
|
||||
- 等效 20M 载波数:TDD 为带宽/20;FDD1800、FDD900 为带宽/20×1.5;使用频段含 3D-MIMO 固定 2.5;5G 不算(填「/」)。
|
||||
- 频点 E1 记作 E,F1、F2、FDD1800、FDD900、3D-MIMO 原样。
|
||||
@@ -71,7 +75,7 @@
|
||||
|
||||
| 数据 | 现在 |
|
||||
| --- | --- |
|
||||
| 工参 | 实际数据:本系统的工参快照;库里没有的日期用提交人的大数据平台凭证经 OpenCode 补取,自有账号用户借号池里的账号 |
|
||||
| 工参 | 实际数据:本系统的工参快照,每周一一份,从 2024-01-01 起提前缓存;库里还没有的周一用提交人的大数据平台凭证经 OpenCode 补取,自有账号用户借号池里的账号 |
|
||||
| 4G 周指标 | 即席查询「[管理视图]重要场景-小区周粒度」(`appdbv3.a_overview_ispm_lte_cell_w`)。按 CGI 或扇区名分批查询,一次覆盖拆除前一周或拆除当周 |
|
||||
| MR、竞对、5G | 仍是模拟数据。结果说明以「模拟数据:」开头 |
|
||||
|
||||
|
||||
+45
-10
@@ -1,7 +1,7 @@
|
||||
# 评估工参的数据来源
|
||||
|
||||
退服评估要用拆除前、拆除后的 4G/5G 小区工参(含经纬度)。工参由 OpenCode 导出;除工参外的其他数据(话务、流量等)都走即席查询。
|
||||
工参按“地市 + 日期”整份存进本系统的 PostgreSQL,任务先查库,库里没有才去大数据平台取。
|
||||
工参按“地市 + 日期”整份存进本系统的 PostgreSQL,只存每周一的,从 2024-01-01 起提前缓存;评估按周一取用,库里没有才去大数据平台取。
|
||||
|
||||
代码位置:
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
| --- | --- |
|
||||
| OpenCode 接口、提示词、导出核对 | `backend/app/nqi/opencode.py` |
|
||||
| 快照合并、入库、日期规则、邻站 | `backend/app/collect/gongcan.py` |
|
||||
| 按周提前缓存 | `backend/app/collect/gongcan_sync.py`,排队任务 `decom_gongcan_sync` |
|
||||
| 表结构 | `backend/app/models.py` 的 `GongcanSnapshot`、`CellData4G`、`CellData5G`,迁移 `0007`–`0009` |
|
||||
|
||||
## 一份快照怎么来
|
||||
@@ -61,25 +62,52 @@
|
||||
不要删 `status = 'loading'` 的行,那是正在取数的快照。
|
||||
- 实测江门两份快照(约 12.3 万个小区)占 52 MB,其中索引 13 MB,即每份约 26 MB。
|
||||
|
||||
## 每周一一份,提前缓存
|
||||
|
||||
平台数据约三天同步好(`SYNC_LAG_DAYS = 3`),所以“现在能取的最新周一”是三天前所在那一周的周一:周一的工参到周四才取。
|
||||
每个地市应有的快照是 2024-01-01(`HISTORY_START`,周一)到这个最新周一之间的每个周一。
|
||||
|
||||
- **谁来取**:排队任务 `decom_gongcan_sync(地市)`。一次只取一份,取完还缺就再排一次,评估任务可以插在中间执行。
|
||||
新的周先补,往回补到 2024-01-01。
|
||||
- **什么时候排**:
|
||||
- 有人用大数据平台账号登录成功,排他所在地市的补取。
|
||||
- 排队进程每 10 分钟检查一次:库里已有快照的地市还缺周一、号池里有有效凭证,就排。新的一周到了也靠这一步补上。
|
||||
- 几周没人登录、凭证都失效时不取;之后有人登录,从库里缺的那一周接着补。
|
||||
- **不重复取**:
|
||||
- 排队里同一个地市只留一个补取任务(`queueing_lock`),再登录多少人也不会多排。
|
||||
- 一个地市有快照正在取时,补取任务直接结束,不开第二个 OpenCode 会话。
|
||||
- 同一份快照靠 `gongcan_snapshot` 的 `loading` 行只取一次,评估任务碰上同一天会等它取完。
|
||||
- **用哪个账号**:号池里有效的账号,先用本地市的;取数时发现凭证失效就标记失效、换下一个,都不行就停下。
|
||||
- **失败**:一份取失败后这个地市 10 分钟内不再取。之后先补别的周,失败过的那一周排到最后再试。
|
||||
- **排队进程重启**:启动时把上次没取完的 `loading` 行删掉,马上可以重取。
|
||||
- **看进度**:管理后台“运行面板”的“工参缓存”,每个地市已缓存几周、范围、正在取哪一天或上次为什么没取成。
|
||||
|
||||
实测(2026-11-12,江门):平台工参表的历史从 2021-12-30 起,4G 历史版本 1165 万行、5G 518 万行,整表导不出来,
|
||||
只能按天取当天有效的记录。2024-01-01 那一份 4G 46,225 个、5G 18,551 个小区,69 秒。
|
||||
到 2026-11-09 共 150 个周一,补完约 3–3.5 小时,库里约 4 GB。
|
||||
|
||||
库里以前按“上月 1 号”“昨天”取的非周一快照不再使用,也不会自动删除。
|
||||
|
||||
## 拆除前后用哪天的工参
|
||||
|
||||
目标是一个或几个 CGI(4G 对 `cgi`、5G 对 `ncgi`,任一存在即算在),或者一个站点名(按 `station_name` 匹配)。“今天”按北京时间。
|
||||
|
||||
**拆除前**(取不到则该小区/站点的评估任务失败):
|
||||
|
||||
1. 库里“拆除日前 3 个月的 1 号”到“拆除日前一天”之间、包含目标的快照,取最晚的一份。
|
||||
2. 没有就从拆除日上个月 1 号开始逐月往前,最多 3 个月:库里已有这天但不含目标的跳过;库里没有的去平台取,取完含目标就用它。
|
||||
3. 三个月都没有,报 `GongcanMissing`。
|
||||
1. 拆除日上一周的周一。这一天现在还取不到(拆除日在本周或以后)时,用现在能取的最新周一。
|
||||
2. 这份里没有目标,就再往前一周,最多往前 4 周(`BEFORE_LOOKBACK_WEEKS`)。
|
||||
3. 都没有,报 `GongcanMissing`。拆除日早于 2024-01-08 的直接报“太早”。
|
||||
|
||||
例:拆除日 11-15,库里范围是 08-01 到 11-14;平台取数顺序 10-01、09-01、08-01。
|
||||
**拆除后**(取不到不算失败):
|
||||
|
||||
**拆除后**(不报错,越接近今天越好):
|
||||
1. 拆除日当周的周一。这一天现在还取不到时没有拆除后工参。
|
||||
2. 这一天通常还在拆除日之前,待拆小区仍在工参里是正常的,只记 `target_present`,页面不提示。
|
||||
算周边站和取指标时会把待拆小区去掉。
|
||||
3. 平台取不到这一份时,周边站改用拆除前工参,结果说明里写明。
|
||||
|
||||
1. 拆除日已经是昨天或之后:没有拆除后的工参,返回空。
|
||||
2. 库里拆除日之后、目标已不在的快照,取最晚的一份。
|
||||
3. 都还有目标时,最晚那份是昨天就直接用;不是就从平台取昨天的。目标仍在只标记 `target_present=True`。
|
||||
用到的周一库里没有时,评估任务自己去平台取这一份并入库。
|
||||
|
||||
注意第 2 步可能选到较早的快照,例如拆除后第三天的快照里目标已不在,而之后没再入过库,就会用那份。
|
||||
例:拆除日 2026-10-15(周四),拆除前用 10-05,拆除后用 10-12。
|
||||
|
||||
## OpenCode 接口
|
||||
|
||||
@@ -88,6 +116,11 @@
|
||||
1. 开通:`GET /pro-opencode/api/provision?random=<随机数>&__PID=LXWXYWGZT&token=<CASTGC>`,返回 307 到
|
||||
`/pro-opencode/<用户>/L3dvcmtzcGFjZQ/session?...`;再 GET 这个地址,服务端种下 `oc_castgc`。
|
||||
之后接口前缀是 `/pro-opencode/<用户>/`。
|
||||
- 账号的工作区没开过、或被平台收回时,这个接口返回的是 200 的页面而不是 307(2026-11-12 生产上遇到一次,
|
||||
几分钟后再请求就正常跳转)。程序每 3 秒重新请求一次,最多等 150 秒(`PROVISION_WAIT`),还不跳转才报
|
||||
“平台没有为这个账号打开 AI 工作区”。那个 200 页面的内容还没抓到,是否只靠重复请求就能把工作区拉起来没有验证。
|
||||
- 跳转地址里 `L3dvcmtzcGFjZQ` 是目录 `/workspace` 的 base64。账号上次打开的是别的目录时会跳到别的目录,
|
||||
程序不依赖它:后面的接口都用 `directory=/workspace` 和 `x-opencode-directory` 指定 `/workspace`。
|
||||
2. 除 `file/content` 外的请求都带查询参数 `tickets=<CASTGC>`,头 `x-opencode-directory: %2Fworkspace`。
|
||||
3. 用到的接口:`session`(建、查、删)、`session/<id>/prompt_async`、`session/status`、`session/<id>/message`、
|
||||
`permission`、`question`、`file`、`file/content`、`global/health`。
|
||||
@@ -157,3 +190,5 @@ python script/download-file-all-async.py --sql "select cgi, longitude, latitude,
|
||||
|
||||
- OpenCode 弹出权限确认(`permission`)或提问(`question`)时的处理。
|
||||
- 会话异常后换新会话重试。
|
||||
- 从没打开过 AI 工作区的账号能不能靠开通接口自动打开;一个账号开了多个工作区时接口是否都正常。目前只有一个账号的数据。
|
||||
- 一个地市的账号能不能取别的地市的工参。
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { computed, onMounted, onUnmounted, ref } from "vue";
|
||||
import type { EChartsCoreOption } from "echarts/core";
|
||||
import Shell from "../../shell/Shell.vue";
|
||||
import { api } from "../../shared/http";
|
||||
@@ -44,9 +44,34 @@ function readPool(result: unknown): PoolDash | null {
|
||||
};
|
||||
}
|
||||
|
||||
interface GongcanCache {
|
||||
city: string;
|
||||
expected: number;
|
||||
ready: number;
|
||||
earliest: string | null;
|
||||
latest: string | null;
|
||||
loading: string | null;
|
||||
error: string;
|
||||
errorAt: string | null;
|
||||
}
|
||||
|
||||
function readGongcan(result: unknown): GongcanCache[] {
|
||||
const list = (result as { gongcan?: unknown } | null)?.gongcan;
|
||||
return Array.isArray(list) ? (list as GongcanCache[]) : [];
|
||||
}
|
||||
|
||||
function cacheState(item: GongcanCache) {
|
||||
if (item.loading) return `正在取 ${item.loading}`;
|
||||
if (item.ready >= item.expected) return "已是最新";
|
||||
if (item.error) return `上次没取成:${item.error}`;
|
||||
return `还缺 ${item.expected - item.ready} 周,有有效凭证时自动补`;
|
||||
}
|
||||
|
||||
const toast = useToast();
|
||||
const loaded = ref(false);
|
||||
const accountPool = ref<PoolDash>(emptyPool());
|
||||
const gongcan = ref<GongcanCache[]>([]);
|
||||
let timer = 0;
|
||||
const stats = computed(() => accountPool.value ?? emptyPool());
|
||||
|
||||
const cards = computed(() => [
|
||||
@@ -124,18 +149,27 @@ const statusOption = computed<EChartsCoreOption>(() => {
|
||||
};
|
||||
});
|
||||
|
||||
async function load() {
|
||||
async function load(quiet = false) {
|
||||
try {
|
||||
const next = readPool(await api<unknown>("/api/admin/dashboard"));
|
||||
const result = await api<unknown>("/api/admin/dashboard");
|
||||
const next = readPool(result);
|
||||
if (!next) throw new Error("运行面板没有获取到");
|
||||
accountPool.value = next;
|
||||
gongcan.value = readGongcan(result);
|
||||
loaded.value = true;
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "运行面板没有获取到");
|
||||
if (!quiet) toast.error(error instanceof Error ? error.message : "运行面板没有获取到");
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
onMounted(() => {
|
||||
void load();
|
||||
// 工参补取一份要一两分钟,没补完时隔一会儿刷新进度。
|
||||
timer = window.setInterval(() => {
|
||||
if (gongcan.value.some((item) => item.ready < item.expected)) void load(true);
|
||||
}, 30000);
|
||||
});
|
||||
onUnmounted(() => window.clearInterval(timer));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -160,6 +194,24 @@ onMounted(load);
|
||||
<ChartPane :option="statusOption" />
|
||||
</section>
|
||||
</div>
|
||||
<section class="surface table-card dash-cache">
|
||||
<h3>工参缓存</h3>
|
||||
<p class="dash-note">每个地市每周一一份,从 2024-01-01 起。平台数据约三天同步好,周一的工参到周四才取。</p>
|
||||
<p v-if="!gongcan.length" class="admin-status">还没有缓存。有人用大数据平台账号登录后开始取。</p>
|
||||
<table v-else class="admin-table">
|
||||
<thead>
|
||||
<tr><th>地市</th><th>已缓存</th><th>范围</th><th>状态</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="item in gongcan" :key="item.city">
|
||||
<td>{{ item.city }}</td>
|
||||
<td class="num">{{ item.ready }} / {{ item.expected }} 周</td>
|
||||
<td class="num">{{ item.earliest ? `${item.earliest} 至 ${item.latest}` : "—" }}</td>
|
||||
<td :class="{ 'status-bad': !item.loading && item.ready < item.expected && item.error }">{{ cacheState(item) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
</template>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -107,7 +107,7 @@ function taskClass(task: EvalTask) {
|
||||
function windowText(task: EvalTask) {
|
||||
if (!task.windows) return "";
|
||||
const before = `${task.windows.before[0]} 至 ${task.windows.before[1]}`;
|
||||
const after = task.windows.after ? `${task.windows.after[0]} 至 ${task.windows.after[1]}` : "拆除后再取";
|
||||
const after = task.windows.after ? `${task.windows.after[0]} 至 ${task.windows.after[1]}` : "数据还没出";
|
||||
return `停闭前 ${before};停闭后 ${after}`;
|
||||
}
|
||||
</script>
|
||||
@@ -169,10 +169,7 @@ function windowText(task: EvalTask) {
|
||||
<div><dt>拆除前工参</dt><dd>{{ task.beforeDate || "—" }}</dd></div>
|
||||
<div>
|
||||
<dt>拆除后工参</dt>
|
||||
<dd>
|
||||
{{ task.afterDate || (task.status === "done" ? "拆除日还没过" : "—") }}
|
||||
<n-tag v-if="task.afterPresent" size="tiny" :bordered="false" type="warning">小区仍在</n-tag>
|
||||
</dd>
|
||||
<dd>{{ task.afterDate || (task.status === "done" ? "暂无" : "—") }}</dd>
|
||||
</div>
|
||||
<div><dt>小区</dt><dd>{{ task.cells.length }} 个</dd></div>
|
||||
</dl>
|
||||
|
||||
@@ -190,6 +190,24 @@ button, input, select { font: inherit; }
|
||||
font-weight: 650;
|
||||
}
|
||||
.dash-chart { height: 260px; }
|
||||
.dash-cache { margin-top: 12px; }
|
||||
.dash-cache h3 {
|
||||
margin: 0;
|
||||
padding: 16px 16px 4px;
|
||||
font-size: 13px;
|
||||
font-weight: 650;
|
||||
}
|
||||
.dash-cache .dash-note,
|
||||
.dash-cache .admin-status {
|
||||
margin: 0;
|
||||
padding: 0 16px 14px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
.dash-cache .num {
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
@media (max-width: 1100px) {
|
||||
.dash-kpis { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
|
||||
Reference in New Issue
Block a user