1#![cfg(feature = "server")]
15
16use std::path::PathBuf;
17use std::sync::atomic::{AtomicU64, Ordering};
18use std::sync::LazyLock;
19
20static GLOBAL_GENERATION: LazyLock<AtomicU64> = LazyLock::new(AtomicU64::default);
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub struct SsrGeneration(pub u64);
32
33const SSR_CACHE_ROOT: &str = "static";
38
39fn 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 } else {
55 Some(path)
56 }
57}
58
59pub 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
75pub 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; };
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
99pub 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
111pub 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 let p = route_cache_dir("/post/../../../etc/passwd").unwrap();
138 let segs: Vec<_> = p.components().collect();
139 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 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 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 invalidate_ssr_route("/__never_exists_xyz_123");
176 }
177
178 #[test]
179 fn invalidate_ssr_all_public_is_safe_on_missing_root() {
180 invalidate_ssr_all_public();
185 }
186}