`<head>` 里那个指向 fonts.googleapis.com 的阻塞样式表,在连不上 Google 的机器上会一路
挂到连接超时;而它**后面**的 `<script type="module">` 必须等它 —— 于是整个 React 应用
在这 20 秒里一个请求都发不出去。从浏览器里看,就是「所有接口都卡了 20 秒」。
用 Playwright 复现(把字体请求挂住 20 秒再失败):
字体请求 20014ms
DOM 就绪 20.070s
首个接口请求 导航后 20055ms
把字体请求掐掉之后:DOM 就绪 0.058s,首个接口请求 58ms。
字体栈里 Inter / JetBrains Mono 后面本来就跟着 system-ui / Consolas,缺字体只是回退,
不影响可用性 —— 何况内网这台机器从来就没成功加载到过它们,当前显示的一直是回退字体。
所以这是一个视觉上零变化、却省掉 20 秒白屏的修复。
tests/test_static_cache.py 加了断言,禁止外壳再出现任何外网 link/script。
83 lines
3.0 KiB
Python
83 lines
3.0 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""前端产物的缓存头。
|
||
|
||
**`index.html` 必须 no-cache。** 它没有内容哈希,一旦被浏览器启发式缓存住,打开的还是
|
||
上一次那份 index.html、指向上一次那个 js 包 —— 现象就是「代码明明发了,界面上却看不见
|
||
新功能」,只能靠 Ctrl+F5 自救。这个坑真的踩过:加完功能在设置页里找不到入口,查了半天
|
||
源码,最后发现是浏览器拿着旧包。
|
||
|
||
带哈希的 `/assets/` 反过来,可以放心让它永久缓存。
|
||
"""
|
||
|
||
import pathlib
|
||
import re
|
||
|
||
import pytest
|
||
from fastapi.testclient import TestClient
|
||
|
||
from api.main import app
|
||
|
||
# 产物是 gitignore 的:没构建过就没有静态文件可测(部署机器上一定有)。
|
||
INDEX = pathlib.Path("api/webui/index.html")
|
||
ASSETS = pathlib.Path("api/webui/assets")
|
||
|
||
needs_build = pytest.mark.skipif(
|
||
not INDEX.exists(), reason="前端产物没构建过,测不了静态文件的缓存头"
|
||
)
|
||
|
||
|
||
@pytest.fixture
|
||
def client():
|
||
with TestClient(app) as test_client:
|
||
yield test_client
|
||
|
||
|
||
@needs_build
|
||
def test_the_entry_page_is_never_cached(client):
|
||
response = client.get("/")
|
||
|
||
assert response.status_code == 200
|
||
assert response.headers["cache-control"] == "no-cache"
|
||
|
||
|
||
@needs_build
|
||
def test_hashed_bundles_are_cached_forever(client):
|
||
"""文件名带内容哈希,变了就是新 URL —— 没有理由每次回源。"""
|
||
bundle = next(ASSETS.glob("*.js"), None)
|
||
if bundle is None:
|
||
pytest.skip("没有 js 产物")
|
||
|
||
response = client.get(f"/assets/{bundle.name}")
|
||
|
||
assert response.status_code == 200
|
||
assert response.headers["cache-control"] == "public, max-age=31536000, immutable"
|
||
|
||
|
||
def test_api_responses_are_left_alone(client):
|
||
"""接口那套缓存由客户端和 React Query 管,这里不该插手。"""
|
||
response = client.get("/api/health")
|
||
|
||
assert response.status_code == 200
|
||
assert response.headers.get("cache-control") is None
|
||
|
||
|
||
def test_the_shell_pulls_nothing_from_the_internet():
|
||
"""外壳(index.html)里不能出现任何指向外网的 link/script。
|
||
|
||
真踩过:`<head>` 里挂了一个 fonts.googleapis.com 的阻塞样式表,而这套东西是
|
||
**内网部署**,那台机器连不上 Google。样式表拿不到,它后面的
|
||
`<script type="module">` 就不执行 —— 整个 React 应用一个请求都发不出去,
|
||
页面白白卡满一次 TCP 连接超时。实测(Playwright,把字体请求挂住 20 秒):
|
||
|
||
DOM 就绪 20.070s,首个接口请求出现在导航后 20055ms
|
||
|
||
而字体栈里 Inter / JetBrains Mono 后面本来就跟着 system-ui / Consolas,
|
||
缺字体只是回退,不影响可用性。为装饰性字体拖住整页 20 秒,不值得。
|
||
"""
|
||
html = pathlib.Path("webui/index.html").read_text(encoding="utf-8")
|
||
|
||
external = re.findall(
|
||
r'<(?:link|script)\b[^>]*\b(?:href|src)="(?:https?:)?//[^"]*"', html
|
||
)
|
||
assert external == [], f"外壳引用了外网资源,内网部署会卡在它上面:{external}"
|