From 9721e32b58256163339e996ce897d68672575f0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B4=AE=E7=94=9F=EF=BC=88=E5=AD=90=E8=99=9A=EF=BC=89?= <2234839456@qq.com> Date: Wed, 4 Nov 2026 20:12:42 +0800 Subject: [PATCH] =?UTF-8?q?feat(rust):=20=E5=AD=97=E4=BD=93=E8=A7=A3?= =?UTF-8?q?=E6=9E=90=E4=BD=93=E7=A9=BA=E9=97=B2=E5=8D=B8=E8=BD=BD=E2=80=94?= =?UTF-8?q?=E2=80=94FONT=5FIDLE=5FUNLOAD=5FSECONDS=20=E7=A7=92=E6=9C=AA?= =?UTF-8?q?=E4=BD=BF=E7=94=A8=E5=8D=B3=E9=87=8A=E6=94=BE=E5=86=85=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - FontCache 条目带 last_used,命中刷新;后台线程每 60s 扫描卸载空闲条目 - 默认 1800s,置 0 关闭;正在写出的响应持 Arc 快照不受影响 - 服务器 1.7G 内存下冷门大字体不再长期驻留,代价是再次访问重付一次读盘+解析 --- package.json | 2 +- rust-spike/src/cache.rs | 29 +++++++++++++++++++++++------ rust-spike/src/main.rs | 18 ++++++++++++++++++ 3 files changed, 42 insertions(+), 7 deletions(-) diff --git a/package.json b/package.json index eb639a8..3dcae73 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/rust-spike/src/cache.rs b/rust-spike/src/cache.rs index e70f216..40180e5 100644 --- a/rust-spike/src/cache.rs +++ b/rust-spike/src/cache.rs @@ -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, + last_used: Instant, +} + /// 预解析字体缓存:path → 解析好的 Font(只读共享,Arc 派发) +/// 空闲超过阈值的条目由后台线程卸载释放内存(再次访问重付一次读盘+解析) pub struct FontCache { - map: Mutex>>, + map: Mutex>, } 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, 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 版) diff --git a/rust-spike/src/main.rs b/rust-spike/src/main.rs index 9bb3080..3cc4689 100644 --- a/rust-spike/src/main.rs +++ b/rust-spike/src/main.rs @@ -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}");