//! 缓存层 — 内存缓存管理 use crate::db::Database; use crate::models::*; use std::collections::HashMap; use std::sync::Arc; use tokio::sync::RwLock; use tracing::info; /// 相册缓存 #[derive(Debug, Clone)] pub struct AlbumsCache { pub albums: Vec, pub search_index: HashMap>, pub last_updated: chrono::DateTime, } impl AlbumsCache { pub fn new() -> Self { Self { albums: Vec::new(), search_index: HashMap::new(), last_updated: chrono::Utc::now() } } pub fn is_expired(&self) -> bool { (chrono::Utc::now() - self.last_updated).num_minutes() >= 30 } pub fn update(&mut self, albums: Vec) { self.search_index.clear(); for album in &albums { let title_lower = album.title.to_lowercase(); for word in title_lower.split_whitespace() { if word.len() >= 2 { self.search_index.entry(word.to_string()).or_default().push(album.clone()); } } self.search_index.entry(title_lower).or_default().push(album.clone()); } self.albums = albums; self.last_updated = chrono::Utc::now(); info!("相册缓存已更新,共 {} 个相册,{} 个搜索索引项", self.albums.len(), self.search_index.len()); } pub fn search(&self, query: &str) -> Vec { let q = query.to_lowercase().trim().to_string(); if q.is_empty() { return Vec::new(); } let mut seen = std::collections::HashSet::new(); let mut results = Vec::new(); // 1. 完整匹配 if let Some(matches) = self.search_index.get(&q) { for album in matches { if seen.insert(album.id) { results.push(album.clone()); } } } // 2. 单词匹配 for word in q.split_whitespace() { if word.len() >= 2 { if let Some(matches) = self.search_index.get(word) { for album in matches { if seen.insert(album.id) { results.push(album.clone()); } } } } } // 3. 模糊搜索 if results.is_empty() { for album in &self.albums { let tl = album.title.to_lowercase(); if tl.contains(&q) { if seen.insert(album.id) { results.push(album.clone()); } } } } // 4. 部分匹配 if results.is_empty() && q.len() >= 2 { for album in &self.albums { let tl = album.title.to_lowercase(); if q.split_whitespace().any(|w| w.len() >= 2 && tl.contains(w)) { if seen.insert(album.id) { results.push(album.clone()); } } } } results } } /// 标签缓存 #[derive(Debug, Clone, Default)] pub struct TagCache { pub popular_tags: Vec, /// tag → 包含该标签的相册列表(倒排索引,供按标签搜索用) pub tag_albums: HashMap>, pub last_updated: chrono::DateTime, } impl TagCache { pub fn update(&mut self, tags: Vec, tag_albums: HashMap>) { self.popular_tags = tags; self.tag_albums = tag_albums; self.last_updated = chrono::Utc::now(); info!("标签缓存已更新,共 {} 个热门标签,{} 个标签倒排索引项", self.popular_tags.len(), self.tag_albums.len()); } /// 按标签搜索相册(从缓存中检索) pub fn search_albums(&self, tag: &str) -> Vec { self.tag_albums.get(tag).cloned().unwrap_or_default() } } /// 人物缓存 #[derive(Debug, Clone, Default)] pub struct PersonCache { pub persons: Vec, /// 搜索索引:关键词小写 → person_id 集合 pub search_index: HashMap>, /// person_id → person 投影(用于按 id 快速访问) pub id_map: HashMap, pub last_updated: chrono::DateTime, } impl PersonCache { pub fn update(&mut self, persons: Vec) { self.search_index.clear(); self.id_map.clear(); for p in &persons { // 构建搜索索引(姓名 + 所有别名) let name_lower = p.name.to_lowercase(); for word in name_lower.split_whitespace() { if word.len() >= 2 { self.search_index.entry(word.to_string()).or_default().push(p.id); } } self.search_index.entry(name_lower.clone()).or_default().push(p.id); // 显示名 if let Some(ref dn) = p.display_name { let dn_lower = dn.to_lowercase(); for word in dn_lower.split_whitespace() { if word.len() >= 2 { self.search_index.entry(word.to_string()).or_default().push(p.id); } } self.search_index.entry(dn_lower).or_default().push(p.id); } // 别名 for alias in &p.aliases { let alias_lower = alias.to_lowercase(); for word in alias_lower.split_whitespace() { if word.len() >= 2 { self.search_index.entry(word.to_string()).or_default().push(p.id); } } self.search_index.entry(alias_lower).or_default().push(p.id); } self.id_map.insert(p.id, p.clone()); } self.persons = persons; self.last_updated = chrono::Utc::now(); info!("人物缓存已更新,共 {} 人,{} 个搜索索引项", self.persons.len(), self.search_index.len()); } /// 从缓存搜索人物(按姓名/别名) pub fn search(&self, query: &str) -> Vec { let q = query.to_lowercase().trim().to_string(); if q.is_empty() || q.len() < 2 { return Vec::new(); } let mut seen = std::collections::HashSet::new(); // 1. 完整匹配 if let Some(ids) = self.search_index.get(&q) { for id in ids { if seen.insert(*id) {} } } // 2. 单词匹配 for word in q.split_whitespace() { if word.len() >= 2 { if let Some(ids) = self.search_index.get(word) { for id in ids { seen.insert(*id); } } } } // 3. 模糊匹配 if seen.is_empty() { for p in &self.persons { let full = format!("{} {} {}", p.name.to_lowercase(), p.display_name.as_deref().unwrap_or(""), p.aliases.join(" ").to_lowercase()); if full.contains(&q) { seen.insert(p.id); } } } seen.iter() .filter_map(|id| self.id_map.get(id).cloned()) .collect() } } /// 刷新所有缓存(相册 + 标签 + 人物) pub async fn refresh_all_caches( db: &Database, albums_cache: &Arc>, persons_cache: &Arc>, tags_cache: &Arc>, ) { // 1. 刷新相册 if let Ok(albums) = db.get_all_albums().await { let mut c = albums_cache.write().await; c.update(albums.clone()); // 2. 刷新标签 let popular_tags = db.get_popular_tags(200).await; let tag_albums = db.get_all_tag_albums().await; let mut tc = tags_cache.write().await; tc.update(popular_tags, tag_albums); } // 3. 刷新人物 let persons = db.get_all_persons_with_aliases().await; let mut pc = persons_cache.write().await; pc.update(persons); info!("全部缓存已刷新"); } /// 仅刷新人物缓存(管线执行后调用) pub async fn refresh_persons_cache(db: &Database, persons_cache: &Arc>) { let persons = db.get_all_persons_with_aliases().await; let mut pc = persons_cache.write().await; pc.update(persons); }