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/// 失效所有公开页 SSR 缓存(删除 `static/` 下除 `.well-known`、`admin` 外的全部)。
76///
77/// 用于批量重建等影响面广的写入。保留 `.well-known`(浏览器/PWA 元数据,
78/// 与内容无关)和 `admin`(管理后台,写入者自己的视角无需刷新)。
79pub fn invalidate_ssr_all_public() {
80    let root = PathBuf::from(SSR_CACHE_ROOT);
81    let Ok(entries) = std::fs::read_dir(&root) else {
82        return; // 目录不存在(首次启动或已被清)
83    };
84    for entry in entries.flatten() {
85        let name = entry.file_name();
86        let name = name.to_string_lossy();
87        if name == ".well-known" || name == "admin" {
88            continue;
89        }
90        if let Err(e) = std::fs::remove_dir_all(entry.path()) {
91            if e.kind() != std::io::ErrorKind::NotFound {
92                tracing::warn!(entry = %name, error = %e, "删除 SSR 缓存条目失败");
93            }
94        }
95    }
96    tracing::debug!("已失效全部公开页 SSR 缓存");
97}
98
99/// 原子递增并返回新的全局世代号。
100///
101/// 仅作可观测性用途(注入 `X-SSR-Generation` 响应头)。实际 SSR 缓存失效由
102/// [`invalidate_ssr_route`] 物理删文件完成(首页由 [`invalidate_ssr_all_public`] 覆盖)。
103pub fn bump_global_generation() -> u64 {
104    let new = GLOBAL_GENERATION
105        .fetch_add(1, Ordering::SeqCst)
106        .wrapping_add(1);
107    tracing::debug!(new_generation = new, "SSR 全局世代号已递增");
108    new
109}
110
111/// 返回当前全局世代号。
112pub fn current_global_generation() -> u64 {
113    GLOBAL_GENERATION.load(Ordering::SeqCst)
114}
115
116#[cfg(test)]
117mod tests {
118    use super::*;
119    use serial_test::serial;
120
121    #[test]
122    #[serial]
123    fn global_generation_is_monotonic() {
124        let before = current_global_generation();
125        let g1 = bump_global_generation();
126        let g2 = bump_global_generation();
127        let current = current_global_generation();
128
129        assert!(g1 > before || g1 == 1);
130        assert!(g2 > g1);
131        assert_eq!(current, g2);
132    }
133
134    #[test]
135    fn route_cache_dir_rejects_traversal() {
136        // 路径穿越尝试不应越出 static/ 根。
137        let p = route_cache_dir("/post/../../../etc/passwd").unwrap();
138        let segs: Vec<_> = p.components().collect();
139        // .. 被过滤,只剩 static/post/etc/passwd
140        assert!(p.starts_with("static"));
141        assert!(!segs.iter().any(|c| c.as_os_str() == ".."));
142    }
143
144    #[test]
145    fn route_cache_dir_normalizes_leading_slash() {
146        let a = route_cache_dir("/post/foo").unwrap();
147        let b = route_cache_dir("post/foo").unwrap();
148        assert_eq!(a, b);
149        assert!(a.ends_with("post/foo"));
150    }
151
152    #[test]
153    fn route_cache_dir_none_for_root() {
154        // 根路由 "/" 无目录段(首页缓存由 invalidate_ssr_all_public 覆盖)。
155        assert!(route_cache_dir("/").is_none());
156        assert!(route_cache_dir("").is_none());
157    }
158
159    #[test]
160    fn invalidate_ssr_route_deletes_dir() {
161        // 造一个假的缓存目录:static/__test_route/index/fake.html
162        let dir = route_cache_dir("/__test_route_xyz").unwrap();
163        std::fs::create_dir_all(dir.join("index")).unwrap();
164        std::fs::write(dir.join("index").join("fake.html"), "stale").unwrap();
165        assert!(dir.exists());
166
167        invalidate_ssr_route("/__test_route_xyz");
168
169        assert!(!dir.exists(), "删除后目录不应存在");
170    }
171
172    #[test]
173    fn invalidate_ssr_route_missing_is_noop() {
174        // 不存在的路由删除应静默成功(NotFound 不报错)。
175        invalidate_ssr_route("/__never_exists_xyz_123");
176    }
177
178    #[test]
179    fn invalidate_ssr_all_public_is_safe_on_missing_root() {
180        // static/ 根不存在时不应 panic(首次启动或已清空场景)。
181        // 不创建真实 static/ 目录,直接调用验证 NotFound 静默。
182        // (若真实环境已有 static/,本测试不会误删——read_dir 对每个条目单独删,
183        //  这里仅验证根缺失分支。)
184        invalidate_ssr_all_public();
185    }
186}