feat(rust): 字体解析体空闲卸载——FONT_IDLE_UNLOAD_SECONDS 秒未使用即释放内存

- FontCache 条目带 last_used,命中刷新;后台线程每 60s 扫描卸载空闲条目
- 默认 1800s,置 0 关闭;正在写出的响应持 Arc 快照不受影响
- 服务器 1.7G 内存下冷门大字体不再长期驻留,代价是再次访问重付一次读盘+解析
This commit is contained in:
崮生(子虚) 2026-11-04 20:12:42 +08:00
parent 19f3095f24
commit 9721e32b58
3 changed files with 42 additions and 7 deletions

View File

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

View File

@ -5,36 +5,53 @@
use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use crate::ttf::Font;
/// 子集缓存默认容量 10MB(SUBSET_CACHE_MAX_SIZE 可覆盖,语义对齐 TS)
pub const DEFAULT_SUBSET_CACHE_MAX_BYTES: usize = 10 * 1024 * 1024;
/// 缓存条目:解析体 + 最后使用时间(空闲卸载判定用)
struct FontEntry {
font: Arc<Font>,
last_used: Instant,
}
/// 预解析字体缓存:path → 解析好的 Font(只读共享,Arc 派发)
/// 空闲超过阈值的条目由后台线程卸载释放内存(再次访问重付一次读盘+解析)
pub struct FontCache {
map: Mutex<HashMap<String, Arc<Font>>>,
map: Mutex<HashMap<String, FontEntry>>,
}
impl FontCache {
#[allow(dead_code)] // /api/stats 接入前未用
pub fn new() -> Self {
FontCache { map: Mutex::new(HashMap::new()) }
}
/// 命中零 IO + 零解析;未命中在锁内读文件并解析(二次检查避免重复解析,对齐 Zig getFont)
/// 命中同时刷新 last_used
pub fn get_or_parse(&self, path: &str) -> Result<Arc<Font>, FontCacheError> {
let mut map = self.map.lock().unwrap();
if let Some(f) = map.get(path) {
return Ok(f.clone());
if let Some(e) = map.get_mut(path) {
e.last_used = Instant::now();
return Ok(e.font.clone());
}
let data = std::fs::read(path).map_err(|_| FontCacheError::NotFound)?;
if data.len() > 100 * 1024 * 1024 {
return Err(FontCacheError::NotFound);
}
let font = Arc::new(Font::parse(data).map_err(|_| FontCacheError::ParseFailed)?);
map.insert(path.to_string(), font);
Ok(map.get(path).unwrap().clone())
map.insert(path.to_string(), FontEntry { font: font.clone(), last_used: Instant::now() });
Ok(font)
}
/** 卸载空闲超过阈值的条目,返回卸载数。正在写出的响应持有 Arc 快照,卸载不影响它 */
pub fn evict_idle(&self, max_idle: Duration) -> usize {
let mut map = self.map.lock().unwrap();
let before = map.len();
map.retain(|_, e| e.last_used.elapsed() < max_idle);
before - map.len()
}
/// 条目数(/api/stats 的 fontBufferCacheEntries 同位字段,口径注释见 Zig 版)

View File

@ -132,6 +132,24 @@ fn run_server() {
// misc 初始化(配置解析/统计恢复/目录创建/后台线程,对齐 zig misc.init 在 listen 之前)
misc::init();
// 字体空闲卸载:FONT_IDLE_UNLOAD_SECONDS 秒未被使用的解析体释放内存(0 = 关闭)
// 内存受限环境(容器限额)下冷门大字体不再长期驻留;再次访问重付一次读盘+解析
let idle_secs: u64 = std::env::var("FONT_IDLE_UNLOAD_SECONDS")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(1800);
if idle_secs > 0 {
let app = app.clone();
eprintln!("[font-idle-unload] 阈值 {idle_secs}s,扫描周期 60s");
std::thread::spawn(move || loop {
std::thread::sleep(std::time::Duration::from_secs(60));
let n = app.fonts.evict_idle(std::time::Duration::from_secs(idle_secs));
if n > 0 {
eprintln!("[font-idle-unload] 卸载 {n} 个空闲字体");
}
});
}
let listener = TcpListener::bind(("0.0.0.0", port)).expect("bind");
let dirs = app.font_dirs.join(":");
eprintln!("webfont-rs listening on {port}, font_dirs={dirs}");