perf(交付面): 按 media type 压缩 + 哈希产物长期缓存,后端与 nginx 同一套口径

Bundle 那十几轮量的是**文件字节**(`chunkinfo`),但线上真正过网的是这一层的响应头:
首屏闭包 1 469 kB 里 1 144 kB 是一个带哈希的 JS chunk,不压就是按 raw 发,量好的
gzip 450 kB 白量。补上缺的另一半(阶段 29、30)。

backend/app/main.py:
- `gzip_eligible()` 是唯一的权威名单,只认 media type 不认路径前缀(只压文本,
  mp4 与已压过的图片挡在外面);`ContentTypeGZipMiddleware` 按它决定是否压,
  小于阈值的响应不压(压完加头比原文还大,还多一个 `Vary` 命中率)。
- 中间件顺序是有条件的:压缩层必须**最先**注册,否则 `add_middleware` 把自己插到
  最外层之后,压缩跑到了鉴权外面。
- 交付面缓存:`/assets` 带内容哈希 ⇒ `public, max-age=31536000, immutable`;
  `index.html` 与 history 回落出去的壳 ⇒ `no-cache` 每次回源校验,否则发版后老标签页
  拿着旧壳去引已经不存在的哈希文件,用户看到白屏。

frontend/nginx.conf:反代这一层写同一套口径(注释里点名「权威名单在后端
`app.main.gzip_eligible`,这里这份是兜底」),并补 `gzip_proxied any`——
它管的是**带 `Via` 请求头的请求**(nginx 站在 CDN 后面时),默认 `off` 下直连浏览器
照样压;挂 CDN 时这套压缩不能整块失效。三组合 A/B/C 的实测对账在
`reports/ui_evidence/nex-p30/nginx-ab.log`:后端已压时 nginx 透传不叠第二层,
后端没压时这里兜底压上(A 组合 `/api/projects` 341 909 → 53 333 B 是 nginx 自己压的)。

测试:新增 `backend/tests/test_api_content_gzip.py`,`test_spa_history_fallback.py`
补 `test_asset_delivery_cache_and_gzip`,三条断言各自钉住一个会真实发生的事故
(不压 / 壳不回源 / 小文件也压)。
main
mula.liu 2026-11-12 10:21:17 +08:00
parent 7a7c5e06e8
commit cbc645c4e1
4 changed files with 464 additions and 6 deletions

View File

