76 lines
4.7 KiB
Python
76 lines
4.7 KiB
Python
#!/usr/bin/env python3
|
||
"""空闲预热到底抢不抢首屏:节流下做 A/B(同一份 dist,B 组把 4 个预热 chunk 拦掉)。
|
||
|
||
router.tsx 的注释写「只在浏览器空闲时做,绝不和首屏的图片/接口抢带宽」。
|
||
本机实测那 4 个请求 start=66 ms、FCP=160 ms——预热跑在首屏画出来**之前**,
|
||
所以这句话在快网上是靠「本机太快」兜住的,不是靠机制。节流一档才知道会不会真抢。
|
||
|
||
B 组用 page.route 直接 abort 这 4 个 URL(warmupRoutes 里是 .catch(() => undefined),
|
||
拦掉不会报错、也不会影响别的东西),对比 FCP / 首个 /api 响应 / DOMContentLoaded。
|
||
"""
|
||
import os, sys, json
|
||
from playwright.sync_api import sync_playwright
|
||
BASE = os.environ.get("NEX_BASE", "http://127.0.0.1:4173")
|
||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||
WARM = ("AssetLibrary-", "ModelCenter-", "ProjectDetail-", "RecordAudio-")
|
||
COND = {"offline": False, "downloadThroughput": 1_600_000 // 8 * 3, "uploadThroughput": 750_000 // 8 * 3, "latency": 150}
|
||
|
||
def run(block, label):
|
||
with sync_playwright() as pw:
|
||
br = pw.chromium.launch()
|
||
a = br.new_context(viewport={"width": 1440, "height": 900})
|
||
p = a.new_page()
|
||
p.goto(BASE + "/login", wait_until="networkidle")
|
||
if p.locator("#login-user").count():
|
||
p.fill("#login-user", "admin"); p.fill("#login-pass", "admin1234")
|
||
p.click("button[type=submit]"); p.wait_for_timeout(1800)
|
||
st = os.path.join(HERE, "session-ablate.json"); a.storage_state(path=st)
|
||
c = br.new_context(viewport={"width": 1440, "height": 900}, storage_state=st)
|
||
pg = c.new_page()
|
||
ablated = []
|
||
if block:
|
||
def h(r):
|
||
if any(w in r.request.url for w in WARM):
|
||
ablated.append(r.request.url.split("/")[-1]); return r.abort()
|
||
return r.continue_()
|
||
pg.route("**/assets/*.js", h)
|
||
c.set_default_timeout(60000)
|
||
api_first = {}
|
||
def on(r):
|
||
if "/api/" in r.url and "t" not in api_first:
|
||
api_first["t"] = round(r.request.timing.get("responseEnd", -1) if r.request.timing else -1)
|
||
api_first["url"] = r.url.split("?")[0].replace(BASE, "")
|
||
pg.on("response", on)
|
||
client = c.new_cdp_session(pg)
|
||
client.send("Network.enable")
|
||
client.send("Network.emulateNetworkConditions", COND)
|
||
pg.goto(BASE + "/", wait_until="load", timeout=60000)
|
||
pg.wait_for_timeout(6000)
|
||
m = pg.evaluate("""() => { const n = performance.getEntriesByType('navigation')[0] || {};
|
||
const fcp = (performance.getEntriesByName('first-contentful-paint')[0]||{}).startTime || -1;
|
||
const res = performance.getEntriesByType('resource').filter(r=>r.name.includes('/assets/'));
|
||
const api = performance.getEntriesByType('resource').filter(r=>r.name.includes('/api/'));
|
||
return { fcp: Math.round(fcp), dcl: Math.round(n.domContentLoadedEventEnd), load: Math.round(n.loadEventEnd),
|
||
lcp: Math.round(((performance.getEntriesByType('largest-contentful-paint').slice(-1)[0])||{}).startTime||-1),
|
||
assets: res.length, assetRaw: res.reduce((a,r)=>a+r.decodedBodySize,0),
|
||
assetEnd: res.length?Math.round(Math.max(...res.map(r=>r.responseEnd))):-1,
|
||
apiStart: api.length?Math.round(Math.min(...api.map(r=>r.startTime))):-1,
|
||
apiEnd: api.length?Math.round(Math.max(...api.map(r=>r.responseEnd))):-1, apiN: api.length }; }""")
|
||
m["aborted"] = sorted(set(ablated))
|
||
m["label"] = label
|
||
br.close(); return m
|
||
|
||
A = run(False, "A 原样(含空闲预热)")
|
||
B = run(True, "B 拦掉 4 个预热 chunk")
|
||
for m in (A, B):
|
||
print(f"\n=== {m['label']} ===")
|
||
print(f" DCL {m['dcl']} ms · FCP {m['fcp']} ms · LCP {m['lcp']} ms · load {m['load']} ms")
|
||
print(f" 资源数 {m['assets']} · 解压后 {round(m['assetRaw']/1000,2)} kB · 最后一个资源结束 {m['assetEnd']} ms")
|
||
print(f" /api 请求 {m['apiN']} 个 · 最早发起 {m['apiStart']} ms · 最晚结束 {m['apiEnd']} ms")
|
||
if m["aborted"]: print(f" 被拦掉的:{m['aborted']}")
|
||
print(f"\n差值:FCP {B['fcp']-A['fcp']:+d} ms · LCP {B['lcp']-A['lcp']:+d} ms · 资源结束 {B['assetEnd']-A['assetEnd']:+d} ms · "
|
||
f"api 最早发起 {B['apiStart']-A['apiStart']:+d} ms · 字节 -{round((A['assetRaw']-B['assetRaw'])/1000,2)} kB")
|
||
print("注意:预热抢的是**带宽**,本机 150 ms RTT / 6 Mbps 一档下若 FCP/LCP 变好,说明确有竞争;"
|
||
"变差或持平说明这 4 个 chunk 在首屏窗口里没造成可测代价。")
|
||
json.dump({"A": A, "B": B}, open(os.path.join(HERE, "warmablate.json"), "w"), ensure_ascii=False, indent=1)
|