client.py 14.6 KB
# -*- coding: utf-8 -*-
"""HTTP 客户端:串行、统一限速(本机所有 DMS 请求共用 infra/ratelimit 的全局节拍)、网络错误/5xx 自动重试。

* 不自动跟随重定向(登录流程需要自己读 Location 里的 code),提供 follow() 手动跟随。
* 带 Cookie 的 opener 用于登录;业务接口用不带 Cookie 的 opener(已实测只需 Authorization)。
* 每个请求都记一条轨迹(方法、地址、状态、耗时、错误、发出的 Cookie 名、响应头名、响应长度),
  存在内存里最近 200 条;登录失败时自检把轨迹写进结果页,[logging] http_trace=true 时每条也写进日志。
* 每个连接都记录实际连的 IP、TCP 建连 / TLS 握手耗时、失败发生在哪个阶段(DNS / TCP / TLS / 请求发出后),
  失败的 IP 下次排到最后(域名解析出多个 IP 时自动换一个);所有网络失败另写一行到 logs/net/<年-月>/net_events_<日期>.jsonl。
* 同时按 HAR 格式缓存最近的请求(infra/har.PyHar,已脱敏),截图 / 登录任务结束时切片写进结果目录。
"""
import collections
import http.client
import http.cookiejar
import json
import logging
import os
import socket
import ssl
import threading
import time
import urllib.error
import urllib.parse
import urllib.request

from ...infra import har
from ...infra.ratelimit import LIMITER
from ...infra.logutil import add_secret

DEFAULT_UA = ("Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 "
              "(KHTML, like Gecko) Chrome/109.0 Safari/537.36")
RETRY_STATUS = (502, 503, 504)
PENALTY_STATUS = (429, 502, 503, 504)        # 网关限流 / 过载:让全局限速器自动降速(单纯的网络断开不算,门店 auth-api 本来就间歇断连)

log = logging.getLogger("dmsfetch")


class NetworkError(Exception):
    """连接/超时/TLS 等网络层错误(重试后仍失败)。"""


class Response(object):
    def __init__(self, status, headers, body, url, elapsed, error=None):
        self.status = status
        self.headers = headers          # [(name, value), ...]
        self.body = body
        self.url = url
        self.elapsed = elapsed
        self.error = error
        self.text = self._decode(body)

    @staticmethod
    def _decode(b):
        for enc in ("utf-8", "gbk"):
            try:
                return b.decode(enc)
            except Exception:
                pass
        return b.decode("utf-8", "replace")

    def header(self, name):
        for k, v in self.headers:
            if k.lower() == name.lower():
                return v
        return None

    def json(self):
        try:
            return json.loads(self.text)
        except Exception:
            return None


def _describe(e):
    """把异常展开成「类型: 信息 <- 原因」,便于区分 DNS / 连接被拒 / TLS / 对端断开 / 超时。"""
    parts, seen = [], 0
    while e is not None and seen < 4:
        reason = getattr(e, "reason", None)
        parts.append(repr(e))
        e = reason if isinstance(reason, BaseException) else (e.__cause__ or e.__context__)
        seen += 1
    return " <- ".join(parts)


class _NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


# ---------------------------------------------------------------- 连接追踪
_conn_info = threading.local()          # 本线程最近一次连接的 {ip, port, tcp_ms, tls_ms, phase, ips}
_bad_ips = {}                           # (host, ip) → 最近一次失败时间
NET_EVENTS = {"dir": None, "path": None}  # dir = 日志目录(由 Client 设置);path = 最近写入的按天文件


def _order_ips(host, ips):
    """最近 10 分钟失败过的 IP 排到后面。"""
    now = time.time()
    return sorted(ips, key=lambda ip: now - _bad_ips.get((host, ip), 0) < 600)


def mark_bad(host, ip):
    if host and ip:
        _bad_ips[(host, ip)] = time.time()


class _TracingMixin(object):
    def __init__(self, host, *a, **kw):
        kw.pop("check_hostname", None)
        super(_TracingMixin, self).__init__(host, *a, **kw)
        self._create_connection = self._traced_create_connection     # http.client 在 __init__ 里赋值,这里覆盖

    def _traced_create_connection(self, address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None):
        host, port = address
        info = {"host": host, "port": port, "ip": "", "tcp_ms": None, "tls_ms": None, "phase": "dns", "ips": []}
        _conn_info.v = info
        t0 = time.time()
        addrs = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
        ips = []
        for a in addrs:
            if a[4][0] not in ips:
                ips.append(a[4][0])
        info["ips"] = ips
        info["dns_ms"] = round((time.time() - t0) * 1000, 1)
        info["phase"] = "tcp"
        last = None
        for ip in _order_ips(host, ips):
            info["ip"] = ip
            t1 = time.time()
            try:
                sock = socket.create_connection((ip, port), timeout, source_address)
                info["tcp_ms"] = round((time.time() - t1) * 1000, 1)
                info["phase"] = "tls" if isinstance(self, http.client.HTTPSConnection) else "request"
                return sock
            except OSError as e:
                last = e
                mark_bad(host, ip)
        raise last or OSError("没有可用的地址")

    def connect(self):
        t0 = time.time()
        super(_TracingMixin, self).connect()
        info = getattr(_conn_info, "v", None)
        if info is not None:
            if isinstance(self, http.client.HTTPSConnection) and info.get("tcp_ms") is not None:
                info["tls_ms"] = round((time.time() - t0) * 1000 - info["tcp_ms"] - (info.get("dns_ms") or 0), 1)
            info["phase"] = "request"