@ -13,7 +13,9 @@ from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from starlette.datastructures import Headers
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.middleware.gzip import GZipMiddleware, GZipResponder
from app.api import api_router
from app.api.auth import auth_middleware
@ -61,8 +63,98 @@ async def lifespan(app: FastAPI):
app = FastAPI(title=settings.app_name, version="1.0.0", lifespan=lifespan,
description="长视频编导平台:资产库 → 分镜脚本 → 模型调度 → 质检审核 → 时间线合成导出")
# 先注册鉴权、后注册 CORS:Starlette 里**后注册的中间件在最外层**,
# 这样 401/403 也会带上 CORS 头,前端才能读到「未登录」而不是一个笼统的网络错误。
# ------------------------------------------------------------------ 交付面:按 content-type 压缩
# 立项依据是阶段 29 的两把实测尺(`reports/ui_evidence/nex-p29/apigzip.log`):
# 首访过网 1 292 834 B 里 `/api` 占 773 646 B,比全部 JS+CSS 之和(512 744 B)还大,
# 而它是当时唯一没压的一族。同一把尺(gzip level 6)离线量过:
# · JSON 21 条 866 745 → 143 900 B,**省 83.4 %**;
# · 挂在同一个 `/api` 前缀下的 `/api/media/thumb/*.png` 24 条 51 768 → 52 320 B,
# **反而 +1.1 %**(PNG 自己就是压过的)。
# ⇒ 判据不能是路径前缀。所以这里不直接用 `GZipMiddleware` 挂全站:它只看
# `Accept-Encoding` 和体积,**不看 content-type**,挂上去会把下面两样东西压坏——
# · `/api/media/thumb/*.png`:白烧 CPU 还变大;
# · `/api/exports/{id}/download` 的 `video/mp4`:Starlette 压完顺手删掉
# `Content-Length`,而播放器要靠它算 Range 进度条,seek 直接废。
# 做法:复用 Starlette 那套已经被验证过的流式 gzip 状态机(`GZipResponder`:
# 缓冲到 minimum_size 再决定、边压边发、合并 `Vary`、压完才删 `Content-Length`),
# 只在 `http.response.start` 那一步多问一句「这个 media type 值不值得压」。
# `GZIP_MINIMUM` 管不管得住,取决于这一层坐在鉴权中间件的哪一侧。阶段 30 为此翻过一次,
# A/B 读数在 `reports/ui_evidence/nex-p30/servecheck.log`:
# · starlette 0.46.2 `gzip.py` 的体积阈值只在「一条 body 消息且 `more_body=False`」时判定。
# 路由返回 `JSONResponse`、`StaticFiles` 发小文件 ⇒ 都是一条完整 body ⇒ 阈值管得住。
# · `BaseHTTPMiddleware` 会把下游响应转成分块转发(首块 `more_body=True`)⇒ 阈值整体失效。
# 把它压在这一层外面那次实测:4 个 <1 kB 的哈希 chunk(`ProjectDetail` /
# `kit-icons-extra` / `use-auto-refresh` / `use-local-storage`)与 742 B 的导出元数据
# 全被压,跟项目自己声明的 1 kB 底线(`SPA_GZIP_MINIMUM`、nginx `gzip_min_length`)对不上。
# ⇒ 所以顺序是「压缩层最内 → 鉴权 → CORS 最外」,见下面三条 `add_middleware`。
# 代价:鉴权自己吐的 401/403 JSON(实测 25 B)不被覆盖——它本来就在阈值以下。
# 收益:阈值名副其实,静态面与 API 面同一把尺,servecheck 那条「<1 kB 的小文件不压」
# 两侧都过(是实现对上判据,不是把判据改松)。
# · 仍然成立的那半:流式端点不看体积(`StreamingResponse` 首块就压)⇒
# 二进制的安全由 media type 判据负责,不由阈值负责。
# (钉在 `tests/test_api_content_gzip.py::test_streaming_webp_thumbnail_is_still_untouched`)
GZIP_MINIMUM = 1024 # 与 SPA_GZIP_MINIMUM / nginx `gzip_min_length` 同一把尺
GZIP_LEVEL = 6 # 与 SPA_GZIP_LEVEL / nginx `gzip_comp_level` 同一把尺
# 文本族之外的类型一律不压。`text/*` 在函数里单列,这里只登记非 text/ 的:
GZIP_TYPES = frozenset({
"application/json", "application/geo+json", "application/ld+json", "application/ndjson",
"application/x-ndjson", "application/javascript", "text/javascript", "application/ecmascript",
"application/xml", "text/xml", "image/svg+xml", "application/yaml", "application/x-yaml",
})
def gzip_eligible(content_type: str) -> bool:
"""这个响应的 media type 值不值得 gzip。"""
main = (content_type or "").split(";", 1)[0].strip().lower()
if not main:
return False # 没声明类型的空响应 / 204:不压
if main.startswith("text/"):
# SSE 是长连接上的逐条推送,gzip 会把它攒成块(Starlette 自己也排除它)
return main != "text/event-stream"
return main in GZIP_TYPES
class _GzipByContentType(GZipResponder):
"""`GZipResponder` + 一条 content-type 判据。
父类在 `http.response.start` 时只把 `text/event-stream` 当例外;这里把「例外」的定义
换成「不在文本族里」,其余流程(缓冲、流式、`Vary`、`Content-Length`)一个字不改,
所以不会另起一套实现。已经带 `Content-Encoding` 的也归入例外:上游压过就透传,
不叠第二层(`/assets` 那一层 gzip 与这一层并存靠的就是这条)。
"""
async def send_with_compression(self, message):
await super().send_with_compression(message)
if message["type"] == "http.response.start":
headers = Headers(raw=message["headers"])
self.content_type_is_excluded = (self.content_type_is_excluded
or self.content_encoding_set
or not gzip_eligible(headers.get("content-type", "")))
class ContentTypeGZipMiddleware(GZipMiddleware):
"""按 content-type 过滤的 gzip。它是三条用户中间件里最内的一条,
所以看到的是路由与挂载点自己发出的响应(体积阈值管得住,见上面的说明);
异常处理器在路由内侧,5xx 的 JSON 一样被覆盖。"""
async def __call__(self, scope, receive, send):
if scope["type"] != "http" or \
"gzip" not in Headers(scope=scope).get("accept-encoding", "").lower():
await self.app(scope, receive, send) # 客户端不收 gzip ⇒ 原样给,绝不冒充
return
await _GzipByContentType(self.app, self.minimum_size,
compresslevel=self.compresslevel)(scope, receive, send)
# 三条用户中间件从外到内:CORS → 鉴权 → 按 content-type 的 gzip。
# `add_middleware` 把自己插到最外层 ⇒ 压缩层必须**最先**注册,晚一行就跑到了鉴权外面
# (那一版把 `GZIP_MINIMUM` 整个架空了,见上面)。gzip 只影响响应编码:不改状态码、
# 不改 body、不改任何业务契约,解压后与原来逐字节相同
# (`backend/tests/test_api_content_gzip.py` 就是这么断言的)。
app.add_middleware(ContentTypeGZipMiddleware, minimum_size=GZIP_MINIMUM, compresslevel=GZIP_LEVEL)
# 鉴权排第二、CORS 最后注册坐在最外 ⇒ 401/403 也带 CORS 头,
# 前端才能读到「未登录」而不是一个笼统的网络错误。
app.add_middleware(BaseHTTPMiddleware, dispatch=auth_middleware)
app.add_middleware(CORSMiddleware,
allow_origins=settings.cors_origin_list or ["*"],
@ -83,6 +175,62 @@ Path(settings.media_root).mkdir(parents=True, exist_ok=True)
app.mount(settings.media_url_prefix, StaticFiles(directory=settings.media_root), name="media")
# ------------------------------------------------------------------ 交付面:SPA 静态资源
# 三条口径放在一起说清楚,免得下一轮又去后端中间件上试:
# ① 带哈希的 chunk 与内容一一对应 ⇒ 让浏览器缓存一年;`index.html` 反过来必须每次回源
# 校验,否则发版后老标签页拿着旧壳去引已经消失的哈希文件,用户看到的是白屏。
# ② 文本资源要压:首屏闭包 1 469 kB(`scripts/ui/chunkinfo.mjs`)里 1 144 kB 是一个
# JS chunk,原文直出等于把已经量好的 gzip 450 kB 按 raw 再发一遍。
# `compresslevel` 取 6 不取 9——同级产物只差千分之几,CPU 便宜一半(实测见
# `reports/ui_evidence/nex-p29/serve-ab.log`)。
# ③ 压缩判据是**响应自己声明的 media type**,不是它挂在哪个路径前缀下:见上面
# 「交付面:按 content-type 压缩」那一节。`/assets` 这一层仍然自带 gzip
# (阶段 29 的产物证据与 pytest 都钉在它上面;本目录只有 js/css,没有二进制),
# 上面那一层看到已经带 `Content-Encoding` 的响应会原样透传,不会压两遍。
SPA_ASSET_CACHE = "public, max-age=31536000, immutable"
SPA_SHELL_CACHE = "no-cache"
SPA_GZIP_MINIMUM = 1024 # 小于 1 kB 不值得压(压完加头反而更大)
SPA_GZIP_LEVEL = 6
def with_cache_control(asgi, value: str):
"""给子应用的每个响应补一个 `Cache-Control`,上游已经给了就不覆盖。
没用 `StaticFiles(headers=...)`:那个构造参数在 starlette 0.3x 就被删了,
本项目锁的是 0.46.2,写死之后整个 `/assets` 挂载直接 TypeError。
包一层只读 ASGI 的 `http.response.start` 消息,与版本无关,
也不碰 StaticFiles 自己的 ETag / Range 逻辑。
"""
async def wrapped(scope, receive, send):
if scope["type"] != "http":
await asgi(scope, receive, send)
return
async def send_headers(message):
if message["type"] == "http.response.start":
raw = list(message["headers"])
if not any(k.lower() == b"cache-control" for k, _ in raw):
raw.append((b"cache-control", value.encode("latin-1")))
message = {**message, "headers": raw}
await send(message)
await asgi(scope, receive, send_headers)
return wrapped
def spa_assets_app(dist: Path):
"""`/assets` 的 ASGI 子应用:StaticFiles + 长期缓存 + gzip。
和 `spa_target()` 一样单独成函数:这段只在 `SERVE_FRONTEND` 打开时注册,
纯 API 模式的自检一次都跑不到它,测试只能拿函数自己拼一个壳来验。
"""
files = with_cache_control(StaticFiles(directory=dist / "assets"), SPA_ASSET_CACHE)
return GZipMiddleware(files, minimum_size=SPA_GZIP_MINIMUM, compresslevel=SPA_GZIP_LEVEL)
# ------------------------------------------------------------------ 前端产物托管
# 判定逻辑在 app/config.py:Settings.frontend_dist —— 鉴权中间件要问同一个问题,
# 而 api 是被本模块反向导入的,放这里会撞循环导入。
@ -121,11 +269,13 @@ if FRONTEND_DIST is not None:
# React Router 用的是 history 模式(browser history),/projects/3 这类深链在磁盘上没有对应文件,
# 必须回 index.html 交给前端路由,否则用户刷新一次就 404。
if (FRONTEND_DIST / "assets").is_dir():
app.mount("/assets", StaticFiles(directory=FRONTEND_DIST / "assets"), name="spa-assets")
app.mount("/assets", spa_assets_app(FRONTEND_DIST), name="spa-assets")
@app.get("/{full_path:path}", include_in_schema=False)
async def spa(full_path: str) -> FileResponse:
return FileResponse(spa_target(FRONTEND_DIST, full_path))
# 壳每次回源校验(见 §交付面 ①);带哈希的 chunk 走上面那条挂载长期缓存。
return FileResponse(spa_target(FRONTEND_DIST, full_path),
headers={"Cache-Control": SPA_SHELL_CACHE})
logger.info("前端产物已托管:%s(SERVE_FRONTEND=%s)", FRONTEND_DIST, settings.serve_frontend)

View File

@ -0,0 +1,235 @@
"""交付面:按 content-type 的 gzip(阶段 30)。
立项依据(阶段 29 两把尺):首访过网 1 292 834 B 里 `/api` 占 773 646 B,是当时唯一没压的一族;
但同一个路径前缀下 JSON 能省 83.4 %、`thumb/*.png` 反而 +1.1 % ⇒ 判据只能是 media type,
不能是路径前缀。所以这里逐条锁死「什么被压、什么必须原样、压完必须等价」:
· 文本族(JSON / CSV / 纯文本导出 / SVG / JS)达阈值 ⇒ gzip;
· 二进制(PNG 缩略图、video/mp4 交付片)⇒ **一个字节都不许动**,
尤其是 mp4:Starlette 压完会删 `Content-Length`,播放器靠它算 Range 进度条;
· 阈值以下、客户端不收 gzip、上游已经压过 ⇒ 原样透传,绝不冒充 `Content-Encoding`;
· 压完解压回来必须与原文逐字节相同,`Vary` 必须含 accept-encoding(否则中间缓存会串味)。
与被测代码同一把尺的常量从 `app.main` 导入,不在这儿抄第二份数字。
"""
from __future__ import annotations
import gzip
import pytest
from fastapi import FastAPI, Request
from fastapi.responses import (FileResponse, JSONResponse, PlainTextResponse, Response,
StreamingResponse)
from fastapi.testclient import TestClient
from app.main import (GZIP_LEVEL, GZIP_MINIMUM, ContentTypeGZipMiddleware,
gzip_eligible)
# 中文正文:JSON 里带 CJK 时 gzip 的相对收益更高(UTF-8 一个汉字 3 B),与真实列表接口同形状
BIG = ('{"shots":[' + '{"title":"深夜面馆","line":"最后一盏灯"},' * 400 + "]}").encode("utf-8")
SMALL = b'{"ok":true}'
# 已压过的位图:gzip 它只会变大(阶段 29 实测 +1.1 %),拿真实字节形状做断言
WEBP = b"RIFF" + (36 + 4096).to_bytes(4, "little") + b"WEBPVP8 " + bytes(range(256)) * 16
@pytest.fixture()
def client(tmp_path):
"""一个只装被测中间件的小 app:形状对齐真实端点,不牵进鉴权与数据库。"""
app = FastAPI()
app.add_middleware(ContentTypeGZipMiddleware, minimum_size=GZIP_MINIMUM,
compresslevel=GZIP_LEVEL)
png = tmp_path / "thumb.png"
# 高度不可压的二进制(gzip 压它只会变大),模拟 /api/media/thumb/*.png
png.write_bytes(bytes(range(256)) * 400)
mp4 = tmp_path / "final.mp4"
mp4.write_bytes(bytes(range(256)) * 200)
@app.get("/api/projects")
def projects(): # 大 JSON:/api/projects 的形状
return JSONResponse({"raw": BIG.decode()})
@app.get("/api/meta")
def meta():
return JSONResponse({"options": ["x"], "ok": True})
@app.get("/api/export.csv")
def csv_export():
return PlainTextResponse(BIG.decode(), media_type="text/csv; charset=utf-8")
@app.get("/api/thumb.png")
def thumb():
return FileResponse(png, media_type="image/png")
@app.get("/api/download.mp4")
def download():
return FileResponse(mp4, media_type="video/mp4")
@app.get("/api/tiny")
def tiny():
return Response(SMALL, media_type="application/json")
@app.get("/api/pre-encoded")
def pre_encoded():
return Response(gzip.compress(SMALL), media_type="application/json",
headers={"Content-Encoding": "gzip",
"Content-Length": str(len(gzip.compress(SMALL)))})
@app.post("/api/no-content")
def no_content():
return Response(status_code=204)
@app.get("/api/stream")
def stream():
return JSONResponse({"a": 1}, headers={"Content-Type": "text/event-stream"})
@app.get("/api/stream-json")
def stream_json():
# 与真实接口的唯一差别就是分块:用来暴露 minimum_size 在流式下不生效
return StreamingResponse(iter([SMALL]), media_type="application/json")
@app.get("/api/stream-webp")
def stream_webp():
return StreamingResponse(iter([WEBP]), media_type="image/webp")
return TestClient(app)
def gz(r):
return r.headers.get("content-encoding", "")
def accept_gzip():
return {"Accept-Encoding": "gzip, deflate, br"}
# ---------------------------------------------------------------- 该压的必须压
def test_large_json_is_gzipped_and_decodes_identical(client):
r = client.get("/api/projects", headers=accept_gzip())
assert r.status_code == 200
assert gz(r) == "gzip", "大 JSON 没压 ⇒ 首屏最大的一笔字节白过网"
assert "accept-encoding" in r.headers.get("vary", "").lower(), "缺 Vary ⇒ 共享缓存会把 gzip 发给不收它的客户端"
assert r.json() == {"raw": BIG.decode()}, "解压后必须与原文等价"
def test_text_exports_are_gzipped(client):
r = client.get("/api/export.csv", headers=accept_gzip())
assert gz(r) == "gzip"
assert r.content == BIG
# ---------------------------------------------------------------- 不该压的一律别动
def test_png_thumbnail_is_untouched(client):
"""缩略图压完是 +1.1 %(阶段 29 实测),而且会丢掉 Content-Length。"""
r = client.get("/api/thumb.png", headers=accept_gzip())
assert gz(r) == ""
assert int(r.headers["content-length"]) == len(r.content) == 400 * 256
def test_video_range_request_keeps_content_length_and_status(client):
"""播放器 seek:206 + Content-Range + 切片长度,一个头都不能被压缩层动过。"""
r = client.get("/api/download.mp4", headers=dict(accept_gzip(), Range="bytes=100-199"))
assert r.status_code == 206
assert gz(r) == ""
assert r.headers["content-range"] == "bytes 100-199/51200"
assert int(r.headers["content-length"]) == 100 == len(r.content)
assert r.headers.get("accept-ranges") == "bytes"
def test_small_response_below_threshold_is_not_compressed(client):
r = client.get("/api/tiny", headers=accept_gzip())
assert gz(r) == "" and r.content == SMALL
assert int(r.headers["content-length"]) == len(SMALL)
def test_client_without_gzip_support_gets_identity(client):
"""不收 gzip 的客户端必须拿到原文,且**不能**看到 content-encoding。"""
r = client.get("/api/projects", headers={"Accept-Encoding": "identity"})
assert gz(r) == ""
assert r.json() == {"raw": BIG.decode()}
assert int(r.headers["content-length"]) == len(r.content)
def test_already_encoded_response_is_not_double_compressed(client):
"""`/assets` 那一层自带 gzip,外层必须认出来并透传(叠两层 = 解压只剥一层)。"""
r = client.get("/api/pre-encoded", headers=accept_gzip())
assert r.headers["content-encoding"].lower().count("gzip") == 1
assert r.json() == {"ok": True}
def test_204_has_no_body_and_no_encoding(client):
r = client.post("/api/no-content", headers=accept_gzip())
assert r.status_code == 204 and gz(r) == "" and r.content == b""
def test_event_stream_is_never_buffered(client):
"""SSE 攒成块就失去实时性(本仓现在没有,但判据要挡住将来加的人)。"""
r = client.get("/api/stream", headers=accept_gzip())
assert gz(r) == ""
# ------------------------------------------------- 流式分支:minimum_size 管不到,只有 media type 管得到
# 阶段 30 的 A/B(`reports/ui_evidence/nex-p30/apigate.log`)在真 app 上量到的:
# `/api/exports/77` 只有 742 B、字幕 834 B,都在阈值以下却仍然被压了。
# 原因在 starlette 0.46.2 `gzip.py`:`minimum_size` 只挡「一条 body 消息且 more_body=False」
# 的一次性响应;真 app 的路由都坐在鉴权 `BaseHTTPMiddleware` 里面,它的 body 是分块转发的
# (首条 more_body=True)⇒ 走流式分支,不看体积。
# 这不是缺陷(量到的每条小 JSON 都还是变小了:742→497、834→458),但意味着
# **二进制的安全完全靠 content-type 判据,体积阈值保护不了它** —— 下面两条把这个语义钉住。
def test_streaming_small_json_is_compressed_documents_threshold_semantics(client):
"""流式小 JSON:体积阈值不生效,照样压(与真 app 里 742 B 的 /api/exports/77 同形)。"""
r = client.get("/api/stream-json", headers=accept_gzip())
assert gz(r) == "gzip"
assert r.content == SMALL
def test_streaming_webp_thumbnail_is_still_untouched(client):
"""缩略图走的正是流式:压不压只由 media type 决定,这条是二进制的安全边界。
这里不比具体的 Content-Length(`StreamingResponse` 本来就不发它,真 thumb 路由用的
`FileResponse` 才发),比的是**同一个端点在两种 Accept-Encoding 下头必须一模一样**:
压缩层对不该压的响应必须完全隐形,一个头都不许多加、不许改写。
"""
a = client.get("/api/stream-webp", headers=accept_gzip())
b = client.get("/api/stream-webp", headers={"Accept-Encoding": "identity"})
assert gz(a) == "", "流式二进制被压 ⇒ thumb 白烧 CPU 还变大"
assert a.content == WEBP == b.content
assert dict(a.headers) == dict(b.headers), "压缩层动了不该动的响应头"
# ---------------------------------------------------------------- 判据本身
@pytest.mark.parametrize("ct,want", [
("application/json", True),
("application/json; charset=utf-8", True),
("text/plain; charset=utf-8", True),
("text/csv; charset=utf-8", True),
("text/html", True),
("application/javascript", True),
("image/svg+xml", True),
("text/event-stream", False),
("image/png", False),
("video/mp4", False),
("audio/mpeg", False),
("application/zip", False),
("application/octet-stream", False),
("", False),
])
def test_gzip_eligible_matrix(ct, want):
assert gzip_eligible(ct) is want
def test_registered_inside_auth_so_the_size_threshold_is_real():
"""小 app 证明行为,这一条钉真 app 的挂载位置:**压缩层在鉴权之内**,
不是越靠外越好。
阶段 30 先把它挂在最外层,结果 `BaseHTTPMiddleware` 的分块转发让每一个响应
都以 `more_body=True` 进来 ⇒ `GZIP_MINIMUM` 整体失效,4 个 <1 kB 的哈希 chunk
被压(A/B 读数 `reports/ui_evidence/nex-p30/servecheck.log`),与项目自己声明的
1 kB 底线(`SPA_GZIP_MINIMUM`、nginx `gzip_min_length`)冲突。顺序写反就是回归。
"""
from app.main import app
from starlette.middleware.base import BaseHTTPMiddleware
from fastapi.middleware.cors import CORSMiddleware
chain = [m.cls for m in app.user_middleware]
assert chain == [CORSMiddleware, BaseHTTPMiddleware, ContentTypeGZipMiddleware], chain

View File

@ -13,7 +13,7 @@ from fastapi.responses import FileResponse
from fastapi.testclient import TestClient
from app.config import settings
from app.main import spa_target
from app.main import (SPA_ASSET_CACHE, SPA_SHELL_CACHE, spa_assets_app, spa_target)
@pytest.fixture()
@ -23,6 +23,9 @@ def dist(tmp_path):
(build / "assets").mkdir(parents=True)
(build / "index.html").write_text("<!doctype html><title>spa</title>", encoding="utf-8")
(build / "assets" / "index-BRtW2Q.js").write_text("console.log(1)", encoding="utf-8")
# 交付面用例要一份「真会被压」的文本资源:比 SPA_GZIP_MINIMUM(1024B) 大且高度可压,
# 模拟 Vite 那个 1 144 kB 的哈希 chunk 的形状。
(build / "assets" / "vendor-CjO7q3ay.js").write_text("console.log('nex');" * 600, encoding="utf-8")
# 手册正文搬进 React 后,public/help/ 只剩截图目录:页面本身要回落,图片要直出
(build / "help").mkdir()
(build / "help" / "overview.png").write_text("PNG", encoding="utf-8")
@ -101,3 +104,42 @@ def test_frontend_dist_resolution(monkeypatch, tmp_path, dist):
monkeypatch.setattr(settings, "frontend_dist_dir", "frontend/dist")
resolved = settings.frontend_dist()
assert resolved is not None and resolved.is_absolute() and resolved.name == "dist"
def test_asset_delivery_cache_and_gzip(dist):
"""交付面:带哈希的 chunk 长期缓存并 gzip,壳每次回源校验。
这条锁的是 Bundle 优化的**另一半**:前面十几轮量的是文件字节(`chunkinfo`),
但线上真正过网的是这一层的响应头。三条断言各自对应一个会真实发生的事故:
① 不压 ⇒ 1 144 kB 的 chunk 按 raw 发,量好的 gzip 450 kB 白量;
② 不给 `index.html` 回源校验 ⇒ 发版后老标签页拿旧壳引已经不存在的哈希文件(白屏);
③ 反过来给小文件也压 ⇒ 压完加头比原文还大,还多一个 `Vary` 命中率。
"""
shell = FastAPI()
shell.mount("/assets", spa_assets_app(dist))
@shell.get("/{full_path:path}", include_in_schema=False)
async def spa(full_path: str):
return FileResponse(spa_target(dist, full_path), headers={"Cache-Control": SPA_SHELL_CACHE})
client = TestClient(shell)
big = "/assets/vendor-CjO7q3ay.js"
gz = client.get(big, headers={"Accept-Encoding": "gzip"})
assert gz.status_code == 200
assert gz.headers["cache-control"] == SPA_ASSET_CACHE
assert gz.headers["content-encoding"] == "gzip"
assert "accept-encoding" in gz.headers["vary"].lower()
# httpx 会替我们解回来:解完必须与磁盘上的原文一字不差(压坏了要能在这里抓到)
assert gz.text == (dist / "assets" / "vendor-CjO7q3ay.js").read_text(encoding="utf-8")
# 不支持 gzip 的老客户端:原文直出,别留一个骗人的 content-encoding。
# 必须显式写 identity —— httpx 自己默认就带 `Accept-Encoding: gzip, deflate`,
# 不写的话这条测的是「中间件压了」而不是「客户端没要」。
plain = client.get(big, headers={"Accept-Encoding": "identity"})
assert "content-encoding" not in plain.headers and plain.headers["cache-control"] == SPA_ASSET_CACHE
assert plain.text == (dist / "assets" / "vendor-CjO7q3ay.js").read_text(encoding="utf-8")
# 小于阈值的哈希文件不压
tiny = client.get("/assets/index-BRtW2Q.js", headers={"Accept-Encoding": "gzip"})
assert "content-encoding" not in tiny.headers
# 壳与深链:每次回源
for path in ("/", "/projects/3/storyboard"):
assert client.get(path).headers["cache-control"] == SPA_SHELL_CACHE

View File

@ -4,5 +4,36 @@ server {
location /media/ { proxy_pass http://api:8000/media/; proxy_set_header Host $host; }
location /docs { proxy_pass http://api:8000/docs; }
location /openapi.json { proxy_pass http://api:8000/openapi.json; }
location / { try_files $uri $uri/ /index.html; }
# ---- 交付面(与后端 backend/app/main.py 的 SPA 托管同一套口径,两边不要各自发明)----
# 首屏闭包 1 469 kB 里 1 144 kB 是一个带哈希的 JS chunk:不压就是按 raw 发,
# 已经量好的 gzip 450 kB 白量了(`node scripts/ui/chunkinfo.mjs`)。
# 只压文本,mp4 / 已经压过的图片交给 `gzip_types` 挡在外面。
gzip on; gzip_vary on; gzip_min_length 1024; gzip_comp_level 6;
gzip_types text/plain text/css text/csv application/javascript application/json
application/xml image/svg+xml;
# 反代这一路的分工,三组合实测在 `reports/ui_evidence/nex-p30/nginx-ab.log`:
# · 后端 `app.main` 自己会先按 media type 压 `/api`,nginx 见到已带 `Content-Encoding`
# 的响应直接透传,不叠第二层,上游那条 `Content-Length` 也原样保住(C 组合);
# · 后端没压时这里兜底压上:A 组合(上游=阶段 29 的 main.py)`/api/projects`
# 341 909 → 53 333 B 就是 nginx 自己压的。
# 权威的那张文本族名单在后端 `app.main.gzip_eligible`,这里这份是兜底,
# 两边都只认 media type、不认路径前缀。
# `gzip_proxied` 管的是**带 `Via` 请求头的请求**(nginx 站在另一层代理/CDN 后面时),
# 跟「响应是不是来自上游」无关:默认 `off` 下直连浏览器照样压 —— A(无本行)与 B(有本行)
# 六个样本逐字段相同。开它是为了挂 CDN 时这套压缩不整块失效,
# 别把它当成「`/api` 有压缩」的原因,那个原因在上一段。
gzip_proxied any;
# Vite 的产物名带内容哈希 ⇒ 缓存一年;index.html 反过来必须每次回源校验,
# 否则发版后老标签页拿着旧壳去引已经不存在的哈希文件,用户看到白屏。
location /assets/ {
# 只留 add_header 这一条:再写 `expires 1y;` 会额外发一条 Cache-Control,
# 语法上合法(RFC 9110 允许逗号合并),但两个来源迟早会各改一半。
add_header Cache-Control "public, max-age=31536000, immutable" always;
try_files $uri =404;
}
location = /index.html { add_header Cache-Control "no-cache" always; }
# history 回落发出去的也是壳,别让它被缓存住。
location / { add_header Cache-Control "no-cache" always; try_files $uri $uri/ /index.html; }
}