edge_hub.py 9.8 KB
"""取数端任务中心:任务落 rsk_sys_edge_tasks,取数端长轮询领取,回传结果唤醒等待方。

* 每个任务只会被领取一次(queued → dispatched 是带条件的 UPDATE),建单任务因此不会重复下发;
* 等待超时:已领取的任务标 unknown(建单时提示"结果未知,请到 DMS 核实,不会重试"),未领取的标 expired;
* 服务重启时,上次遗留的 queued 任务标 expired、dispatched 任务标 unknown;
* 只下发本实例自己创建的任务(两个云端连同一个库时,不会把对方的任务派给自己的取数端);
* 超时按工作量放大:run(..., extra_seconds=) 由调用方按配件数给出。
"""
from __future__ import annotations

import asyncio
import json
import time
import uuid

from . import db, events
from .settings import S


class EdgeError(Exception):
    pass


class EdgeTimeout(EdgeError):
    pass


class EdgeHub:
    def __init__(self) -> None:
        self._new = asyncio.Event()
        self._futures: dict[str, asyncio.Future] = {}
        self._files: dict[str, list[dict]] = {}
        self._batches: dict[str, int] = {}
        self.last_seen: dict[str, float] = {}
        self.versions: dict[str, str] = {}
        self.loop: asyncio.AbstractEventLoop | None = None

    def startup(self) -> None:
        self.loop = asyncio.get_running_loop()
        t = db.tasks_t
        n1 = db.q(db.update(t).where(t.c.status == "queued").values(status="expired", error="服务重启,任务作废")).rowcount
        n2 = db.q(db.update(t).where(t.c.status == "dispatched").values(
            status="unknown", error="服务重启时取数端还没回传结果")).rowcount
        if n1 or n2:
            events.emit(f"服务重启:作废 {n1} 个未领取任务,{n2} 个已领取任务结果未知", "warn", source="edge")

    # ---------------- 状态 ----------------
    def online(self) -> tuple[bool, str, float | None]:
        if not self.last_seen:
            return False, "", None
        eid, ts = max(self.last_seen.items(), key=lambda kv: kv[1])
        age = time.time() - ts
        return age <= float(S.get("edge.offline_seconds")), eid, age

    # ---------------- 云端侧 ----------------
    def submit(self, typ: str, params: dict, run_id: int | None = None) -> str:
        tid = uuid.uuid4().hex
        db.q(db.insert(db.tasks_t).values(id=tid, type=typ, params=db.jdump(params), status="queued", run_id=run_id,
                                          created_at=db.now()))
        self._futures[tid] = self.loop.create_future()
        self._new.set()
        events.emit(f"下发任务 {typ}({tid[:8]})给门店取数端", run_id=run_id, source="edge")
        return tid

    async def wait(self, tid: str, timeout: float, run_id: int | None = None) -> dict:
        fut = self._futures.get(tid)
        try:
            return await asyncio.wait_for(asyncio.shield(fut), timeout)
        except asyncio.TimeoutError:
            t = db.tasks_t
            row = db.one(db.select(t.c.status, t.c.type).where(t.c.id == tid))
            if row and row["status"] == "queued":
                db.q(db.update(t).where(t.c.id == tid, t.c.status == "queued").values(
                    status="expired", error="取数端一直没来领取"))
                raise EdgeTimeout(f"门店取数端 {int(timeout)} 秒内没有领取任务(取数端可能没启动或连不上云端)")
            db.q(db.update(t).where(t.c.id == tid, t.c.status == "dispatched").values(
                status="unknown", error=f"{int(timeout)} 秒内没有回传结果"))
            raise EdgeTimeout(f"取数端已领取任务,但 {int(timeout)} 秒内没有回传结果,执行结果未知")
        finally:
            self._futures.pop(tid, None)

    async def run(self, typ: str, params: dict, run_id: int | None = None, extra_seconds: float = 0) -> dict:
        timeout = float(S.get(f"edge.timeout_{typ}") or 300) + max(0.0, float(extra_seconds or 0))
        res = await self.wait(self.submit(typ, params, run_id), timeout, run_id)
        result = res.get("result") or {}
        if not res["ok"]:
            # 扫描:部分配件查询失败(旧版取数端会把整次标成失败),只要还有查到的配件就照常出补货单
            items = result.get("items") or []
            if typ == "scan" and any(not it.get("error") for it in items):
                bad = [it.get("part_no") for it in items if it.get("error")]
                events.emit(f"{len(bad)} 个配件查询失败({'、'.join(map(str, bad[:10]))}{'…' if len(bad) > 10 else ''}),"
                            f"补货单里标「查询失败」,其余照常", "warn", run_id=run_id, source="edge")
                return result
            raise EdgeError(res.get("error") or "取数端执行失败")
        return result

    # ---------------- 取数端侧 ----------------
    def touch(self, edge_id: str, version: str = "") -> None:
        if edge_id not in self.last_seen or time.time() - self.last_seen[edge_id] > float(S.get("edge.offline_seconds")):
            events.emit(f"门店取数端 {edge_id} 已连接(版本 {version or '?'})", "ok", source="edge")
        self.last_seen[edge_id] = time.time()
        self.versions[edge_id] = version

    async def next_task(self, edge_id: str, wait: float) -> dict | None:
        deadline = time.time() + min(wait, 30)
        t = db.tasks_t
        while True:
            self.touch(edge_id, self.versions.get(edge_id, ""))
            self._new.clear()                 # 先清再查:查询之后新到的任务一定能唤醒下面的 wait
            mine = list(self._futures)
            cands = db.rows(db.select(t).where(t.c.status == "queued", t.c.id.in_(mine))
                            .order_by(t.c.created_at).limit(5)) if mine else []
            for cand in cands:
                n = db.q(db.update(t).where(t.c.id == cand["id"], t.c.status == "queued").values(
                    status="dispatched", edge_id=edge_id, dispatched_at=db.now())).rowcount
                if n == 1:
                    events.emit(f"取数端领取任务 {cand['type']}({cand['id'][:8]})", run_id=cand["run_id"], source="edge")
                    return {"id": cand["id"], "type": cand["type"], "params": json.loads(cand["params"] or "{}")}
            left = deadline - time.time()
            if left <= 0:
                return None
            try:
                await asyncio.wait_for(self._new.wait(), left)
            except asyncio.TimeoutError:
                return None

    def task(self, tid: str) -> dict | None:
        return db.one(db.select(db.tasks_t).where(db.tasks_t.c.id == tid))

    def on_result(self, tid: str, ok: bool, result: dict, error: str, logs: list[str]) -> None:
        row = self.task(tid)
        if not row:
            raise EdgeError("任务不存在")
        run_id = row["run_id"]
        for line in (logs or [])[-80:]:
            lvl = "error" if "[ERROR]" in line else ("warn" if "[WARNING]" in line else "info")
            events.emit(line, lvl, run_id=run_id, source="edge-log")
        if self._files.get(tid):
            result = dict(result or {}, files=self._files.pop(tid))
        if tid in self._batches:
            self._finish_batch(tid, ok, result, error)
        status = "done" if ok else "failed"
        if row["status"] not in ("dispatched",):
            events.emit(f"任务 {tid[:8]} 迟到的结果(当前状态 {row['status']}),已记录", "warn", run_id=run_id, source="edge")
            status = f"late_{status}"
        db.q(db.update(db.tasks_t).where(db.tasks_t.c.id == tid).values(
            status=status, finished_at=db.now(), result=db.jdump(result), error=error or None))
        events.emit(f"任务 {row['type']}({tid[:8]}){'完成' if ok else '失败:' + (error or '')}",
                    "ok" if ok else "error", run_id=run_id, source="edge")
        fut = self._futures.get(tid)
        if fut and not fut.done():
            fut.set_result({"ok": ok, "result": result or {}, "error": error})

    def on_file(self, tid: str, name: str, data: bytes) -> dict:
        if not self.task(tid):
            raise EdgeError("任务不存在")
        safe = "".join(ch for ch in name if ch.isalnum() or ch in "._-")[:60] or "shot.png"
        fname = f"{tid[:12]}_{uuid.uuid4().hex[:6]}_{safe}"
        path = S.data_dir() / "shots"
        path.mkdir(parents=True, exist_ok=True)
        (path / fname).write_bytes(data)
        info = {"name": safe, "file": fname, "url": f"/shots/{fname}", "size": len(data)}
        self._files.setdefault(tid, []).append(info)
        return info

    def on_stock_page(self, tid: str, page: int, total: int, rows: list[dict]) -> None:
        if tid not in self._batches:
            row = self.task(tid)
            if not row or row["type"] != "sync_stock_full":
                raise EdgeError("不是全量库存任务")
            r = db.q(db.insert(db.batches_t).values(task_id=tid, source=str(S.get("business.dms_mode")),
                                                    status="running", api_total=total, started_at=db.now()))
            self._batches[tid] = r.inserted_primary_key[0]
        bid = self._batches[tid]
        db.stock_rows_insert(bid, page, rows)
        cnt = db.q(db.select(db.func.count()).select_from(db.stock_rows_t).where(db.stock_rows_t.c.batch_id == bid)).scalar()
        db.q(db.update(db.batches_t).where(db.batches_t.c.id == bid).values(rows_count=cnt, api_total=total))

    def _finish_batch(self, tid: str, ok: bool, result: dict, error: str) -> None:
        bid = self._batches.pop(tid)
        status = (result or {}).get("status", "success") if ok else "failed"
        msg = error or ";".join((result or {}).get("problems") or []) or "完成"
        db.q(db.update(db.batches_t).where(db.batches_t.c.id == bid).values(
            status=status, message=msg, finished_at=db.now()))


hub = EdgeHub()