270 lines
12 KiB
Python
270 lines
12 KiB
Python
"""按需压缩:接口 JSON 就地压,前端静态资源压一次留在内存里。
|
||
|
||
为什么加这一层
|
||
==============
|
||
``pnpm build`` 之后前端一共 2.7 MB,首屏那一串 ``modulepreload``(入口 + vendor-vue +
|
||
vendor-misc + vendor-i18n + 一个页面 chunk + 一份 CSS)就 650 KB 原文,接口这边一页人员
|
||
列表也有 20 多 KB。这些全是文本,压一下普遍只剩三到四成,浏览器少下两倍字节,弱网和跨机房
|
||
访问时省的是实打实的一两秒。而 uvicorn + ``StaticFiles`` 是直接把原文吐出去的,
|
||
``Content-Length`` 与磁盘上的字节数一字不差 —— 压缩这件事过去没人做。
|
||
|
||
和 ``GZipMiddleware`` 的分工差别在"什么都不压坏":
|
||
|
||
* **只压一次性写完的响应**。``FileResponse`` / ``StreamingResponse`` 的第一块 body 带着
|
||
``more_body=True``,这种一律原样放行。附件下载、预览、``Range`` 断点续传因此完全不受影响
|
||
—— 给 206 响应套一层 gzip 会把 ``Content-Range`` 说成假话,视频拖动就废了。
|
||
* **只压文本类 content-type**。图片、附件、导出包已经是压缩过的字节,再套一层白烧 CPU。
|
||
* **压完更大就不压**(gzip 对已经压过的内容确实会发生),头一个字都不动。
|
||
* 静态资源走另一条路:内容是内容哈希命名的、``Cache-Control: immutable``,压一次的结果
|
||
按 ``路径 + mtime + 大小`` 记在内存里,之后每个请求只是查表,不重复烧 CPU。
|
||
|
||
``Vary: Accept-Encoding`` 两处都会带(``app/cors.py`` 那个中间件认得这个头,会把自己的
|
||
``Origin`` 追加在后面而不是覆盖掉),缓存代理因此不会把 gzip 的响应发给不接受 gzip 的客户端。
|
||
|
||
一个都没配就能跑:本模块不需要任何配置项,也不碰数据库。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import gzip
|
||
import logging
|
||
import threading
|
||
from collections import OrderedDict
|
||
from typing import Any
|
||
|
||
from starlette.datastructures import Headers, MutableHeaders
|
||
from starlette.responses import Response
|
||
from starlette.staticfiles import StaticFiles
|
||
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
||
|
||
logger = logging.getLogger("unisoa.compress")
|
||
|
||
#: 这么小的body不值得压:省下的字节抵不上一个 HTTP 头的零头
|
||
MINIMUM_SIZE = 1024
|
||
#: 压缩档位。9 档对 200 KB 的 JS 要多烧几十毫秒 CPU,换回来的字节不到 3%,不值
|
||
COMPRESS_LEVEL = 5
|
||
#: 静态资源压缩结果在内存里最多留多少字节。整个 dist 的 JS+CSS 压完约 700 KB,
|
||
#: 这个上限留了足够余量,同时挡住"挂载目录被换成一堆大文件"这类意外
|
||
STATIC_CACHE_MAX_BYTES = 16 * 1024 * 1024
|
||
|
||
#: 值得压的 content-type 前缀/特征。除此之外(图片、视频、zip、未知)一律原样放行
|
||
COMPRESSIBLE_TYPES = (
|
||
"application/json",
|
||
"application/javascript",
|
||
"application/xml",
|
||
"application/x-javascript",
|
||
"application/manifest",
|
||
"application/schema",
|
||
"text/",
|
||
"image/svg+xml",
|
||
)
|
||
|
||
|
||
def compressible(content_type: str) -> bool:
|
||
"""这个响应值得压吗。``content-type`` 可能带 ``; charset=``,按前缀判就够。"""
|
||
head = (content_type or "").split(";", 1)[0].strip().lower()
|
||
return any(head.startswith(prefix) for prefix in COMPRESSIBLE_TYPES)
|
||
|
||
|
||
def gzip_body(raw: bytes) -> bytes | None:
|
||
"""压一段完整内容。压完不见得更小,所以要么给出更小的结果,要么给 ``None`` 表示"别压"。"""
|
||
if len(raw) < MINIMUM_SIZE:
|
||
return None
|
||
try:
|
||
packed = gzip.compress(raw, COMPRESS_LEVEL)
|
||
except Exception: # pragma: no cover - gzip 只在内存不足时才会失败
|
||
logger.debug("压缩响应失败,原样返回", exc_info=True)
|
||
return None
|
||
return packed if len(packed) < len(raw) else None
|
||
|
||
|
||
def accepts_gzip(scope: Scope) -> bool:
|
||
"""客户端收不收 gzip。``Accept-Encoding: identity`` 与缺省都按不收处理。"""
|
||
return "gzip" in Headers(scope=scope).get("accept-encoding", "").lower()
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 静态资源:压一次,按内容指纹记在内存里
|
||
# ---------------------------------------------------------------------------
|
||
|
||
_lock = threading.Lock()
|
||
#: (路径, mtime_ns, 大小) -> 压缩结果。用有序字典做最久没用到先丢
|
||
_packed: OrderedDict[tuple[str, int, int], bytes] = OrderedDict()
|
||
_packed_bytes = 0
|
||
|
||
|
||
def _packed_of(full_path: str, stat_result: Any) -> bytes | None:
|
||
"""这个文件的 gzip 结果,没有就现压一份存起来。
|
||
|
||
缓存键带上 mtime 与大小:``pnpm build`` 之后同名文件的内容是新的(哈希命名的其实不会
|
||
重名,这里挡的是没带哈希的 ``manifest.webmanifest``、``sw.js`` 那几份)。
|
||
"""
|
||
global _packed_bytes
|
||
key = (full_path, int(stat_result.st_mtime_ns), int(stat_result.st_size))
|
||
with _lock:
|
||
hit = _packed.get(key)
|
||
if hit is not None:
|
||
_packed.move_to_end(key)
|
||
return hit
|
||
try:
|
||
with open(full_path, "rb") as handle:
|
||
raw = handle.read()
|
||
except OSError:
|
||
return None
|
||
packed = gzip_body(raw)
|
||
if packed is None:
|
||
return None
|
||
with _lock:
|
||
_packed[key] = packed
|
||
_packed_bytes += len(packed)
|
||
while _packed_bytes > STATIC_CACHE_MAX_BYTES and len(_packed) > 1:
|
||
_oldest, dropped = next(iter(_packed.items()))
|
||
del _packed[_oldest]
|
||
_packed_bytes -= len(dropped)
|
||
return packed
|
||
|
||
|
||
def _as_gzip(response: Response, payload: bytes) -> Response:
|
||
"""把已经组装好的文件响应换成同内容的 gzip 版。
|
||
|
||
换掉而不是就地改:``FileResponse`` 的响应体是文件流,改不了字节;直接给
|
||
``Response`` 装内存里那份,内容长度、ETag、``Accept-Ranges`` 才说得准。
|
||
"""
|
||
out = Response(content=payload, status_code=response.status_code)
|
||
for name, value in response.headers.items():
|
||
out.headers[name] = value
|
||
out.headers["content-encoding"] = "gzip"
|
||
out.headers["content-length"] = str(len(payload))
|
||
out.headers.add_vary_header("Accept-Encoding")
|
||
etag = out.headers.get("etag")
|
||
if etag:
|
||
# 同一 URL 现在有两种字节,ETag 必须区分开,否则代理与浏览器会拿 gzip 的 ETag
|
||
# 去要原文(或反过来),命中一次就错一次
|
||
out.headers["etag"] = f"{etag[:-1]}-gz\"" if etag.endswith('"') else f"{etag}-gz"
|
||
# 压过的字节按段范围取没有意义(浏览器也不会对 JS/CSS 发 Range),宁可不说这话
|
||
if "accept-ranges" in out.headers:
|
||
del out.headers["accept-ranges"]
|
||
return out
|
||
|
||
|
||
class GzipStaticFiles(StaticFiles):
|
||
"""``StaticFiles`` + gzip:客户端收 gzip 且这个文件值得压时,给压过的那一份。
|
||
|
||
只管挂载进来的哈希资源。那是 ``dist/assets`` 的专属挂载点,``Cache-Control`` 本来就是
|
||
``immutable``,压过的那一份和原文同生同死,不会和缓存打架。
|
||
"""
|
||
|
||
def file_response(self, *args: Any, **kwargs: Any) -> Response:
|
||
response = super().file_response(*args, **kwargs)
|
||
response.headers["Cache-Control"] = "public, max-age=31536000, immutable"
|
||
# file_response(full_path, stat_result, scope, status_code=...)
|
||
full_path = args[0] if args else kwargs.get("full_path")
|
||
stat_result = args[1] if len(args) > 1 else kwargs.get("stat_result")
|
||
scope = args[2] if len(args) > 2 else kwargs.get("scope")
|
||
if not full_path or stat_result is None or scope is None:
|
||
return response
|
||
if not compressible(response.headers.get("content-type", "")) or not accepts_gzip(scope):
|
||
return response
|
||
payload = _packed_of(str(full_path), stat_result)
|
||
return _as_gzip(response, payload) if payload is not None else response
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 接口响应:只压一次性写完的可压缩响应
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
class GzipResponseMiddleware:
|
||
"""给 ``JSONResponse`` 这类"一口写完"的响应套 gzip。
|
||
|
||
判据(content-type、状态码)在响应头里,压不压又要看 body,所以扣住
|
||
``http.response.start`` 一帧,等第一块 body 出来一起定:
|
||
|
||
* 第一块 body 带 ``more_body=True`` => 流式响应(文件、附件、206 分段),
|
||
头和 body 原样放行。为了省几成字节去缓冲一个导出包,是把首字节时间换了带宽,
|
||
而且给 206 套上 gzip 会让 ``Content-Range`` 说假话。
|
||
* 压完不比原文小(gzip 对已压过的内容真会发生)=> 一个字节都不动。
|
||
|
||
客户端不带 ``Accept-Encoding: gzip`` 时整个中间件不参与,一次判定就放行。
|
||
"""
|
||
|
||
def __init__(self, app: ASGIApp) -> None:
|
||
self.app = app
|
||
|
||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||
if scope["type"] != "http" or not accepts_gzip(scope):
|
||
await self.app(scope, receive, send)
|
||
return
|
||
gate = _GzipGate(send)
|
||
await self.app(scope, receive, gate)
|
||
|
||
|
||
class _GzipGate:
|
||
"""ASGI ``send`` 的关卡:只拦"响应头 + 一整块 body"这一种组合,其余原样过。"""
|
||
|
||
def __init__(self, send: Send) -> None:
|
||
self.send = send
|
||
#: 扣住的响应头;``None`` 表示没扣着东西
|
||
self.start: Message | None = None
|
||
#: 还在等第一块 body 做决定。定过一次之后就再也不拦了
|
||
self.deciding = True
|
||
|
||
async def __call__(self, message: Message) -> None:
|
||
if not self.deciding:
|
||
await self.send(message)
|
||
return
|
||
kind = message["type"]
|
||
if kind == "http.response.start":
|
||
if self._worth_trying(message):
|
||
self.start = message # 扣着,等 body
|
||
else:
|
||
await self._pass_through(message)
|
||
return
|
||
if kind != "http.response.body" or self.start is None:
|
||
await self._pass_through(message)
|
||
return
|
||
await self._first_body(message)
|
||
|
||
def _worth_trying(self, message: Message) -> bool:
|
||
"""这个响应有没有可能压:状态、有没有压过、分段、类型,全在响应头里。"""
|
||
if int(message.get("status") or 200) != 200:
|
||
return False
|
||
headers = MutableHeaders(scope=message)
|
||
return (
|
||
"content-encoding" not in headers
|
||
and headers.get("content-range") is None
|
||
and compressible(headers.get("content-type", ""))
|
||
)
|
||
|
||
async def _pass_through(self, message: Message) -> None:
|
||
"""不做压缩:把扣住的响应头放走,之后所有消息都不再拦。"""
|
||
if self.start is not None:
|
||
await self.send(self.start)
|
||
self.start = None
|
||
self.deciding = False
|
||
await self.send(message)
|
||
|
||
async def _first_body(self, message: Message) -> None:
|
||
if message.get("more_body"):
|
||
await self._pass_through(message) # 流式响应,交给它自己
|
||
return
|
||
packed = gzip_body(message.get("body", b""))
|
||
if packed is None:
|
||
await self._pass_through(message)
|
||
return
|
||
start, self.start = self.start, None
|
||
self.deciding = False
|
||
try:
|
||
headers = MutableHeaders(raw=start["headers"])
|
||
headers["content-encoding"] = "gzip"
|
||
headers["content-length"] = str(len(packed))
|
||
headers.add_vary_header("Accept-Encoding")
|
||
# 原文的长度与"可以分段取"这两句已经都不成立了,留着就是撒谎
|
||
if "accept-ranges" in headers:
|
||
del headers["accept-ranges"]
|
||
await self.send(dict(start, headers=headers.raw))
|
||
except Exception: # pragma: no cover - 头改坏了也要把内容发出去,不能把响应吞了
|
||
logger.exception("压缩响应头改写失败,退回未压缩内容")
|
||
await self.send(start)
|
||
await self.send(dict(message, body=packed))
|