download_meter.py 3.28 KB
"""证据文件下载计量:日志包 / 诊断包 / 截图下载一次记一行日志(状态、字节数、耗时、客户端、是否中途断开)。

浏览器那边只会报笼统的 "Failed to fetch" / 下载失败;有了这一行就能分清是请求没到云端、云端出错,
还是传到一半连接断了(代理 / 网关 / 网络)。纯 ASGI 包装,不改响应本身(Range 续传照常可用)。
"""
from __future__ import annotations

import logging
import re
import time

log = logging.getLogger("server.download")
PREFIXES = ("/api/evidence/", "/api/public/evidence/")
_FILENAME = re.compile(r"""filename\*=utf-8''([^;]+)|filename="?([^";]+)"?""", re.I)


def _header(headers, name: bytes) -> str:
    for k, v in headers or []:
        if k.lower() == name:
            return v.decode("latin-1")
    return ""


class DownloadMeter:
    def __init__(self, app):
        self.app = app

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http" or not scope["path"].startswith(PREFIXES):
            return await self.app(scope, receive, send)
        from urllib.parse import unquote
        t0 = time.monotonic()
        st = {"status": 0, "total": None, "sent": 0, "done": False, "gone": False, "name": ""}

        async def _receive():
            msg = await receive()
            if msg["type"] == "http.disconnect" and not st["done"]:
                st["gone"] = True
            return msg

        async def _send(msg):
            if msg["type"] == "http.response.start":
                st["status"] = msg["status"]
                cl = _header(msg.get("headers"), b"content-length")
                st["total"] = int(cl) if cl.isdigit() else None
                m = _FILENAME.search(_header(msg.get("headers"), b"content-disposition"))
                st["name"] = unquote(m.group(1) or m.group(2)) if m else ""
            elif msg["type"] == "http.response.body":
                st["sent"] += len(msg.get("body") or b"")
                if not msg.get("more_body"):
                    st["done"] = True
            await send(msg)

        err = None
        try:
            await self.app(scope, _receive, _send)
        except BaseException as e:  # noqa: BLE001
            err = e
            raise
        finally:
            hdrs = scope.get("headers")
            client = (scope.get("client") or ("?",))[0]
            what = "%s%s" % (scope["path"].rsplit("/", 1)[-1], f" {st['name']}" if st["name"] else "")
            size = f"{st['sent']}/{st['total'] if st['total'] is not None else '?'} 字节"
            rng = _header(hdrs, b"range")
            tail = f",{time.monotonic() - t0:.1f} 秒,客户端 {client}{',Range ' + rng if rng else ''},UA {_header(hdrs, b'user-agent')[:120]}"
            if err is not None:
                log.error("下载证据 #%s:云端出错 %s(已发送 %s)%s", what, type(err).__name__, size, tail)
            elif st["gone"]:
                log.warning("下载证据 #%s:客户端中途断开(已交给网络层 %s,HTTP %s)%s", what, size, st["status"], tail)
            elif st["status"] >= 400:
                log.warning("下载证据 #%s:HTTP %s%s", what, st["status"], tail)
            else:
                log.info("下载证据 #%s:完成 HTTP %s,%s%s", what, st["status"], size, tail)