静态资源交给 Cloudflare 边缘缓存(下载提速 41 倍)

实测基线:
  ykxmz-setup-1.8.1.exe   只下到 237568/15067199 字节就停(17 KB/s)
  ykxmz-watch-1.8.1.apk   201523 字节 / 66.8 秒 = 3 KB/s
  ykxmz-server-1.8.1.zip  214900 字节 / 3.1 秒  = 67 KB/s

原因:relay 给所有响应都发 Cache-Control: no-store,
Cloudflare 完全不缓存 —— 每次下载/每张图都要穿隧道回 4G 源站。

改动:
  /download/*   no-store -> public, max-age=604800, immutable
                文件名带版本号,同一名字内容永不改变,可以长缓存
  /             -> public, max-age=60(挡住刷新重复回源)
  /favicon.ico  已是 max-age=86400,保持不变
  /shot/*       已是 max-age=86400,保持不变
  /v1/*         保持 no-store(接口必须实时)

顺带修两个自己踩的坑:

1. _send() 无条件先发 no-store,再追加 extra 里的 Cache-Control,
   结果是**两个 Cache-Control 头**,客户端只认第一个 ——
   调用方传的缓存策略被吃掉。改成 extra 里有就不再发默认值。

2. do_HEAD 和 do_GET 的缓存头不一致:HEAD 对非 /shot/ 一律报 no-store。
   下载器/代理用 HEAD 探测时会误判文件不可缓存。
   现在 _head_info 给每个路由带上和 GET 完全相同的缓存头,
   do_HEAD 也不再盲目覆盖。

结果(同一个测试口径):
  setup.exe  17 KB/s(截断) -> 695 KB/s 完整 15 MB   41 倍
  watch.apk   3 KB/s         -> 101 KB/s              33 倍
  server.zip 67 KB/s         ->  87 KB/s
  三个文件全部 cf-cache-status=HIT(不再穿隧道回源)

排查过程记一笔:我一开始用 curl -I 验证,
看到的全是 no-store —— 因为 **-I 发的是 HEAD**,
而 HEAD 走的是另一个分支。查了半天才发现是验证方法错了。
This commit is contained in:
xmz7891
2026-10-07 15:44:48 +08:00
parent 46196c3618
commit bf15a2ee61
203 changed files with 1789 additions and 40 deletions
+44 -17
View File
@@ -59,7 +59,7 @@ from collections import deque
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
VERSION = "1.8.0"
VERSION = "1.8.1"
# ---------------- 参数(都能用环境变量覆盖)----------------
@@ -901,8 +901,15 @@ class Handler(BaseHTTPRequestHandler):
self.send_response(code)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
for name, value in (extra or {}).items():
# ⚠ 默认 no-store,但**如果调用方在 extra 里给了 Cache-Control,
# 就不要再发默认的了** —— 否则会有两个 Cache-Control 头,
# 客户端/Cloudflare 只看第一个,调用方的设置就被吃掉了。
# (这个坑真踩了:首页明明传了 public,max-age=60,
# 响应里却还是 no-store,Cloudflare 一直 DYNAMIC 不缓存。)
extra = extra or {}
if not any(name.lower() == "cache-control" for name in extra):
self.send_header("Cache-Control", "no-store")
for name, value in extra.items():
self.send_header(name, value)
self.end_headers()
if body:
@@ -1061,13 +1068,16 @@ class Handler(BaseHTTPRequestHandler):
self.send_response(info["status"])
self.send_header("Content-Type", info["ctype"])
self.send_header("Content-Length", str(info["length"]))
for name, value in (info.get("extra") or {}).items():
self.send_header(name, value)
# 静态图可以缓存,跟 GET 那边保持一致
if path.startswith("/shot/"):
self.send_header("Cache-Control", "public, max-age=86400")
else:
extra = info.get("extra") or {}
# ⚠ HEAD 的响应头必须和 GET 一致。
# 否则下载器/代理用 HEAD 探测时会拿到 no-store 和错误的长度,
# 进而误判文件不可缓存、甚至误判成空文件。
# (这个不一致坑过一次:我拿 curl -I 验证 GET 的缓存改动,
# 看到的全是 no-store,白查了半天 —— 因为 -I 发的是 HEAD。)
if not any(name.lower() == "cache-control" for name in extra):
self.send_header("Cache-Control", "no-store")
for name, value in extra.items():
self.send_header(name, value)
self.end_headers()
def _as_bytes(self, value) -> bytes:
@@ -1102,9 +1112,16 @@ class Handler(BaseHTTPRequestHandler):
return {"status": status, "ctype": "text/plain; charset=utf-8",
"length": 0, "extra": {}}
# 各路由必须带上**和 GET 完全一样**的缓存头,否则用 HEAD 探测的
# 下载器/代理会拿到 no-store,误判成不可缓存。
CACHE_SITE = {"Cache-Control": "public, max-age=60"}
CACHE_ICON = {"Cache-Control": "public, max-age=86400"}
CACHE_SHOT = {"Cache-Control": "public, max-age=86400"}
CACHE_DL = {"Cache-Control": "public, max-age=604800, immutable"}
if path == "/":
body = self._as_bytes(_site_page())
return ok("text/html; charset=utf-8", len(body))
return ok("text/html; charset=utf-8", len(body), CACHE_SITE)
if path in ("/v1/health", "/v1/downloads"):
return ok("application/json", 2)
if path in ("/url", "/v1/url"):
@@ -1112,7 +1129,7 @@ class Handler(BaseHTTPRequestHandler):
if path in ("/favicon.ico", "/shot/favicon.ico"):
icon = Path(__file__).resolve().parent / "favicon.ico"
if icon.is_file():
return ok("image/x-icon", icon.stat().st_size)
return ok("image/x-icon", icon.stat().st_size, CACHE_ICON)
return no()
if path == ADMIN_PATH or path == "/admin" or path == "/login":
# 注意:_login_page() 返回的**已经是 bytes**(它的签名是 -> bytes),
@@ -1134,7 +1151,7 @@ class Handler(BaseHTTPRequestHandler):
(".png", ".jpg", ".jpeg", ".webp")):
ctype = ("image/png" if name.lower().endswith(".png")
else "image/jpeg")
return ok(ctype, target.stat().st_size)
return ok(ctype, target.stat().st_size, CACHE_SHOT)
return no()
# ---- 下载区 ----
@@ -1158,9 +1175,10 @@ class Handler(BaseHTTPRequestHandler):
else:
ctype = "application/octet-stream"
quoted = urllib.parse.quote(safe)
return ok(ctype, target.stat().st_size, {
"Content-Disposition":
"attachment; filename*=UTF-8''%s" % quoted})
headers = dict(CACHE_DL)
headers["Content-Disposition"] = (
"attachment; filename*=UTF-8''%s" % quoted)
return ok(ctype, target.stat().st_size, headers)
return no()
@@ -1283,7 +1301,13 @@ class Handler(BaseHTTPRequestHandler):
self.send_header(
"Content-Disposition",
f"attachment; filename*=UTF-8''{quoted}")
self.send_header("Cache-Control", "no-store")
# ★ 让 Cloudflare 在边缘缓存这个文件。
# 原来这里是 no-store,于是每次下载都要穿隧道回 4G 源站 ——
# 实测吞吐只有 3~67 KB/s(15 MB 的安装包根本下不动)。
# 文件名带版本号(ykxmz-setup-1.8.1.exe),同一名字内容
# 永不改变,所以可以放心长缓存。
self.send_header("Cache-Control",
"public, max-age=604800, immutable")
self.end_headers()
# 分块流式发送,不要一次性 read_bytes 再 write ——
@@ -1391,8 +1415,11 @@ class Handler(BaseHTTPRequestHandler):
# ---- 官网首页(公开,不用登录)----
if path == "/":
# 缓存 60 秒:挡住"刷新就重新回源"的浪费,
# 又不会让页面上的当前版本号和下载按钮过期太久。
self._send(200, _site_page().encode("utf-8"),
"text/html; charset=utf-8")
"text/html; charset=utf-8",
{"Cache-Control": "public, max-age=60"})
return
# ---- 管理后台 ----