代码管理

dashboard/conn_health.py

← 返回编辑
# -*- coding: utf-8 -*-
"""接口健康体检 —— 真打一次只读接口,把「能不能用」落到库上。

为什么要这个模块(2026-11-18 用户):
    原来接口状态只有「未接入 / 接入中 / 已接入」三态,只要 token 存进去就
    永远显示「已接入」。token 过期了、被同平台别的账号挤掉了、或者网关改了
    鉴权,页面照样一片绿色 —— 用户点测试才发现都是过期。

    所以状态必须由**真实探测结果**决定,而不是「有没有 token」。

    ⚠️ 探测跑在云端容器里(实测三个网关都是公网,200/404 均可达),
       不依赖本机执行器;执行器只保留「拉浏览器登录拿 token」这一个职责。

只读红线:本模块只调 count / page(size=1),绝不写任何业务数据。
"""
from __future__ import annotations

import json
import time
import urllib.error
import urllib.parse
import urllib.request
from typing import Any, Dict, Optional, Tuple

import crypto_store as cs

ODIN_TENANT = "100004"
OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))


# ------------------------------------------------------------------ 凭据
def cred(raw: Any) -> Dict[str, Any]:
    """解析库里的 token(可能是密文、JSON 串或裸 token)。"""
    if isinstance(raw, dict):
        return raw
    t = str(raw or "").strip()
    if t and cs.is_encrypted(t):
        try:
            t = cs.decrypt(t)
        except Exception:
            pass
    t = str(t or "").strip()
    if t.startswith("{"):
        try:
            d = json.loads(t)
            if isinstance(d, dict):
                return d
        except Exception:
            pass
    return {"token": _unwrap(t), "x_token": _unwrap(t), "sc_token": _unwrap(t)}


def _unwrap(v: Any) -> Any:
    if isinstance(v, str):
        v = v.strip()
        if len(v) >= 2 and v[0] == '"' and v[-1] == '"':
            try:
                return json.loads(v)
            except Exception:
                return v[1:-1]
    return v


def expired(cred_: Dict[str, Any]) -> bool:
    """凭据自带过期时间且已过期、且没法自动续期 → 真过期。"""
    exp = cred_.get("expires_at")
    if not exp:
        return False
    try:
        if int(float(exp)) > time.time():
            return False
    except Exception:
        return False
    # 有过期时间但带 refresh_token 的(奥丁)能自动续,不算掉线
    return not cred_.get("refresh_token")


# ------------------------------------------------------------------ HTTP
def _post(url: str, body: Dict[str, Any], headers: Dict[str, str],
          timeout: float = 40.0) -> Dict[str, Any]:
    req = urllib.request.Request(
        url, data=json.dumps(body).encode(), headers=headers, method="POST")
    req.add_header("User-Agent", "gr-dashboard-health/1.0")
    with OPENER.open(req, timeout=timeout) as r:
        txt = r.read().decode("utf-8", "ignore")
    try:
        return json.loads(txt)
    except Exception:
        return {"__raw": txt[:300]}


