- libs: 新增 hr_sdk / hotel_report / dingtalk,更新 desktopauto - controlplane-next: SDK 管理模块(controller/entity/migrations)与前端视图 - electron-shell: 插件同步、注册表、runner 调整 - plugins: XQ0035/XQ0041/XQ0042/XQ0045_XQ0046/XQ0048/XQ0076/XQ0078 等版本更新 - tests/tools: 新增 SDK 兼容性检查与打包工具(sdk_pack.py、sdk_compat_check.py)
240 lines
8.4 KiB
Python
240 lines
8.4 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""统一 HTTP 通道:重试、JSON 解析、钉钉错误码归一、DNS 兜底、日志脱敏。
|
||
|
||
只用 ``requests``(执行机环境包已预装,见 ``sdk.json.deps``)。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
import re
|
||
import socket
|
||
import time
|
||
from typing import Any, Callable, Dict, Optional
|
||
|
||
import requests
|
||
|
||
from .config import get_settings
|
||
from .errors import ApiError, AuthError, DingTalkError, NetworkError
|
||
|
||
API_HOST = "api.dingtalk.com"
|
||
OAPI_HOST = "oapi.dingtalk.com"
|
||
API_BASE = f"https://{API_HOST}/v1.0"
|
||
OAPI_BASE = f"https://{OAPI_HOST}"
|
||
|
||
#: 需要重试的业务错误码(限流/系统繁忙)
|
||
_RETRYABLE_CODES = {"-1", "88", "90018", "130101", "Throttling", "ServiceUnavailable",
|
||
"InternalError", "RequestTimeOut"}
|
||
|
||
_TOKEN_QUERY_RE = re.compile(r"(access_token=)[^&]+", re.IGNORECASE)
|
||
_SECRET_KEYS = ("appSecret", "app_secret", "secret", "password")
|
||
|
||
|
||
# ==================== 日志脱敏 ====================
|
||
|
||
def mask(text: Any) -> str:
|
||
"""脱敏:隐藏 URL 里的 access_token 与 JSON 里的密钥字段。"""
|
||
s = str(text)
|
||
s = _TOKEN_QUERY_RE.sub(r"\1***", s)
|
||
for key in _SECRET_KEYS:
|
||
s = re.sub(rf'("{key}"\s*:\s*")[^"]*(")', r"\1***\2", s)
|
||
return s
|
||
|
||
|
||
# ==================== DNS 兜底 ====================
|
||
|
||
_dns_state: dict = {} # host -> True=已打补丁 / False=系统解析正常
|
||
|
||
|
||
def _doh_resolve(host: str) -> str:
|
||
"""系统 DNS 解析失败时用 DoH 兜底取 A 记录。
|
||
|
||
现场问题:部分 Windows 机器 ``api.dingtalk.com`` 的 CNAME 链能查到、A 记录取不到,
|
||
``socket.getaddrinfo`` 直接 11001 失败,而 IP 直连是通的。
|
||
"""
|
||
for url in ("https://223.5.5.5/resolve", "https://119.29.29.29/resolve"):
|
||
try:
|
||
r = requests.get(url, params={"name": host, "type": "A"},
|
||
headers={"accept": "application/dns-json"},
|
||
timeout=8, verify=False)
|
||
for ans in r.json().get("Answer", []):
|
||
if ans.get("type") == 1 and ans.get("data"):
|
||
return str(ans["data"])
|
||
except Exception: # noqa: BLE001 - 兜底失败即放弃
|
||
continue
|
||
return ""
|
||
|
||
|
||
def install_dns_fallback(host: str = API_HOST) -> bool:
|
||
"""系统 DNS 解析不了该域名时,把 getaddrinfo 打到 DoH 解析出的 IP。返回是否安装。"""
|
||
if host in _dns_state:
|
||
return _dns_state[host]
|
||
try:
|
||
requests.packages.urllib3.disable_warnings() # DoH 走 IP 直连,证书域名不匹配
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
try:
|
||
socket.getaddrinfo(host, 443)
|
||
_dns_state[host] = False
|
||
return False # 系统解析正常
|
||
except socket.gaierror:
|
||
pass
|
||
ip = (os.getenv("DINGTALK_DNS_IP", "") or os.getenv("AITABLE_DNS_IP", "")).strip()
|
||
if not ip:
|
||
ip = _doh_resolve(host)
|
||
if not ip:
|
||
return False
|
||
_orig = socket.getaddrinfo
|
||
|
||
def _gai(h, port, *args, **kwargs):
|
||
return _orig(ip if h == host else h, port, *args, **kwargs)
|
||
|
||
socket.getaddrinfo = _gai # type: ignore[assignment]
|
||
_dns_state[host] = True
|
||
return True
|
||
|
||
|
||
# ==================== 错误归一 ====================
|
||
|
||
def _raise_for_api(data: dict) -> None:
|
||
"""把钉钉响应体里的错误码转成异常;正常返回不抛。"""
|
||
if not isinstance(data, dict):
|
||
return
|
||
code = data.get("code")
|
||
if code:
|
||
msg = str(data.get("message") or data.get("msg") or "")
|
||
full = f"{code}: {msg}" if msg else str(code)
|
||
if "token" in str(code).lower() or "Auth" in str(code):
|
||
raise AuthError(full)
|
||
raise ApiError(mask(full), code=str(code), errmsg=msg, payload=data)
|
||
errcode = data.get("errcode")
|
||
if errcode not in (None, 0, "0"):
|
||
msg = str(data.get("errmsg") or "")
|
||
full = f"errcode={errcode}, errmsg={msg}"
|
||
if str(errcode) in ("40014", "42001", "88"):
|
||
raise AuthError(full)
|
||
raise ApiError(mask(full), code=str(errcode), errmsg=msg, payload=data)
|
||
|
||
|
||
def is_retryable(exc: BaseException) -> bool:
|
||
if isinstance(exc, (NetworkError, AuthError)):
|
||
return isinstance(exc, NetworkError)
|
||
if isinstance(exc, ApiError):
|
||
return exc.code in _RETRYABLE_CODES or exc.code.startswith("5")
|
||
return False
|
||
|
||
|
||
# ==================== 客户端 ====================
|
||
|
||
class HttpClient:
|
||
"""带重试的 JSON 客户端;线程内共享一个 ``requests.Session``。"""
|
||
|
||
def __init__(self, timeout: Optional[float] = None, retries: Optional[int] = None,
|
||
log: Optional[Callable[[str], None]] = None) -> None:
|
||
s = get_settings()
|
||
self.timeout = float(timeout if timeout is not None else s.timeout)
|
||
self.retries = max(1, int(retries if retries is not None else s.retries))
|
||
self.log = log or (lambda msg: None)
|
||
self.session = requests.Session()
|
||
|
||
def close(self) -> None:
|
||
try:
|
||
self.session.close()
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
|
||
def __enter__(self) -> "HttpClient":
|
||
return self
|
||
|
||
def __exit__(self, *exc) -> None:
|
||
self.close()
|
||
|
||
def request(self, method: str, url: str, *, params: Optional[dict] = None,
|
||
body: Optional[dict] = None, files: Optional[dict] = None,
|
||
headers: Optional[dict] = None, token: str = "",
|
||
timeout: Optional[float] = None, retries: Optional[int] = None) -> dict:
|
||
"""发请求并返回 JSON dict;业务错误/网络错误最终以异常抛出。"""
|
||
attempts = max(1, int(retries if retries is not None else self.retries))
|
||
tmo = float(timeout if timeout is not None else self.timeout)
|
||
# multipart 上传时不能预设 Content-Type,交给 requests 生成 boundary
|
||
hdrs = {} if files else {"Content-Type": "application/json"}
|
||
if token:
|
||
hdrs["x-acs-dingtalk-access-token"] = token
|
||
if headers:
|
||
hdrs.update(headers)
|
||
|
||
last: Optional[BaseException] = None
|
||
for attempt in range(1, attempts + 1):
|
||
try:
|
||
resp = self.session.request(
|
||
method, url, params=params, json=body, files=files,
|
||
headers=hdrs, timeout=tmo)
|
||
except requests.RequestException as exc:
|
||
last = NetworkError(mask(f"请求失败({attempt}/{attempts}):{exc}"))
|
||
else:
|
||
if resp.status_code >= 500:
|
||
last = NetworkError(f"服务端 {resp.status_code}({attempt}/{attempts})")
|
||
else:
|
||
try:
|
||
data = self._parse(resp)
|
||
_raise_for_api(data)
|
||
except ApiError as exc:
|
||
last = exc
|
||
if not is_retryable(exc):
|
||
raise
|
||
except AuthError:
|
||
raise
|
||
else:
|
||
return data
|
||
if attempt < attempts:
|
||
self.log(f"[WARN] {mask(last)};{attempt * 1.0:.0f}s 后重试")
|
||
time.sleep(1.0 * attempt)
|
||
assert last is not None
|
||
if isinstance(last, DingTalkError):
|
||
raise last
|
||
raise NetworkError(mask(last))
|
||
|
||
@staticmethod
|
||
def _parse(resp) -> dict:
|
||
text = resp.text or ""
|
||
try:
|
||
data = resp.json()
|
||
except ValueError:
|
||
raise NetworkError(
|
||
mask(f"响应不是 JSON(HTTP {resp.status_code}):{text[:200]}")) from None
|
||
if not isinstance(data, dict):
|
||
raise NetworkError(mask(f"响应结构异常(HTTP {resp.status_code}):{text[:200]}"))
|
||
return data
|
||
|
||
|
||
def request(method: str, url: str, **kwargs) -> dict:
|
||
"""一次性请求(内部临时客户端,适合低频调用)。"""
|
||
client = HttpClient()
|
||
try:
|
||
return client.request(method, url, **kwargs)
|
||
finally:
|
||
client.close()
|
||
|
||
|
||
def join_url(base: str, *parts: str) -> str:
|
||
url = base.rstrip("/")
|
||
for part in parts:
|
||
part = str(part or "").strip("/")
|
||
if part:
|
||
url = f"{url}/{part}"
|
||
return url
|
||
|
||
|
||
__all__ = [
|
||
"API_BASE",
|
||
"API_HOST",
|
||
"HttpClient",
|
||
"OAPI_BASE",
|
||
"OAPI_HOST",
|
||
"install_dns_fallback",
|
||
"is_retryable",
|
||
"join_url",
|
||
"mask",
|
||
"request",
|
||
]
|