perf(双端): 字体目录清单 TTL 缓存——find_font_path 模糊匹配与 /api/fonts 共享

- 原 find 模糊匹配每请求 readdir+逐项 stat,成本随字体数线性增长(线上 find 4ms)
- rust: misc::font_dir_listing 5s TTL + Arc 共享;精确匹配不缓存(新上传字体立即可见);
  上传成功主动失效;collect_gids/seed_gids 的 O(n²) contains 改定长位图
- ts: shared.fontDirListing 同设计;findFontPath/routes fonts/upload 失效同步
- 回归:51 测试过;3 字体×3 文本新旧产物 sha256 一致;/api/fonts 输出 diff 为空;
  线上二次模糊匹配 find 4ms→0ms
This commit is contained in:
崮生(子虚) 2026-11-04 21:05:42 +08:00
parent 6c1d304baf
commit e15f96294b
7 changed files with 158 additions and 83 deletions

View File

@ -1,21 +1,8 @@
import { jsonResponse } from "../shared";
import { readdir } from "../interface";
import { fontDirs } from "../config";
import { jsonResponse, fontDirListing } from "../shared";
/** GET /api/fonts — 列出所有可用字体 */
/** GET /api/fonts — 列出所有可用字体(走共享目录清单缓存) */
export async function handleListFonts(req: Request, _res: Response) {
const allFonts: Array<{ name: string; temporary: boolean }> = [];
for (const dir of fontDirs) {
try {
const entries = await readdir(dir);
for (const entry of entries) {
if (entry.isFile() && /\.(ttf|otf|woff|woff2)$/i.test(entry.name)) {
allFonts.push({ name: entry.name, temporary: dir === "font/temp" });
}
}
} catch {}
}
const entries = await fontDirListing();
const allFonts = entries.map((e) => ({ name: e.name, temporary: e.dir === "font/temp" }));
return { req, res: jsonResponse(allFonts) };
}

View File

@ -103,6 +103,50 @@ export const subsetCache = new LruCache<SubsetCacheEntry>({
sizeFn: (v) => v.bytes.byteLength * (v.ttf ? 17 : 1),
});
/** 字体目录清单条目:模糊匹配键 + 列表输出共享 */
interface FontDirEntry {
/** 去扩展名小写 stem(前缀/包含匹配键) */
stem: string;
/** 原始文件名(/api/fonts 输出) */
name: string;
/** 所在目录 */
dir: string;
}
/** 目录清单缓存(5s TTL):消除每请求 readdir + 逐项判定的成本(随字体数线性增长)。
* 上传/删除后主动失效(invalidateFontDirCache);精确匹配不走此缓存,新上传字体立即可见 */
const FONT_DIR_CACHE_TTL = 5_000;
let fontDirCache: { at: number; entries: FontDirEntry[] } | null = null;
/** 上传/删除字体后主动失效(下一次任何查找立即重建清单) */
export function invalidateFontDirCache(): void {
fontDirCache = null;
}
/** 取字体目录清单(TTL 内复用),findFontPath 模糊匹配与 /api/fonts 共享 */
export async function fontDirListing(): Promise<FontDirEntry[]> {
if (fontDirCache && Date.now() - fontDirCache.at < FONT_DIR_CACHE_TTL) {
return fontDirCache.entries;
}
const entries: FontDirEntry[] = [];
for (const dir of fontDirs) {
try {
const list = await readdir(dir);
for (const entry of list) {
if (entry.isFile() && /\.(ttf|otf|woff|woff2)$/i.test(entry.name)) {
entries.push({
stem: entry.name.replace(/\.[^.]+$/, "").toLowerCase(),
name: entry.name,
dir,
});
}
}
} catch {}
}
fontDirCache = { at: Date.now(), entries };
return entries;
}
/**
* 在所有字体目录中查找字体文件
* 匹配优先级:精确匹配 > 前缀匹配 > 包含匹配
@ -116,29 +160,16 @@ export async function findFontPath(filename: string): Promise<string | null> {
} catch {}
}
const allFonts: Array<{ basename: string; path: string }> = [];
for (const dir of fontDirs) {
try {
const entries = await readdir(dir);
for (const entry of entries) {
if (entry.isFile() && /\.(ttf|otf|woff|woff2)$/i.test(entry.name)) {
allFonts.push({
basename: entry.name.replace(/\.[^.]+$/, ""),
path: path_join(dir, entry.name),
});
}
}
} catch {}
}
const allFonts = await fontDirListing();
const query = filename.replace(/\.[^.]+$/, "").toLowerCase();
for (const f of allFonts) {
if (f.basename.toLowerCase().startsWith(query)) return f.path;
if (f.stem.startsWith(query)) return path_join(f.dir, f.name);
}
for (const f of allFonts) {
if (f.basename.toLowerCase().includes(query)) return f.path;
if (f.stem.includes(query)) return path_join(f.dir, f.name);
}
return null;

View File

@ -1,4 +1,5 @@
import { writeFile, unlink, readdir, stat, mkdir, path_join } from "./interface";
import { invalidateFontDirCache } from "./shared";
import { enableTempUpload, adminApiKey, tempMaxFiles, tempMaxTotalSize } from "./config";
/** 允许的字体文件扩展名 */
@ -101,6 +102,7 @@ export async function handleTempUpload(fileData: { data: Uint8Array; filename: s
}
await writeFile(filePath, fileData.data);
invalidateFontDirCache();
return { success: true };
}
@ -124,5 +126,6 @@ export async function handleAdminUpload(
const filename = sanitizeFilename(fileData.filename);
await writeFile(path_join("font/admin", filename), fileData.data);
invalidateFontDirCache();
return { success: true };
}