class _TracingHTTPConnection(_TracingMixin, http.client.HTTPConnection):
    pass


class _TracingHTTPSConnection(_TracingMixin, http.client.HTTPSConnection):
    pass


class _TracingHTTPHandler(urllib.request.HTTPHandler):
    def http_open(self, req):
        return self.do_open(_TracingHTTPConnection, req)


class _TracingHTTPSHandler(urllib.request.HTTPSHandler):
    def __init__(self, context=None):
        urllib.request.HTTPSHandler.__init__(self, context=context)
        self._ctx2 = context

    def https_open(self, req):
        return self.do_open(_TracingHTTPSConnection, req, context=self._ctx2)


PHASE_CN = {"dns": "DNS 解析", "tcp": "TCP 建连", "tls": "TLS 握手", "request": "请求发出后(等响应时被断开)"}


def _net_event(rec):
    if not NET_EVENTS["dir"]:
        return
    from ...infra.logs import dated_path
    path = NET_EVENTS["path"] = dated_path(NET_EVENTS["dir"], "net")
    try:
        os.makedirs(os.path.dirname(path), exist_ok=True)
        with open(path, "a", encoding="utf-8") as f:
            f.write(json.dumps(rec, ensure_ascii=False) + "\n")
    except OSError:
        pass


class Client(object):
    def __init__(self, cfg):
        self.cfg = cfg
        ctx = ssl.create_default_context()
        if not cfg.verify_ssl:
            ctx.check_hostname = False
            ctx.verify_mode = ssl.CERT_NONE
        self._ctx = ctx
        self.jar = http.cookiejar.CookieJar()
        self._opener_jar = self._build(self.jar)
        self._opener_nojar = self._build(None)
        self.trace = collections.deque(maxlen=200)
        self.ua = getattr(cfg, "user_agent", "") or DEFAULT_UA
        self.http_trace = getattr(cfg, "http_trace", False)
        self.har = har.PyHar(enabled=getattr(cfg, "har_capture", True))
        if getattr(cfg, "log_dir", ""):
            NET_EVENTS["dir"] = cfg.log_dir
        self._lock = threading.RLock()       # 截图时浏览器代发和业务请求可能并发,统一串行
        self.penalize = True                 # 出错时让全局限速器降速(网络诊断等探测请求关掉)

    def _build(self, jar):
        if self.cfg.proxy:
            proxy = urllib.request.ProxyHandler({"http": self.cfg.proxy, "https": self.cfg.proxy})
        elif self.cfg.use_system_proxy:
            proxy = urllib.request.ProxyHandler()
        else:
            proxy = urllib.request.ProxyHandler({})
        handlers = [proxy, _NoRedirect(), _TracingHTTPHandler(), _TracingHTTPSHandler(context=self._ctx)]
        if jar is not None:
            handlers.append(urllib.request.HTTPCookieProcessor(jar))
        return urllib.request.build_opener(*handlers)

    # ------------------------------------------------------------------
    def _throttle(self):
        LIMITER.wait(self.cfg)

    def _harvest_cookies(self):
        for c in self.jar:
            if c.value and len(c.value) >= 8:
                add_secret(c.value)

    def _once(self, method, url, headers, data, cookies, timeout):
        h = {"User-Agent": self.ua, "Accept": "*/*"}
        h.update(headers or {})
        if isinstance(data, str):
            data = data.encode("utf-8")
        req = urllib.request.Request(url, data=data, headers=h, method=method)
        opener = self._opener_jar if cookies else self._opener_nojar
        _conn_info.v = None
        t0 = time.time()
        try:
            r = opener.open(req, timeout=timeout or self.cfg.timeout)
            resp = Response(r.status, r.getheaders(), r.read(), url, time.time() - t0)
        except urllib.error.HTTPError as e:
            resp = Response(e.code, list(e.headers.items()), e.read(), url, time.time() - t0)
        except Exception as e:  # 连接 / 超时 / TLS
            resp = Response(0, [], b"", url, time.time() - t0, error=_describe(e))
        info = getattr(_conn_info, "v", None) or {}
        resp.conn = info
        if resp.status == 0 and info:
            mark_bad(info.get("host"), info.get("ip"))
            resp.error = "%s [阶段: %s, IP %s]" % (resp.error, PHASE_CN.get(info.get("phase"), info.get("phase")),
                                                  info.get("ip") or "?")
        self._harvest_cookies()
        self._record(req, resp, data, t0)
        return resp

    def _record(self, req, resp, data, t0):
        sent_len = len(data or b"")
        cookie = req.unredirected_hdrs.get("Cookie") or req.headers.get("Cookie") or ""
        info = getattr(resp, "conn", None) or {}
        rec = {"time": time.strftime("%H:%M:%S"), "method": req.get_method(), "url": resp.url,
               "status": resp.status, "elapsed": round(resp.elapsed, 3), "error": resp.error,
               "ip": info.get("ip"), "tcp_ms": info.get("tcp_ms"), "tls_ms": info.get("tls_ms"),
               "phase": info.get("phase") if resp.status == 0 else None,
               "sent_bytes": sent_len, "cookie_names": [c.split("=", 1)[0].strip() for c in cookie.split(";") if c.strip()],
               "cookie_header_len": len(cookie),
               "req_headers": sorted(set(list(req.headers) + list(req.unredirected_hdrs))),
               "resp_bytes": len(resp.body), "location": resp.header("Location"),
               "resp_headers": [k for k, _ in resp.headers]}
        if resp.status == 0 or resp.status >= 400:
            rec["resp_snippet"] = resp.text[:300]
        self.trace.append(rec)
        log.log(logging.INFO if self.http_trace else logging.DEBUG,
                "HTTP %s %s -> %s %.2fs %dB%s%s%s", rec["method"], rec["url"].split("?")[0], rec["status"] or "网络错误",
                rec["elapsed"], rec["resp_bytes"], "  IP %s" % rec["ip"] if rec["ip"] else "",
                "  Cookie(%d个/%d字节)" % (len(rec["cookie_names"]), len(cookie)) if cookie else "",
                "  错误: " + resp.error if resp.error else "")
        if resp.status == 0:
            _net_event({"time": time.strftime("%Y-%m-%d %H:%M:%S"), "source": "python", "method": rec["method"],
                        "host": urllib.parse.urlparse(resp.url).netloc, "path": urllib.parse.urlparse(resp.url).path,
                        "ip": rec["ip"], "ips": info.get("ips"), "phase": rec["phase"], "tcp_ms": rec["tcp_ms"],
                        "tls_ms": rec["tls_ms"], "elapsed": rec["elapsed"], "error": resp.error})
        hdrs = dict((k, v) for k, v in req.header_items())
        self.har.add(har.entry(
            rec["method"], resp.url, t0, list(hdrs.items()), data, resp.status, "", resp.headers, resp.body,
            resp.elapsed * 1000.0, {"dns": info.get("dns_ms"), "connect": info.get("tcp_ms"), "ssl": info.get("tls_ms")},
            rec["ip"] or "", resp.error or "", "失败阶段:%s" % PHASE_CN.get(rec["phase"], rec["phase"]) if rec["phase"] else "",
            hdrs.get("Content-type") or hdrs.get("Content-Type") or "", resp.header("Content-Type") or ""))

    def request(self, method, url, headers=None, data=None, cookies=True, retries=None, timeout=None):
        """发请求。网络错误(status=0)与 502/503/504 会按退避重试 retries 次;其余状态码原样返回。"""
        retries = self.cfg.max_retries if retries is None else retries
        attempt = 0
        while True:
            with self._lock:
                self._throttle()
                resp = self._once(method, url, headers, data, cookies, timeout)
            if not self.penalize:
                pass
            elif resp.status in PENALTY_STATUS:
                LIMITER.penalize("HTTP %d" % resp.status, self.cfg)
            elif resp.status:
                LIMITER.reward(self.cfg)
            if not (resp.status == 0 or resp.status in RETRY_STATUS) or attempt >= retries:
                return resp
            attempt += 1
            delay = self.cfg.retry_backoff * (2 ** (attempt - 1))
            log.warning("请求失败(%s),%.1f 秒后重试 %d/%d: %s %s", resp.error or "HTTP %d" % resp.status,
                        delay, attempt, retries, method, url.split("?")[0])
            time.sleep(delay)

    def follow(self, method, url, headers=None, data=None, stop_when=None, max_hops=12, retries=None):
        """手动跟随重定向。返回 (最后一个响应, 链[{url,status,location}])。stop_when(location)=True 时停在该跳。"""
        chain = []
        resp = None
        for _ in range(max_hops):
            resp = self.request(method, url, headers=headers, data=data, retries=retries)
            loc = resp.header("Location")
            loc_abs = urllib.parse.urljoin(url, loc) if loc else None
            chain.append({"url": url, "status": resp.status, "location": loc_abs, "error": resp.error})
            if resp.error:
                return resp, chain
            if loc_abs and stop_when and stop_when(loc_abs):
                return resp, chain
            if resp.status in (301, 302, 303, 307, 308) and loc_abs:
                url, method, data = loc_abs, "GET", None
                continue
            return resp, chain
        return resp, chain