代码管理

sync_engine.py

← 返回编辑
"""自动同步引擎:定时拉取在线表格 → 标准化 → 落库 → 通知前端刷新。

为什么需要独立模块
------------------
原实现里没有定时同步:点"抓取"会访问表格,但结果丢弃(只更新状态);
/api/datasets//fetch 需要手工触发。需求是"数据变了卡片自动更新",
所以必须有一个常驻的调度器。

设计要点
--------
1. 后台守护线程 + 时间轮转,不依赖外部 cron(Serverless 环境无 cron)
2. 单个数据集失败不阻塞其它数据集
3. token 复用由 dingtalk_adapter 内部缓存,本模块只管调度
4. 同步成功后写 change_log,配合 SSE 推送前端自动刷新
5. 可通过环境变量 SYNC_INTERVAL_MIN 调整频率,默认 30 分钟;设 0 关闭
"""
import json
import os
import threading
import time
import traceback
from datetime import datetime, timedelta

import requests

from db import get_conn
from normalize import normalize_matrix

# 默认同步间隔(分钟)—— 可在看板配置 dashboard_config.sync_interval_min 覆盖。
# 配了 WPS OAuth 之后探测很便宜(每份文档 1 次请求),默认降到 5 分钟;
# 没凭证时降到 30 分钟,避免刷屏报错。
# 2026-10-27:用户接受「1~2 小时」,默认 120 分钟。
# 抓取在云端只有 13 张表,2 小时一轮完全够,也避免撞 WPS 的下载限额。
DEFAULT_INTERVAL_MIN = int(os.environ.get("SYNC_INTERVAL_MIN", "120"))
# 请求超时(秒)
HTTP_TIMEOUT = int(os.environ.get("SYNC_HTTP_TIMEOUT", "20"))


def _log(msg: str):
    print(f"[自动同步 {datetime.now().strftime('%H:%M:%S')}] {msg}", flush=True)


_files_cache = {"at": 0.0, "files": []}


def _kdocs_ready() -> bool:
    """金山文档开放平台(个人空间)凭证是否齐备。"""
    try:
        import kdocs_cloud
        c = kdocs_cloud.get_creds()
        return bool(c.get("app_id") and c.get("app_key") and c.get("refresh_token"))
    except Exception:
        return False


def _kd_files(ttl: float = 45.0) -> list:
    """个人文档列表(短缓存)。

    9 个数据集共用一份列表:一轮同步只发 1 个列表请求,而不是 9 个。
    列表里带 mtime/fsize,本身就是探针,不需要额外请求。
    """
    import time as _t
    import kdocs_cloud
    if _files_cache["files"] and (_t.time() - _files_cache["at"]) < ttl:
        return _files_cache["files"]
    files = kdocs_cloud.list_files()
    _files_cache["files"] = files
    _files_cache["at"] = _t.time()
    return files


def _fetch_kdocs(ds: dict, files: list) -> dict:
    """下载个人文档 xlsx 并解析(消耗下载额度,只在 mtime 变时调用)。"""
    import kdocs_cloud
    d = kdocs_cloud.fetch_dataset(ds, files)
    note = f"文件 {d.get('fname')} / 工作表 {d.get('sheet')}"
    return {"columns": d["columns"], "rows": d["rows"], "_note": note}


def _wps_ready() -> bool:
    """WPS 云端凭证是否齐备(AppID + AppKey + refresh_token)。"""
    try:
        import wps_cloud
        c = wps_cloud.get_creds()
        return bool(c.get("app_id") and c.get("app_key") and c.get("refresh_token"))
    except Exception:
        return False


_LAST_RUN = {"at": None, "total": 0, "ok": 0, "fail": 0, "skip": 0,
             "errors": []}


def _record_history(conn, ds_id: str, rows: int, cols: int, changed: bool):
    """把每次抓取的结果留成历史(保留最近 90 条)。

    ## 为什么
    之前 datasets 表只存"最新一份",抓坏了、抓空了、源表被清空,都无从回溯。
    云端库是 PostgREST,**不能建表**(写 DDL 会被 WAF 拦),所以历史塞进
    dashboard_config 的 JSON 里 —— 体积可控(每条约 80 字节 × 90 × 13 张 ≈ 90KB)。
    """
    try:
        cfg = _load_cfg(conn)
        h = cfg.get("dataset_history")
        if not isinstance(h, dict):
            h = {}
        seq = h.get(ds_id)
        if not isinstance(seq, list):
            seq = []
        seq.append({"t": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                    "rows": rows, "cols": cols, "changed": bool(changed)})
        h[ds_id] = seq[-90:]
        cfg["dataset_history"] = h
        _save_cfg(conn, cfg)
    except Exception:
        pass


