tdm_server_rust/cache/
auth_snapshot_cache.rs1use crate::{
15 app::AppState,
16 entity::member::Member,
17 error::AppError,
18 repository::member_repo::MemberRepository,
19};
20use std::sync::Arc;
21use std::time::Duration;
22
23pub type AuthSnapshotCache = moka::future::Cache<i32, Arc<Member>>;
28
29pub fn new_auth_snapshot_cache() -> AuthSnapshotCache {
33 let ttl_secs = std::env::var("AUTH_SNAPSHOT_CACHE_SECS")
34 .ok()
35 .and_then(|v| v.parse().ok())
36 .unwrap_or(30);
37 moka::future::Cache::builder()
38 .time_to_live(Duration::from_secs(ttl_secs))
39 .build()
40}
41
42pub async fn get_auth_snapshot_cached(
60 state: &AppState,
61 member_id: i32,
62) -> Result<Member, AppError> {
63 if let Some(cached) = state.auth_snapshot_cache.get(&member_id).await {
64 return Ok((*cached).clone());
65 }
66 let repo = MemberRepository::new(state.db.clone());
67 let member = repo.get_auth_snapshot(member_id).await?;
68 state
69 .auth_snapshot_cache
70 .insert(member_id, Arc::new(member.clone()))
71 .await;
72 Ok(member)
73}
74
75pub async fn invalidate_auth_snapshot(state: &AppState, member_id: i32) {
79 state.auth_snapshot_cache.invalidate(&member_id).await;
80}
81
82pub async fn invalidate_all_auth_snapshots(state: &AppState) {
86 state.auth_snapshot_cache.invalidate_all();
87}