tdm_server_rust/cache/
auth_snapshot_cache.rs1use crate::{
15 app::AppState, entity::member::Member, error::AppError,
16 repository::member_repo::MemberRepository,
17};
18
19pub struct AuthSnapshotCache;
21
22const VALUE_NS: &str = "auth_snapshot";
24
25pub fn new_auth_snapshot_cache() -> AuthSnapshotCache {
29 AuthSnapshotCache
30}
31
32pub async fn get_auth_snapshot_cached(
50 state: &AppState,
51 member_id: i32,
52) -> Result<Member, AppError> {
53 let key = member_id.to_string();
54 if let Some(cached) = state.redis.get_value(VALUE_NS, &key).await {
55 return Ok(cached);
56 }
57 let repo = MemberRepository::new(state.db.clone());
58 let member = repo.get_auth_snapshot(member_id).await?;
59 state
60 .redis
61 .set_value_ttl(VALUE_NS, &key, &member, cache_ttl_secs())
62 .await;
63 Ok(member)
64}
65
66pub async fn invalidate_auth_snapshot(state: &AppState, member_id: i32) {
70 state
71 .redis
72 .del_value(VALUE_NS, &member_id.to_string())
73 .await;
74}
75
76fn cache_ttl_secs() -> u64 {
78 std::env::var("AUTH_SNAPSHOT_CACHE_SECS")
79 .ok()
80 .and_then(|v| v.parse().ok())
81 .unwrap_or(30)
82}