def _record_run(conn, res: dict):
    """记录每轮同步的概览(最近 60 轮),供 /api/sync/scheduler 展示。"""
    global _LAST_RUN
    item = {"t": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "total": res.get("total", 0), "ok": res.get("ok", 0),
            "fail": res.get("fail", 0), "skip": res.get("skip", 0),
            "errors": [str(e)[:120] for e in (res.get("errors") or [])][:6]}
    _LAST_RUN = item
    try:
        cfg = _load_cfg(conn)
        runs = cfg.get("sync_runs")
        if not isinstance(runs, list):
            runs = []
        runs.append(item)
        cfg["sync_runs"] = runs[-60:]
        _save_cfg(conn, cfg)
    except Exception:
        pass


def last_run() -> dict:
    return dict(_LAST_RUN)


def _load_cfg(conn) -> dict:
    try:
        row = conn.execute(
            "SELECT config FROM dashboard_config WHERE id='main'").fetchone()
        return json.loads(row["config"]) if row and row["config"] else {}
    except Exception:
        return {}


def _save_cfg(conn, cfg: dict):
    from datetime import datetime
    conn.execute(
        "INSERT OR REPLACE INTO dashboard_config(id, config, updated_at)"
        " VALUES('main', ?, ?)",
        (json.dumps(cfg, ensure_ascii=False),
         datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
    conn.commit()


def _bump_change_log(conn, resource_type: str, resource_id: str):
    """写变更日志,供 SSE 推送使用。"""
    try:
        conn.execute(
            "INSERT INTO change_log(resource_type, resource_id) VALUES(?,?)",
            (resource_type, resource_id),
        )
        conn.commit()
    except Exception as e:
        print("[自动同步] change_log 写入失败:", e)


# ---------- 各平台拉取 ----------

def _fetch_wps(ds: dict) -> dict:
    """拉取金山文档(云端,OAuth 授权码模式)。

    2026-10-27 补齐实现:原来这里是空壳(直接抛"需接入 OAuth"),
    所以云端自动同步跑了一年也抓不到任何 WPS 数据。
    真正的读表逻辑在 wps_cloud 里(token 续期 / 分页 / 表头提升)。
    """
    import wps_cloud
    d = wps_cloud.fetch_dataset(ds)
    note = f"工作表 {d.get('sheet')}"
    if d.get("pages", 1) > 1:
        note += f"({d['pages']} 页)"
    return {"columns": d["columns"], "rows": d["rows"], "_note": note}


def _fetch_dingtalk(dataset: dict) -> dict:
    """拉取钉钉表格。dataset 需含 platform_token / sheet_name / range。"""
    import dingtalk_adapter

    token = dataset.get("platform_token")
    sheet = dataset.get("sheet_name")
    rng = dataset.get("range") or "Sheet1!A1:Z1000"
    if not token:
        raise RuntimeError("数据集未配置 platform_token(钉钉表格 ID)")
    raw = dingtalk_adapter.fetch_sheet_range(token, rng)
    return normalize_dingtalk_safe(raw)


def normalize_dingtalk_safe(raw: dict) -> dict:
    """钉钉返回值标准化(与 normalize.normalize_dingtalk_sheet 同义,单独包一层便于测试)。"""
    from normalize import normalize_dingtalk_sheet
    return normalize_dingtalk_sheet(raw)


# ---------- 单个数据集同步 ----------

def sync_one(dataset_id: str, conn=None) -> dict:
    """同步单个数据集。返回 {ok, message, rows}。"""
    own_conn = conn is None
    if own_conn:
        conn = get_conn()
    try:
        row = conn.execute(
            "SELECT * FROM datasets WHERE id=?", (dataset_id,)
        ).fetchone()
        if not row:
            return {"ok": False, "message": "数据集不存在"}
        ds = dict(row)

        # auto_sync=0 的数据集不参与自动同步
        if str(ds.get("auto_sync", "1")) in ("0", "False", "false"):
            return {"ok": True, "message": "已跳过(关闭了自动同步)", "skipped": True}

        platform = (ds.get("platform") or "").lower()
        _log(f"同步 [{ds.get('name')}] platform={platform}")

        if platform == "dingtalk":
            normalized = _fetch_dingtalk(ds)
        elif platform in ("wps", "kdocs"):
            # ⚠️ 2026-10-27 改走金山文档开放平台(developer.kdocs.cn)。
            # openapi.wps.cn 那套是 WPS365 企业应用,读个人空间一律 403(已两次实测),
            # 用户的表格在个人账号「我的云文档」里。
            if not _kdocs_ready():
                return {"ok": False, "skipped": True,
                        "message": "个人文档未授权,跳过(完成 /api/oauth/kdocs 授权后自动生效)"}
            import kdocs_cloud
            fp = ""
            try:
                files = _kd_files()
                pr = kdocs_cloud.probe(ds, files)
                if pr.get("matched"):
                    fp = json.dumps(pr["fp"], sort_keys=True, ensure_ascii=False)
                else:
                    return {"ok": False, "skipped": True,
                            "message": "个人文档里没找到匹配的表格,"
                                       "可用 /api/kdocs/mapping 指定 file_token"}
            except Exception as e:
                files = []
                _log(f"  探测失败(将直接尝试抓取):{str(e)[:140]}")
            if fp:
                cfg = _load_cfg(conn)
                if (cfg.get("kdocs_probe") or {}).get(dataset_id) == fp:
                    return {"ok": True, "message": "无变化(跳过下载)",
                            "skipped": True}
                normalized = _fetch_kdocs(ds, files)
                cfg.setdefault("kdocs_probe", {})[dataset_id] = fp
                try:
                    _save_cfg(conn, cfg)
                except Exception:
                    pass
            else:
                normalized = _fetch_kdocs(ds, files)
        else:
            return {"ok": False, "message": f"暂不支持的平台: {platform}"}

        columns = normalized.get("columns") or []
        rows = normalized.get("rows") or []
        if not columns:
            return {"ok": False, "message": "拉取成功但表头为空"}

        prev_rows = json.loads(ds.get("rows") or "[]")
        changed = len(rows) != len(prev_rows)

        conn.execute(
            "UPDATE datasets SET columns=?, rows=?, fetched_at=? WHERE id=?",
            (
                json.dumps(columns, ensure_ascii=False),
                json.dumps(rows, ensure_ascii=False),
                datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                dataset_id,
            ),
        )
        conn.commit()
        _record_history(conn, dataset_id, len(rows), len(columns), changed)
        _bump_change_log(conn, "dataset", dataset_id)
        _log(f"  ✓ 成功 {len(rows)} 行 x {len(columns)} 列({'有变化' if changed else '无变化'})")
        return {"ok": True, "message": f"{len(rows)} 行", "rows": len(rows), "changed": changed}

    except Exception as e:
        _log(f"  ✗ 失败: {e}")
        return {"ok": False, "message": str(e)}
    finally:
        if own_conn:
            conn.close()


def sync_all_once() -> dict:
    """同步所有开启自动同步的数据集。"""
    conn = get_conn()
    try:
        rows = conn.execute(
            "SELECT id, name, auto_sync FROM datasets ORDER BY fetched_at DESC"
        ).fetchall()
        total = len(rows)
        ok = fail = skip = 0
        msgs = []
        for r in rows:
            ds = dict(r)
            if str(ds.get("auto_sync", "1")) in ("0", "False", "false"):
                skip += 1
                continue
            res = sync_one(ds["id"], conn)
            if res.get("ok"):
                ok += 1
                if res.get("skipped"):
                    skip += 1
            else:
                fail += 1
                msgs.append(f"{ds.get('name')}: {res.get('message')}")
        return {"total": total, "ok": ok, "fail": fail, "skip": skip, "errors": msgs}
    finally:
        conn.close()


# ---------- 常驻调度线程 ----------

class SyncScheduler:
    """后台调度器:单例,避免 Flask debug 模式重复启动。"""

    _thread = None
    _stop_event = threading.Event()
    _lock = threading.Lock()

    @classmethod
    def start(cls, interval_min: int = None):
        if interval_min is None:
            interval_min = DEFAULT_INTERVAL_MIN
        if interval_min <= 0:
            _log("自动同步已关闭(SYNC_INTERVAL_MIN=0)")
            return
        with cls._lock:
            if cls._thread and cls._thread.is_alive():
                return
            cls._stop_event.clear()
            cls._thread = threading.Thread(target=cls._loop, args=(interval_min,), daemon=True)
            cls._thread.start()
            _log(f"已启动,间隔 {interval_min} 分钟")

    @classmethod
    def _loop(cls, interval_min: int):
        # 启动后延迟 30 秒再首轮,避免与数据库初始化竞争
        if cls._stop_event.wait(30):
            return
        while not cls._stop_event.is_set():
            try:
                res = sync_all_once()
                _log(f"本轮完成:共 {res['total']} 个,成功 {res['ok']},失败 {res['fail']},跳过 {res['skip']}")
                for e in res.get("errors", []):
                    _log(f"  - {e}")
                try:
                    _c = get_conn()
                    _record_run(_c, res)
                    _c.close()
                except Exception:
                    pass
            except Exception:
                _log("本轮同步异常:\n" + traceback.format_exc())
            # 间隔自适应:授权后 5 分钟一轮(探测便宜),未授权 30 分钟(避免空转刷屏)
            try:
                conn = get_conn()
                cfg = _load_cfg(conn)
                conn.close()
                interval_min = int(cfg.get("sync_interval_min")
                                   or DEFAULT_INTERVAL_MIN)
            except Exception:
                pass
            if cls._stop_event.wait(interval_min * 60):
                return

    @classmethod
    def stop(cls):
        cls._stop_event.set()
        with cls._lock:
            if cls._thread:
                cls._thread.join(timeout=5)
                cls._thread = None


def start_scheduler_if_enabled():
    """应用启动时调用。"""
    if os.environ.get("SYNC_DISABLED") == "1":
        _log("SYNC_DISABLED=1,跳过启动")
        return
    SyncScheduler.start()


if __name__ == "__main__":
    print("单次同步测试:")
    print(sync_all_once())