def _odin_refresh(base: str, cred_: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    """奥丁 refresh_token 换新 token(与原执行器同一套)。失败返回 None。"""
    rt = cred_.get("refresh_token") or ""
    ba = cred_.get("basic_auth") or ""
    if not (rt and ba):
        return None
    qs = urllib.parse.urlencode({"refresh_token": rt,
                                 "grant_type": "refresh_token",
                                 "scope": "server"})
    req = urllib.request.Request(base + "/auth/oauth2/token?" + qs, data=b"",
                                 method="POST")
    req.add_header("Authorization", ba)
    req.add_header("Content-Type", "application/x-www-form-urlencoded")
    req.add_header("TENANT-ID", str(cred_.get("tenant_id") or ODIN_TENANT))
    req.add_header("TENANT-CODE", str(cred_.get("tenant_code")
                                      or cred_.get("tenant_id") or ODIN_TENANT))
    req.add_header("Cch", "Y2NocA==")
    try:
        with OPENER.open(req, timeout=30) as r:
            j = json.loads(r.read().decode())
    except Exception as e:
        return {"__err": "续期请求失败:%s" % str(e)[:80]}
    if str(j.get("code")) not in ("0", "200"):
        return {"__err": "续期被拒:%s" % str(j)[:100]}
    d = j.get("data") or {}
    tokv = d.get("access_token")
    if not tokv:
        return {"__err": "续期无 access_token"}
    exp = d.get("expires_in")
    return {
        "token": tokv,
        "refresh_token": d.get("refresh_token") or cred_.get("refresh_token") or "",
        "tenant_id": cred_.get("tenant_id") or "",
        "tenant_code": cred_.get("tenant_code") or "",
        "basic_auth": ba,
        "expires_at": str(int(time.time()) + int(exp)) if exp else "",
    }


def _msg(d: Dict[str, Any]) -> str:
    for k in ("msg", "message", "errMsg", "error_description"):
        v = d.get(k)
        if v:
            return str(v)[:160]
    return str(d.get("__raw") or d)[:160]


# ------------------------------------------------------------------ 探测
def probe(it: Dict[str, Any]) -> Tuple[bool, str, Optional[str]]:
    """探一个接口。返回 (是否可用, 说明, 需要回写的新 token 明文或 None)。

    只读:线索取 count、库存取 page(size=1)。
    异常统一在这里翻成人话 —— 页面直接显示,不能给用户看
    「HTTPError: HTTP Error 401: Unauthorized」这种。
    """
    try:
        return _probe(it)
    except urllib.error.HTTPError as e:
        body = ""
        try:
            body = (e.read() or b"")[:120].decode("utf-8", "ignore")
        except Exception:
            pass
        if e.code in (401, 403):
            return False, ("登录已过期或没有访问权限(HTTP %s)→ 需重新授权" % e.code), None
        return False, ("接口报错 HTTP %s %s" % (e.code, body)).strip(), None
    except Exception as e:                                   # noqa: BLE001
        return False, ("%s: %s" % (type(e).__name__, str(e)[:120])), None


def _probe(it: Dict[str, Any]) -> Tuple[bool, str, Optional[str]]:
    fam = str(it.get("family") or "")
    gw = str(it.get("gateway") or "").rstrip("/")
    raw = it.get("token") or ""
    if not (gw and raw):
        return False, "缺少网关或 token", None
    c = cred(raw)

    if fam in ("chery_scrm", "chery_gf", "chery_icar"):
        base = gw if gw.endswith("/scrm-clue") else gw + "/api/app/scrm-clue"
        # body 用最简形式:iCAR 租户对完整空字段 body 会 500「操作失败」
        d = _post(base + "/crmClue/pc/list/count",
                  {"pageNum": 1, "pageSize": 1, "clueStatus": [], "clueLevel": []},
                  {"Content-Type": "application/json",
                   "X-Token": str(c.get("x_token") or c.get("token") or ""),
                   "pre-auth-code": str(c.get("pre_auth_code")
                                        or it.get("pre_auth_code") or "160002"),
                   "client-type": str(c.get("client_type") or "0"),
                   "Origin": "https://scrm.mychery.com"})
        if d.get("code") not in (0, "0", 200, "200", None):
            return False, "接口返回异常:%s" % _msg(d), None
        n = d.get("data")
        if n is None:
            return False, "无数据字段:%s" % _msg(d), None
        return True, "线索计数 %s" % n, None

    if fam == "jetour_yike":
        d = _post(gw + "/shop/clue/pool/shop/default/queryPageTotal",
                  {"pageIndex": 1, "pageSize": 1, "erpCode": it.get("erp") or "",
                   "meFlag": 0, "handleType": 1},
                  {"Content-Type": "application/json",
                   "sc_token": str(c.get("sc_token") or c.get("token") or ""),
                   "scrm_permission": str(c.get("scrm_permission")
                                          or "ShopGeneralClueManage")})
        if d.get("error"):
            return False, "登录过期或权限不足:%s" % _msg(d), None
        n = (d.get("data") or {}).get("allTotal") if isinstance(d.get("data"), dict) \
            else d.get("data")
        return True, "店铺线索池 %s" % (n if n is not None else "—"), None

    if fam.startswith("odin"):
        # 网关本身常已带 /api,再拼就 404
        base = gw if gw.endswith("/api") else gw + "/api"
        url = base + "/dealerSvc/dealerVehicleStock/pageDealer"
        body = {"activeTab": "", "current": 1, "size": 1}

        def call(cr: Dict[str, Any]) -> Dict[str, Any]:
            return _post(url, body, {
                "Content-Type": "application/json",
                "Accept": "application/json, text/plain, */*",
                "Authorization": "Bearer " + str(cr.get("token") or ""),
                "TENANT-ID": str(cr.get("tenant_id") or ODIN_TENANT),
                "TENANT-CODE": str(cr.get("tenant_code")
                                   or cr.get("tenant_id") or ODIN_TENANT),
                "Cch": str(cr.get("basic_auth") or "Y2NocA=="),
                "time-zone": "Asia/Shanghai"})

        new_tok: Optional[str] = None
        try:
            d = call(c)
        except urllib.error.HTTPError as e:
            if e.code not in (401, 424, 403):
                return False, "HTTP %s %s" % (e.code,
                                              (e.read() or b"")[:100].decode("utf-8", "ignore")), None
            c2 = _odin_refresh(base, c)
            if not c2 or c2.get("__err"):
                return False, "token 过期且自动续期失败(%s)" % (
                    (c2 or {}).get("__err") or "无 refresh_token"), None
            d = call(c2)
            new_tok = json.dumps(c2, ensure_ascii=False)
        if str(d.get("code")) not in ("0", "200", "None"):
            return False, "接口返回异常:%s" % _msg(d), new_tok
        n = (d.get("data") or {}).get("total") if isinstance(d.get("data"), dict) else None
        return True, "在库车辆 %s" % (n if n is not None else "—"), new_tok

    return False, "未知平台族:%s" % (fam or "(空)"), None