崮生(子虚) 7a2e8dc209 feat(双端): P95/P99 延迟可观测 + woff2 编码移出闸门 + stats 防抖 dirty 化 (1.15.6)
- 双端: 子集请求耗时环形缓冲(1024) + /api/stats 输出 latencySamples/P50/P95/P99
- rust: woff2 编码移出内存闸门,闸门只管读盘+解析+裁剪
- TS: markStatsDirty 改传快照函数,落盘时才拷贝(对齐 rust dirty 模式)
- rust: 修复环形未满时零值掺入分位的 bug
2026-11-04 21:23:15 +08:00

53 lines
2.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { jsonResponse, stats, subsetCache, fontBufferCache, markStatsDirty, latencySnapshot } from "../shared";
/** GET /api/stats — 返回运行时统计 */
export async function handleStats(req: Request, _res: Response) {
return {
req,
res: jsonResponse({
uptime: Math.floor((Date.now() - stats.startTime) / 1000),
totalRequests: stats.totalRequests,
subsetRequests: stats.subsetRequests,
subsetCacheHits: stats.subsetCacheHits,
totalChars: stats.totalChars,
tempUploads: stats.tempUploads,
offlineSubsets: stats.offlineSubsets,
offlineDownloads: stats.offlineDownloads,
subsetCacheEntries: subsetCache.size,
fontBufferCacheEntries: fontBufferCache.size,
/** 最近 1024 次子集请求耗时分位(毫秒,进程级观测) */
...latencySnapshot(),
}),
};
}
/** 允许上报的匿名事件类型 —— 白名单校验,防止任意字段注入 */
const OFFLINE_EVENTS = new Set(["offline_subset", "offline_download"]);
/**
* POST /api/stats/event — 离线裁剪匿名事件上报
*
* 离线裁剪完全在浏览器端完成,字体和文字均不经过服务器。
* 这里只接收事件类型并累计计数,不记录任何内容数据,隐私无损。
* 请求体:{ event: "offline_subset" | "offline_download" }
*/
export async function handleStatsEvent(req: Request, _res: Response) {
try {
/** 服务器把 body 挂在 _bodyBuffer 上(LLRT 下手写 Request 不支持 req.json()) */
const buf = (req as Request & { _bodyBuffer?: ArrayBuffer })._bodyBuffer;
if (!buf || buf.byteLength === 0) {
return { req, res: jsonResponse({ success: false, error: "请求体为空" }, 400) };
}
const body = JSON.parse(new TextDecoder().decode(buf)) as { event?: string };
if (!body || typeof body.event !== "string" || !OFFLINE_EVENTS.has(body.event)) {
return { req, res: jsonResponse({ success: false, error: "unknown event" }, 400) };
}
if (body.event === "offline_subset") stats.offlineSubsets++;
else stats.offlineDownloads++;
markStatsDirty();
return { req, res: jsonResponse({ success: true }) };
} catch {
return { req, res: jsonResponse({ success: false, error: "invalid body" }, 400) };
}
}