Skip to main content

yggdrasil/
ssr_cache.rs

1//! SSR 增量渲染缓存失效。
2//!
3//! Dioxus 0.7 增量渲染器把每个路由的 SSR 结果落盘到 `static/<route>/index/<hash>.html`,
4//! 以请求 `path_and_query()` 作 key。它只暴露 `invalidate_after(ttl)` 一个失效手段,
5//! **没有按路由失效的公开 API**。本模块通过**物理删除缓存目录**绕过这个限制:
6//! 写路径(create/update/rebuild/delete)调用 [`invalidate_ssr_route`] 删掉对应路由的
7//! 缓存目录,下次请求触发重渲染。
8//!
9//! 全局世代号(`bump_global_generation`)保留作可观测性 + 未来就绪钩子,但不依赖它
10//! 实际失效缓存。
11//!
12//! 仅在启用 `server` feature 时编译。
13
14#![cfg(feature = "server")]
15
16use std::path::PathBuf;
17use std::sync::atomic::{AtomicU64, Ordering};
18use std::sync::LazyLock;
19
20/// 全局 SSR 世代号。
21///
22/// 任何文章写入操作都会使其递增,从而让所有基于该全局世代的 SSR 缓存键在未来
23/// Dioxus 支持自定义缓存键时失效。
24static GLOBAL_GENERATION: LazyLock<AtomicU64> = LazyLock::new(AtomicU64::default);
25
26/// 注入到请求扩展中的当前 SSR 世代号。
27///
28/// 这是为未来 Dioxus 支持自定义 SSR 缓存键预留的钩子。当前 Dioxus 0.7 的渲染器
29/// 不会读取此扩展。
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub struct SsrGeneration(pub u64);
32
33/// Dioxus 增量渲染器缓存落盘根目录(相对 CWD)。
34///
35/// 路由 `/post/foo` 的缓存为 `static/post/foo/index/<hash>.html`。
36/// 由 `IncrementalRendererConfig::default()` 决定,无公开 API 可读,故硬编码。
37const SSR_CACHE_ROOT: &str = "static";
38
39/// 计算某路由的 SSR 缓存目录路径。
40///
41/// route 形如 `/post/markdown-syntax-test`(前导 `/` 可有可无)。返回
42/// `static/post/markdown-syntax-test`(不含 `index/`,删整目录更彻底)。
43/// 对路径段做安全清洗:禁止 `..` / 空段,避免越出 `static/` 根。
44fn route_cache_dir(route: &str) -> Option<PathBuf> {
45    let mut path = PathBuf::from(SSR_CACHE_ROOT);
46    for seg in route.trim_start_matches('/').split('/') {
47        if seg.is_empty() || seg == ".." || seg == "." {
48            continue;
49        }
50        path.push(seg);
51    }
52    if path.as_path() == std::path::Path::new(SSR_CACHE_ROOT) {
53        None // 根路由("/")无目录段;首页缓存由 invalidate_ssr_all_public 覆盖删除
54    } else {
55        Some(path)
56    }
57}
58
59/// 失效单一路由的 SSR 磁盘缓存。
60///
61/// 删除 `static/<route>/` 目录(含 `index/<hash>.html`)。文件不存在时静默。
62/// **IO 在当前线程同步执行**——删除一个空目录是纳秒级操作,不值得 spawn_blocking;
63/// 调用方已在事务提交后调用,无阻塞风险。
64pub fn invalidate_ssr_route(route: &str) {
65    let Some(dir) = route_cache_dir(route) else {
66        return;
67    };
68    match std::fs::remove_dir_all(&dir) {
69        Ok(()) => tracing::debug!(route = route, dir = %dir.display(), "SSR 路由缓存已删除"),
70        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
71        Err(e) => tracing::warn!(route = route, error = %e, "删除 SSR 路由缓存失败"),
72    }
73}
74
75/// 失效某文章的 admin 预览路由 SSR 缓存。
76///
77/// 草稿编辑后预览需见最新内容。`invalidate_ssr_all_public` 显式跳过 `admin/`
78/// 目录(见 [`invalidate_ssr_all_public`] 注释),预览路由 (`/admin/preview/<slug>`)
79/// 不会被全量失效覆盖,故写入路径需定向调用本函数。
80pub fn invalidate_post_preview(slug: &str) {
81    invalidate_ssr_route(&format!("/admin/preview/{slug}"));
82}
83
84/// 失效所有公开页 SSR 缓存(删除 `static/` 下除 `.well-known`、`admin` 外的全部)。
85///
86/// 用于批量重建等影响面广的写入。保留 `.well-known`(浏览器/PWA 元数据,
87/// 与内容无关)和 `admin`(管理后台,写入者自己的视角无需刷新)。
88pub fn invalidate_ssr_all_public() {
89    let root = PathBuf::from(SSR_CACHE_ROOT);
90    let Ok(entries) = std::fs::read_dir(&root) else {
91        return; // 目录不存在(首次启动或已被清)
92    };
93    for entry in entries.flatten() {
94        let name = entry.file_name();
95        let name = name.to_string_lossy();
96        if name == ".well-known" || name == "admin" {
97            continue;
98        }
99        if let Err(e) = std::fs::remove_dir_all(entry.path()) {
100            if e.kind() != std::io::ErrorKind::NotFound {
101                tracing::warn!(entry = %name, error = %e, "删除 SSR 缓存条目失败");
102            }
103        }
104    }
105    tracing::debug!("已失效全部公开页 SSR 缓存");
106}
107
108/// 原子递增并返回新的全局世代号。
109///
110/// 仅作可观测性用途(注入 `X-SSR-Generation` 响应头)。实际 SSR 缓存失效由
111/// [`invalidate_ssr_route`] 物理删文件完成(首页由 [`invalidate_ssr_all_public`] 覆盖)。
112pub fn bump_global_generation() -> u64 {
113    let new = GLOBAL_GENERATION
114        .fetch_add(1, Ordering::SeqCst)
115        .wrapping_add(1);
116    tracing::debug!(new_generation = new, "SSR 全局世代号已递增");
117    new
118}
119
120/// 返回当前全局世代号。
121pub fn current_global_generation() -> u64 {
122    GLOBAL_GENERATION.load(Ordering::SeqCst)
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128    use serial_test::serial;
129
130    #[test]
131    #[serial]
132    fn global_generation_is_monotonic() {
133        let before = current_global_generation();
134        let g1 = bump_global_generation();
135        let g2 = bump_global_generation();
136        let current = current_global_generation();
137
138        assert!(g1 > before || g1 == 1);
139        assert!(g2 > g1);
140        assert_eq!(current, g2);
141    }
142
143    #[test]
144    fn route_cache_dir_rejects_traversal() {
145        // 路径穿越尝试不应越出 static/ 根。
146        let p = route_cache_dir("/post/../../../etc/passwd").unwrap();
147        let segs: Vec<_> = p.components().collect();
148        // .. 被过滤,只剩 static/post/etc/passwd
149        assert!(p.starts_with("static"));
150        assert!(!segs.iter().any(|c| c.as_os_str() == ".."));
151    }
152
153    #[test]
154    fn route_cache_dir_normalizes_leading_slash() {
155        let a = route_cache_dir("/post/foo").unwrap();
156        let b = route_cache_dir("post/foo").unwrap();
157        assert_eq!(a, b);
158        assert!(a.ends_with("post/foo"));
159    }
160
161    #[test]
162    fn route_cache_dir_none_for_root() {
163        // 根路由 "/" 无目录段(首页缓存由 invalidate_ssr_all_public 覆盖)。
164        assert!(route_cache_dir("/").is_none());
165        assert!(route_cache_dir("").is_none());
166    }
167
168    #[test]
169    fn invalidate_ssr_route_deletes_dir() {
170        // 造一个假的缓存目录:static/__test_route/index/fake.html
171        let dir = route_cache_dir("/__test_route_xyz").unwrap();
172        std::fs::create_dir_all(dir.join("index")).unwrap();
173        std::fs::write(dir.join("index").join("fake.html"), "stale").unwrap();
174        assert!(dir.exists());
175
176        invalidate_ssr_route("/__test_route_xyz");
177
178        assert!(!dir.exists(), "删除后目录不应存在");
179    }
180
181    #[test]
182    fn invalidate_ssr_route_missing_is_noop() {
183        // 不存在的路由删除应静默成功(NotFound 不报错)。
184        invalidate_ssr_route("/__never_exists_xyz_123");
185    }
186
187    #[test]
188    fn invalidate_ssr_all_public_is_safe_on_missing_root() {
189        // static/ 根不存在时不应 panic(首次启动或已清空场景)。
190        // 不创建真实 static/ 目录,直接调用验证 NotFound 静默。
191        // (若真实环境已有 static/,本测试不会误删——read_dir 对每个条目单独删,
192        //  这里仅验证根缺失分支。)
193        invalidate_ssr_all_public();
194    }
195}