View File

@ -1,7 +1,7 @@
{
"name": "webfont",
"private": true,
"version": "1.15.4",
"version": "1.15.5",
"type": "module",
"scripts": {
"dev": "pnpx tsx scripts/dev-all.ts",

View File

@ -546,7 +546,7 @@ fn ms(from: Instant, to: Instant) -> u128 {
/// 在所有字体目录中查找字体文件(对译 findFontPath:精确 > 前缀 > 包含,大小写不敏感,扩展名剥除比较)
pub(crate) fn find_font_path(dirs: &[String], name: &str) -> Option<String> {
// 精确匹配
// 精确匹配(不缓存:直 stat,新上传字体立即可见)
for dir in dirs {
let p = format!("{dir}/{name}");
if let Ok(md) = std::fs::metadata(&p) {
@ -555,36 +555,18 @@ pub(crate) fn find_font_path(dirs: &[String], name: &str) -> Option<String> {
}
}
}
// 扫描目录收集(basename 剥扩展名 + 小写)
let mut all: Vec<(String, String)> = Vec::new(); // (stem 小写, path)
for dir in dirs {
let Ok(entries) = std::fs::read_dir(dir) else { continue };
for entry in entries.flatten() {
// TS readdir 逐项 stat(跟随符号链接):必须用 std::fs::metadata(stat 语义),
// DirEntry::metadata 是 lstat——symlink 字体(如 /tmp/ssim-fonts 的基准链接)会被误跳过
let Ok(md) = std::fs::metadata(entry.path()) else { continue };
if !md.is_file() {
continue;
}
let fname = entry.file_name();
let Some(fname) = fname.to_str() else { continue };
if !has_font_ext(fname) {
continue;
}
all.push((strip_ext(fname).to_lowercase(), format!("{dir}/{fname}")));
}
}
// 模糊匹配(前缀 > 包含)走共享清单缓存(5s TTL,上传后主动失效):
// 原实现每请求 readdir + 逐项 stat,成本随字体数线性增长(线上实测 find 4ms)
let listing = misc::font_dir_listing(dirs);
let query = strip_ext(name).to_lowercase();
// 前缀匹配
for (stem, path) in &all {
if stem.starts_with(&query) {
return Some(path.clone());
for e in listing.iter() {
if e.stem_lower.starts_with(&query) {
return Some(format!("{}/{}", e.dir, e.fname));
}
}
// 包含匹配
for (stem, path) in &all {
if stem.contains(&query) {
return Some(path.clone());
for e in listing.iter() {
if e.stem_lower.contains(&query) {
return Some(format!("{}/{}", e.dir, e.fname));
}
}
None

View File

@ -814,6 +814,76 @@ fn obj_get<'a>(v: &'a JsonValue, key: &str) -> Option<&'a JsonValue> {
v.get(key)
}
// ===== 字体目录清单缓存(find_font_path 模糊匹配与 /api/fonts 共用)=====
/// 清单条目:模糊匹配键 + 列表输出(main.rs find_font_path 跨模块读取,pub 字段)
pub struct CachedFontEntry {
/// 去扩展名小写 stem(前缀/包含匹配键)
pub stem_lower: String,
/// 原始文件名(/api/fonts 输出)
pub fname: String,
/// 所在目录(路径拼装 + temporary 判定)
pub dir: String,
}
struct FontDirCache {
at: Instant,
key: String,
entries: Arc<Vec<CachedFontEntry>>,
}
/// 短 TTL:上传/删除后的陈旧条目最多存活 5s(成功上传会主动失效,实际窗口更小)
const FONT_DIR_CACHE_TTL: Duration = Duration::from_secs(5);
static FONT_DIR_CACHE: OnceLock<Mutex<Option<FontDirCache>>> = OnceLock::new();
/// 取字体目录清单(5s TTL):消除每请求 readdir + 逐项 stat,成本随字体数增长的问题。
/// 精确匹配不走此缓存(直 stat,新上传字体立即可见);上传/删除成功后主动失效
pub fn font_dir_listing(dirs: &[String]) -> Arc<Vec<CachedFontEntry>> {
let key = dirs.join(":");
let cell = FONT_DIR_CACHE.get_or_init(|| Mutex::new(None));
let mut g = cell.lock().unwrap();
if let Some(c) = g.as_ref() {
if c.key == key && c.at.elapsed() < FONT_DIR_CACHE_TTL {
return c.entries.clone();
}
}
let entries = scan_font_dirs(dirs);
let arc = Arc::new(entries);
*g = Some(FontDirCache { at: Instant::now(), key, entries: arc.clone() });
arc
}
/// 上传/删除字体后主动失效(下一次任何查找立即重建清单)
pub fn invalidate_font_dir_cache() {
if let Some(cell) = FONT_DIR_CACHE.get() {
*cell.lock().unwrap() = None;
}
}
/// 全量扫描目录建清单(readdir + 逐项 stat,symlink 跟随,对齐原实现)
fn scan_font_dirs(dirs: &[String]) -> Vec<CachedFontEntry> {
let mut all = Vec::new();
for dir in dirs {
let Ok(entries) = std::fs::read_dir(dir) else { continue };
for entry in entries.flatten() {
if !entry_is_file(&entry, dir) {
continue;
}
let fname = entry.file_name();
let Some(fname) = fname.to_str() else { continue };
if !crate::has_font_ext(fname) {
continue;
}
all.push(CachedFontEntry {
stem_lower: crate::strip_ext(fname).to_lowercase(),
fname: fname.to_string(),
dir: dir.clone(),
});
}
}
all
}
// ===== GET /api/fonts(对齐 backend/routes/fonts.ts)=====
/// 目录条目判定是否为普通文件(symlink 需跟进一次 metadata,对齐 readdir+statFile 语义)
@ -835,27 +905,17 @@ pub fn handle_list_fonts(
dirs: &[String],
close: bool,
) -> io::Result<bool> {
let listing = font_dir_listing(dirs);
let mut body = String::from("[");
let mut first = true;
for dir in dirs {
let Ok(entries) = std::fs::read_dir(dir) else { continue };
for entry in entries.flatten() {
if !entry_is_file(&entry, dir) {
continue;
}
let fname = entry.file_name();
let Some(fname) = fname.to_str() else { continue };
if !crate::has_font_ext(fname) {
continue;
}
if !first {
body.push(',');
}
first = false;
body.push_str("{\"name\":");
body.push_str(&json_stringify_str(fname));
body.push_str(&format!(",\"temporary\":{}}}", *dir == *"font/temp"));
for e in listing.iter() {
if !first {
body.push(',');
}
first = false;
body.push_str("{\"name\":");
body.push_str(&json_stringify_str(&e.fname));
body.push_str(&format!(",\"temporary\":{}}}", e.dir == "font/temp"));
}
body.push(']');
http::send_json(stream, 200, &body, close)?;
@ -1262,6 +1322,9 @@ pub fn handle_upload(
let auth = get_header(raw_req, "Authorization").unwrap_or("");
let api_key = auth.strip_prefix("Bearer ").unwrap_or(auth);
let result = handle_admin_upload(file.data, &filename, api_key);
if result.success {
invalidate_font_dir_cache();
}
let out = write_upload_result(&result);
http::send_json(stream, if result.success { 200 } else { 403 }, &out, close)?;
return Ok(close);
@ -1270,6 +1333,7 @@ pub fn handle_upload(
let result = handle_temp_upload(file.data, &filename);
if result.success {
stats_record_temp_upload();
invalidate_font_dir_cache();
}
let out = write_upload_result(&result);
http::send_json(stream, if result.success { 200 } else { 400 }, &out, close)?;

View File

@ -380,14 +380,18 @@ impl Font {
}
}
/// 文本涉及的 gid 集(gid 0 始终保留,升序)
/// 文本涉及的 gid 集(gid 0 始终保留,升序)。
/// 去重用定长位图(O(1) 判重,替代 Vec::contains 的 O(n)——长文本时平方复杂度)
pub fn collect_gids(&self, text: &str) -> Result<Vec<u16>, SubsetError> {
let mut gids: Vec<u16> = vec![0];
let mut seen = vec![false; self.num_glyphs as usize + 1];
seen[0] = true;
let glyf = self.find_table(b"glyf");
for ch in text.chars() {
let cp = ch as u32;
if let Some(gid) = self.cmap_get(cp) {
if !gids.contains(&gid) {
if !seen[gid as usize] {
seen[gid as usize] = true;
gids.push(gid);
}
if let Some(g) = glyf {
@ -410,8 +414,11 @@ impl Font {
/// 种子 gid(TS probe 语义):gid 0 + 文本码点首次出现序的 cmap gid。
/// 不排序——插入序决定 TS subsetGids 追加顺序即新 gid 编号,是 GSUB 对拍的前提。
/// 去重用位图(O(1) 判重,见 collect_gids)
fn seed_gids(&self, text: &str) -> Vec<u16> {
let mut seeds: Vec<u16> = vec![0];
let mut seen_gid = vec![false; self.num_glyphs as usize + 1];
seen_gid[0] = true;
let mut seen_cp: HashSet<u32> = HashSet::new();
for ch in text.chars() {
let cp = ch as u32;
@ -419,7 +426,8 @@ impl Font {
continue;
}
if let Some(gid) = self.cmap_get(cp) {
if !seeds.contains(&gid) {
if !seen_gid[gid as usize] {
seen_gid[gid as usize] = true;
seeds.push(gid);
}
}