Skip to main content

hyperinfer_core/
redis.rs

1//! Redis utilities for HyperInfer
2//!
3//! Provides functionality for Redis-based configuration and policy updates.
4
5use futures_util::stream::StreamExt;
6use redis::aio::ConnectionManager;
7use redis::Client;
8use serde::{Deserialize, Serialize};
9use std::sync::Arc;
10use tokio::sync::RwLock;
11use tracing::{error, info};
12
13use crate::error::ConfigError;
14use crate::types::{Config, Provider, Quota, RoutingRule};
15use std::collections::HashMap;
16
17pub const CONFIG_CHANNEL: &str = "hyperinfer:config_updates";
18pub const CONFIG_KEY: &str = "hyperinfer:config";
19
20/// Internal Redis serialization DTO for `Config` that preserves `api_keys`
21/// (unlike public `Config`, which skips `api_keys` during serialization to prevent HTTP leaks).
22#[derive(Debug, Clone, Serialize, Deserialize)]
23struct StoredConfig {
24    #[serde(default)]
25    api_keys: HashMap<String, String>,
26    #[serde(default)]
27    routing_rules: Vec<RoutingRule>,
28    #[serde(default)]
29    quotas: HashMap<String, Quota>,
30    #[serde(default)]
31    model_aliases: HashMap<String, String>,
32    #[serde(default)]
33    default_provider: Option<Provider>,
34}
35
36impl From<&Config> for StoredConfig {
37    fn from(c: &Config) -> Self {
38        Self {
39            api_keys: c.api_keys.clone(),
40            routing_rules: c.routing_rules.clone(),
41            quotas: c.quotas.clone(),
42            model_aliases: c.model_aliases.clone(),
43            default_provider: c.default_provider.clone(),
44        }
45    }
46}
47
48impl From<StoredConfig> for Config {
49    fn from(s: StoredConfig) -> Self {
50        Self {
51            api_keys: s.api_keys,
52            routing_rules: s.routing_rules,
53            quotas: s.quotas,
54            model_aliases: s.model_aliases,
55            default_provider: s.default_provider,
56        }
57    }
58}
59
60#[derive(Debug, Clone, Serialize, Deserialize)]
61struct StoredConfigUpdate {
62    config: StoredConfig,
63}
64
65#[derive(Debug, Clone, Serialize, Deserialize)]
66pub struct ConfigUpdate {
67    pub config: Config,
68}
69
70#[derive(Debug, Clone, Serialize, Deserialize)]
71pub struct PolicyUpdate {
72    pub key: String,
73    pub action: PolicyAction,
74    pub reason: Option<String>,
75}
76
77#[derive(Debug, Clone, Serialize, Deserialize)]
78#[serde(rename_all = "lowercase")]
79pub enum PolicyAction {
80    Revoke,
81    Update,
82}
83
84#[derive(Clone)]
85pub struct ConfigManager {
86    client: Arc<Client>,
87    manager: ConnectionManager,
88}
89
90impl ConfigManager {
91    pub async fn new(redis_url: &str) -> Result<Self, ConfigError> {
92        let client = Client::open(redis_url)?;
93        let manager = ConnectionManager::new(client.clone()).await?;
94        Ok(Self {
95            client: Arc::new(client),
96            manager,
97        })
98    }
99
100    pub async fn subscribe_to_config_updates(
101        &self,
102        config: Arc<RwLock<Config>>,
103    ) -> Result<tokio::task::JoinHandle<()>, ConfigError> {
104        let client = Arc::clone(&self.client);
105
106        let handle = tokio::spawn(async move {
107            let mut backoff = 1u64;
108
109            loop {
110                let result = async {
111                    let mut pubsub = client.get_async_pubsub().await?;
112                    pubsub.subscribe(CONFIG_CHANNEL).await?;
113
114                    info!(
115                        "Subscribed to Redis config updates channel: {}",
116                        CONFIG_CHANNEL
117                    );
118
119                    let mut stream = pubsub.on_message();
120
121                    while let Some(msg) = stream.next().await {
122                        let payload_str = match msg.get_payload::<String>() {
123                            Ok(p) => p,
124                            Err(e) => {
125                                error!("Failed to get message payload: {}", e);
126                                continue;
127                            }
128                        };
129
130                        let new_config =
131                            match serde_json::from_str::<StoredConfigUpdate>(&payload_str) {
132                                Ok(update) => Config::from(update.config),
133                                Err(e) => {
134                                    error!("Failed to parse config update: {}", e);
135                                    continue;
136                                }
137                            };
138
139                        {
140                            let mut cfg = config.write().await;
141                            *cfg = new_config;
142                            info!("Config updated via Pub/Sub");
143                        }
144                    }
145                    Ok::<(), Box<dyn std::error::Error + Send + Sync>>(())
146                }
147                .await;
148
149                match result {
150                    Err(e) => {
151                        error!(
152                            "Config subscription error: {}, reconnecting in {}s",
153                            e, backoff
154                        );
155                        tokio::time::sleep(tokio::time::Duration::from_secs(backoff)).await;
156                        backoff = (backoff * 2).min(60);
157                    }
158                    Ok(()) => {
159                        backoff = 1;
160                        info!("Config updates stream ended, reconnecting in {}s", backoff);
161                        tokio::time::sleep(tokio::time::Duration::from_secs(backoff)).await;
162                    }
163                }
164            }
165        });
166
167        Ok(handle)
168    }
169
170    pub async fn subscribe_to_policy_updates(
171        &self,
172        callback: impl Fn(PolicyUpdate) + Send + Sync + 'static,
173    ) -> Result<tokio::task::JoinHandle<()>, ConfigError> {
174        let client = Arc::clone(&self.client);
175
176        let handle = tokio::spawn(async move {
177            let mut backoff = 1u64;
178
179            loop {
180                let result = async {
181                    let mut pubsub = client.get_async_pubsub().await?;
182                    pubsub.subscribe("hyperinfer:policy_updates").await?;
183
184                    info!("Subscribed to Redis policy updates channel");
185
186                    let mut stream = pubsub.on_message();
187
188                    while let Some(msg) = stream.next().await {
189                        let payload = match msg.get_payload::<String>() {
190                            Ok(p) => p,
191                            Err(e) => {
192                                error!("Failed to get policy message payload: {}", e);
193                                continue;
194                            }
195                        };
196
197                        match serde_json::from_str::<PolicyUpdate>(&payload) {
198                            Ok(update) => callback(update),
199                            Err(e) => error!("Failed to parse policy update: {}", e),
200                        }
201                    }
202                    Ok::<(), Box<dyn std::error::Error + Send + Sync>>(())
203                }
204                .await;
205
206                match result {
207                    Err(e) => {
208                        error!(
209                            "Policy subscription error: {}, reconnecting in {}s",
210                            e, backoff
211                        );
212                        tokio::time::sleep(tokio::time::Duration::from_secs(backoff)).await;
213                        backoff = (backoff * 2).min(60);
214                    }
215                    Ok(()) => {
216                        backoff = 1;
217                        info!("Policy updates stream ended, reconnecting in {}s", backoff);
218                        tokio::time::sleep(tokio::time::Duration::from_secs(backoff)).await;
219                    }
220                }
221            }
222        });
223
224        Ok(handle)
225    }
226
227    pub async fn ping(&self) -> Result<(), ConfigError> {
228        let mut conn = self.manager.clone();
229        redis::cmd("PING").query_async::<String>(&mut conn).await?;
230        Ok(())
231    }
232
233    pub async fn fetch_config(&self) -> Result<Config, ConfigError> {
234        let mut conn = self.manager.clone();
235
236        let data: Option<Vec<u8>> = redis::cmd("GET")
237            .arg(CONFIG_KEY)
238            .query_async(&mut conn)
239            .await?;
240
241        match data {
242            Some(bytes) => {
243                let stored: StoredConfig = serde_json::from_slice(&bytes)?;
244                Ok(Config::from(stored))
245            }
246            None => Ok(Config {
247                api_keys: std::collections::HashMap::new(),
248                routing_rules: Vec::new(),
249                quotas: std::collections::HashMap::new(),
250                model_aliases: std::collections::HashMap::new(),
251                default_provider: None,
252            }),
253        }
254    }
255
256    pub async fn publish_config_update(&self, config: &Config) -> Result<(), ConfigError> {
257        let mut conn = self.manager.clone();
258        let stored = StoredConfig::from(config);
259
260        // Store config first so it's available when subscribers receive notification
261        let config_bytes = serde_json::to_vec(&stored)?;
262
263        redis::cmd("SET")
264            .arg(CONFIG_KEY)
265            .arg(config_bytes)
266            .query_async::<()>(&mut conn)
267            .await?;
268
269        let update = StoredConfigUpdate { config: stored };
270
271        let payload = serde_json::to_string(&update)?;
272
273        redis::cmd("PUBLISH")
274            .arg(CONFIG_CHANNEL)
275            .arg(&payload)
276            .query_async::<()>(&mut conn)
277            .await?;
278
279        info!("Published config update to channel: {}", CONFIG_CHANNEL);
280
281        Ok(())
282    }
283
284    pub async fn publish_policy_update(&self, update: &PolicyUpdate) -> Result<(), ConfigError> {
285        let mut conn = self.manager.clone();
286
287        let payload = serde_json::to_string(update)?;
288
289        redis::cmd("PUBLISH")
290            .arg("hyperinfer:policy_updates")
291            .arg(&payload)
292            .query_async::<()>(&mut conn)
293            .await?;
294
295        info!("Published policy update: {:?}", update.action);
296
297        Ok(())
298    }
299}
300
301#[cfg(test)]
302mod tests {
303    use super::*;
304    use crate::Provider;
305
306    #[test]
307    fn test_config_update_serialization() {
308        let config = Config {
309            api_keys: std::collections::HashMap::new(),
310            routing_rules: vec![],
311            quotas: std::collections::HashMap::new(),
312            model_aliases: std::collections::HashMap::new(),
313            default_provider: Some(Provider::OpenAI),
314        };
315
316        let update = ConfigUpdate {
317            config: config.clone(),
318        };
319
320        let json = serde_json::to_string(&update).unwrap();
321        let deserialized: ConfigUpdate = serde_json::from_str(&json).unwrap();
322
323        assert_eq!(deserialized.config.default_provider, Some(Provider::OpenAI));
324    }
325
326    #[test]
327    fn test_policy_update_serialization() {
328        let update = PolicyUpdate {
329            key: "test-key".to_string(),
330            action: PolicyAction::Revoke,
331            reason: Some("Testing".to_string()),
332        };
333
334        let json = serde_json::to_string(&update).unwrap();
335        let deserialized: PolicyUpdate = serde_json::from_str(&json).unwrap();
336
337        assert_eq!(deserialized.key, "test-key");
338        assert_eq!(deserialized.reason, Some("Testing".to_string()));
339    }
340
341    #[test]
342    fn test_policy_action_revoke() {
343        let action = PolicyAction::Revoke;
344        let json = serde_json::to_string(&action).unwrap();
345        assert_eq!(json, "\"revoke\"");
346    }
347
348    #[test]
349    fn test_policy_action_update() {
350        let action = PolicyAction::Update;
351        let json = serde_json::to_string(&action).unwrap();
352        assert_eq!(json, "\"update\"");
353    }
354
355    #[test]
356    fn test_policy_update_without_reason() {
357        let update = PolicyUpdate {
358            key: "key123".to_string(),
359            action: PolicyAction::Update,
360            reason: None,
361        };
362
363        let json = serde_json::to_string(&update).unwrap();
364        let deserialized: PolicyUpdate = serde_json::from_str(&json).unwrap();
365
366        assert_eq!(deserialized.key, "key123");
367        assert_eq!(deserialized.reason, None);
368    }
369
370    #[test]
371    fn test_policy_update_clone() {
372        let update = PolicyUpdate {
373            key: "clone-key".to_string(),
374            action: PolicyAction::Revoke,
375            reason: Some("Clone test".to_string()),
376        };
377
378        let cloned = update.clone();
379        assert_eq!(update.key, cloned.key);
380        assert_eq!(update.reason, cloned.reason);
381    }
382
383    #[test]
384    fn test_config_update_clone() {
385        let config = Config {
386            api_keys: std::collections::HashMap::new(),
387            routing_rules: vec![],
388            quotas: std::collections::HashMap::new(),
389            model_aliases: std::collections::HashMap::new(),
390            default_provider: None,
391        };
392
393        let update = ConfigUpdate { config };
394        let cloned = update.clone();
395
396        assert_eq!(
397            update.config.routing_rules.len(),
398            cloned.config.routing_rules.len()
399        );
400    }
401
402    #[test]
403    fn test_config_channel_constant() {
404        assert_eq!(CONFIG_CHANNEL, "hyperinfer:config_updates");
405    }
406
407    #[test]
408    fn test_config_key_constant() {
409        assert_eq!(CONFIG_KEY, "hyperinfer:config");
410    }
411
412    #[test]
413    fn test_policy_action_deserialization_revoke() {
414        let json = "\"revoke\"";
415        let action: PolicyAction = serde_json::from_str(json).unwrap();
416        assert!(matches!(action, PolicyAction::Revoke));
417    }
418
419    #[test]
420    fn test_policy_action_deserialization_update() {
421        let json = "\"update\"";
422        let action: PolicyAction = serde_json::from_str(json).unwrap();
423        assert!(matches!(action, PolicyAction::Update));
424    }
425
426    #[test]
427    fn test_config_update_with_routing_rules() {
428        use crate::types::RoutingRule;
429
430        let rule = RoutingRule {
431            name: "test-rule".to_string(),
432            priority: 1,
433            fallback_models: vec!["model1".to_string(), "model2".to_string()],
434        };
435
436        let config = Config {
437            api_keys: std::collections::HashMap::new(),
438            routing_rules: vec![rule],
439            quotas: std::collections::HashMap::new(),
440            model_aliases: std::collections::HashMap::new(),
441            default_provider: None,
442        };
443
444        let update = ConfigUpdate { config };
445        let json = serde_json::to_string(&update).unwrap();
446        let deserialized: ConfigUpdate = serde_json::from_str(&json).unwrap();
447
448        assert_eq!(deserialized.config.routing_rules.len(), 1);
449        assert_eq!(deserialized.config.routing_rules[0].name, "test-rule");
450    }
451
452    #[test]
453    fn test_config_update_with_model_aliases() {
454        let mut aliases = std::collections::HashMap::new();
455        aliases.insert("alias1".to_string(), "model1".to_string());
456        aliases.insert("alias2".to_string(), "model2".to_string());
457
458        let config = Config {
459            api_keys: std::collections::HashMap::new(),
460            routing_rules: vec![],
461            quotas: std::collections::HashMap::new(),
462            model_aliases: aliases,
463            default_provider: None,
464        };
465
466        let update = ConfigUpdate { config };
467        let json = serde_json::to_string(&update).unwrap();
468        let deserialized: ConfigUpdate = serde_json::from_str(&json).unwrap();
469
470        assert_eq!(deserialized.config.model_aliases.len(), 2);
471    }
472}