Skip to main content

atomr_persistence_redis/
config.rs

1//! Connection configuration for the Redis provider.
2
3use std::env;
4
5#[derive(Debug, Clone)]
6pub struct RedisConfig {
7    pub url: String,
8    pub key_prefix: String,
9    pub pool_size: usize,
10}
11
12impl RedisConfig {
13    pub fn new(url: impl Into<String>) -> Self {
14        Self { url: url.into(), key_prefix: "atomr".into(), pool_size: 4 }
15    }
16
17    pub fn with_key_prefix(mut self, prefix: impl Into<String>) -> Self {
18        self.key_prefix = prefix.into();
19        self
20    }
21
22    pub fn with_pool_size(mut self, size: usize) -> Self {
23        self.pool_size = size.max(1);
24        self
25    }
26
27    /// Env lookup order: `ATOMR_PERSISTENCE_REDIS_URL`, `ATOMR_IT_REDIS_URL`,
28    /// `REDIS_URL`, then dev fallback `redis://127.0.0.1:6379`.
29    pub fn from_env() -> Self {
30        let url = env::var("ATOMR_PERSISTENCE_REDIS_URL")
31            .or_else(|_| env::var("ATOMR_IT_REDIS_URL"))
32            .or_else(|_| env::var("REDIS_URL"))
33            .unwrap_or_else(|_| "redis://127.0.0.1:6379".to_string());
34        let prefix = env::var("ATOMR_PERSISTENCE_REDIS_PREFIX").unwrap_or_else(|_| "atomr".into());
35        Self::new(url).with_key_prefix(prefix)
36    }
37
38    pub(crate) fn journal_key(&self, pid: &str) -> String {
39        format!("{}:journal:{}", self.key_prefix, pid)
40    }
41
42    pub(crate) fn snapshot_key(&self, pid: &str) -> String {
43        format!("{}:snapshot:{}", self.key_prefix, pid)
44    }
45
46    pub(crate) fn tag_key(&self, tag: &str) -> String {
47        format!("{}:tag:{}", self.key_prefix, tag)
48    }
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54
55    #[test]
56    fn keys_respect_prefix() {
57        let cfg = RedisConfig::new("redis://h").with_key_prefix("demo");
58        assert_eq!(cfg.journal_key("p1"), "demo:journal:p1");
59        assert_eq!(cfg.snapshot_key("p1"), "demo:snapshot:p1");
60        assert_eq!(cfg.tag_key("red"), "demo:tag:red");
61    }
62
63    #[test]
64    fn from_env_default() {
65        std::env::remove_var("ATOMR_PERSISTENCE_REDIS_URL");
66        std::env::remove_var("ATOMR_IT_REDIS_URL");
67        std::env::remove_var("REDIS_URL");
68        let cfg = RedisConfig::from_env();
69        assert!(cfg.url.starts_with("redis://"));
70    }
71}