rustpbx 0.4.4

A SIP PBX implementation in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! HTTP Registry - External HTTP API agent registry integration
//!
//! Suitable for:
//! - Integration with existing CRM/HR systems
//! - Microservices architectures
//! - Scenarios where agent data is managed externally

use super::{AgentRecord, AgentRegistry, PresenceState, RoutingStrategy};
use async_trait::async_trait;
use std::collections::HashMap;
use std::time::{Duration, Instant};
use tokio::sync::RwLock;
use tracing::{error, info};

/// HTTP API-backed agent registry implementation
///
/// Communicates with an external HTTP API for agent management.
/// Suitable for integration with existing systems.
pub struct HttpRegistry {
    base_url: String,
    api_key: Option<String>,
    client: reqwest::Client,
    /// Local cache for fast reads
    cache: RwLock<HashMap<String, (AgentRecord, Instant)>>,
    /// Round-robin counter
    rr_counter: RwLock<u64>,
    /// Event callbacks for state changes
    #[allow(dead_code)]
    event_handlers: RwLock<Vec<super::AgentEventHandler>>,

    /// Cache TTL
    cache_ttl: Duration,
}

impl HttpRegistry {
    pub fn new(base_url: String, api_key: Option<String>) -> Self {
        Self {
            base_url,
            api_key,
            client: reqwest::Client::new(),
            cache: RwLock::new(HashMap::new()),
            rr_counter: RwLock::new(0),
            event_handlers: RwLock::new(Vec::new()),
            cache_ttl: Duration::from_secs(30),
        }
    }

    pub fn with_cache_ttl(mut self, ttl: Duration) -> Self {
        self.cache_ttl = ttl;
        self
    }

    /// Build HTTP headers with API key if present
    fn build_headers(&self) -> reqwest::header::HeaderMap {
        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(
            reqwest::header::CONTENT_TYPE,
            reqwest::header::HeaderValue::from_static("application/json"),
        );
        if let Some(ref key) = self.api_key {
            headers.insert(
                "X-API-Key",
                reqwest::header::HeaderValue::from_str(key).unwrap(),
            );
        }
        headers
    }

    /// Check if cache entry is still valid
    fn is_cache_valid(&self, timestamp: Instant) -> bool {
        timestamp.elapsed() < self.cache_ttl
    }

    /// Fetch agent from HTTP API
    async fn fetch_agent(&self, agent_id: &str) -> anyhow::Result<Option<AgentRecord>> {
        let url = format!("{}/agents/{}", self.base_url, agent_id);

        let response = self
            .client
            .get(&url)
            .headers(self.build_headers())
            .send()
            .await?;

        if response.status() == reqwest::StatusCode::NOT_FOUND {
            return Ok(None);
        }

        if !response.status().is_success() {
            anyhow::bail!("HTTP error: {}", response.status());
        }

        let data: serde_json::Value = response.json().await?;

        // Parse agent record from JSON
        let record = Self::parse_agent_from_json(&data)?;

        // Update cache
        let mut cache = self.cache.write().await;
        cache.insert(agent_id.to_string(), (record.clone(), Instant::now()));

        Ok(Some(record))
    }

    /// Update agent via HTTP API
    async fn update_agent_api(
        &self,
        agent_id: &str,
        updates: serde_json::Value,
    ) -> anyhow::Result<()> {
        let url = format!("{}/agents/{}", self.base_url, agent_id);

        let response = self
            .client
            .patch(&url)
            .headers(self.build_headers())
            .json(&updates)
            .send()
            .await?;

        if !response.status().is_success() {
            anyhow::bail!("HTTP error: {}", response.status());
        }

        Ok(())
    }

    /// Parse agent record from JSON
    pub fn parse_agent_from_json(data: &serde_json::Value) -> anyhow::Result<AgentRecord> {
        let agent_id = data["agent_id"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("Missing agent_id"))?;
        let display_name = data["display_name"].as_str().unwrap_or(agent_id);
        let uri = data["uri"].as_str().unwrap_or("");
        let skills: Vec<String> = data["skills"]
            .as_array()
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(String::from))
                    .collect()
            })
            .unwrap_or_default();
        let max_concurrency = data["max_concurrency"].as_u64().unwrap_or(1) as u32;
        let current_calls = data["current_calls"].as_u64().unwrap_or(0) as u32;
        let presence = data["presence"]
            .as_str()
            .and_then(PresenceState::parse_state)
            .unwrap_or(PresenceState::Offline);
        let total_calls_handled = data["total_calls_handled"].as_u64().unwrap_or(0);
        let total_talk_time_secs = data["total_talk_time_secs"].as_u64().unwrap_or(0);

        Ok(AgentRecord {
            agent_id: agent_id.to_string(),
            display_name: display_name.to_string(),
            uri: uri.to_string(),
            skills,
            max_concurrency,
            current_calls,
            presence,
            last_state_change: Instant::now(),
            total_calls_handled,
            total_talk_time_secs,
            last_call_end: None,
            custom_data: HashMap::new(),
        })
    }
}

#[async_trait]
impl AgentRegistry for HttpRegistry {
    async fn register(
        &self,
        agent_id: String,
        display_name: String,
        uri: String,
        skills: Vec<String>,
        max_concurrency: u32,
    ) -> anyhow::Result<()> {
        let url = format!("{}/agents", self.base_url);

        let payload = serde_json::json!({
            "agent_id": agent_id,
            "display_name": display_name,
            "uri": uri,
            "skills": skills,
            "max_concurrency": max_concurrency,
            "presence": "available",
        });

        let response = self
            .client
            .post(&url)
            .headers(self.build_headers())
            .json(&payload)
            .send()
            .await?;

        if !response.status().is_success() {
            anyhow::bail!("HTTP error: {}", response.status());
        }

        info!(agent_id = %agent_id, "Agent registered via HTTP API");
        Ok(())
    }

    async fn unregister(&self, agent_id: &str) -> anyhow::Result<()> {
        let url = format!("{}/agents/{}", self.base_url, agent_id);

        let response = self
            .client
            .delete(&url)
            .headers(self.build_headers())
            .send()
            .await?;

        if !response.status().is_success() {
            anyhow::bail!("HTTP error: {}", response.status());
        }

        // Remove from cache
        let mut cache = self.cache.write().await;
        cache.remove(agent_id);

        info!(agent_id = %agent_id, "Agent unregistered via HTTP API");
        Ok(())
    }

    async fn get_agent(&self, agent_id: &str) -> Option<AgentRecord> {
        // Try cache first
        let cache = self.cache.read().await;
        if let Some((record, timestamp)) = cache.get(agent_id)
            && self.is_cache_valid(*timestamp)
        {
            return Some(record.clone());
        }
        drop(cache);

        // Fetch from API
        match self.fetch_agent(agent_id).await {
            Ok(agent) => agent,
            Err(e) => {
                error!(agent_id = %agent_id, error = %e, "Failed to fetch agent from HTTP API");
                None
            }
        }
    }

    async fn list_agents(&self) -> Vec<AgentRecord> {
        let url = format!("{}/agents", self.base_url);

        match self
            .client
            .get(&url)
            .headers(self.build_headers())
            .send()
            .await
        {
            Ok(response) if response.status().is_success() => {
                match response.json::<Vec<serde_json::Value>>().await {
                    Ok(data) => data
                        .iter()
                        .filter_map(|v| Self::parse_agent_from_json(v).ok())
                        .collect(),
                    Err(e) => {
                        error!(error = %e, "Failed to parse agents list");
                        Vec::new()
                    }
                }
            }
            _ => {
                // Fallback to cache
                let cache = self.cache.read().await;
                cache
                    .values()
                    .filter(|(_, ts)| self.is_cache_valid(*ts))
                    .map(|(record, _)| record.clone())
                    .collect()
            }
        }
    }

    async fn update_presence(
        &self,
        agent_id: &str,
        new_state: PresenceState,
    ) -> anyhow::Result<()> {
        let updates = serde_json::json!({
            "presence": new_state.as_str(),
        });

        self.update_agent_api(agent_id, updates).await?;

        // Update cache
        let mut cache = self.cache.write().await;
        if let Some((record, _)) = cache.get_mut(agent_id) {
            record.presence = new_state;
            record.last_state_change = Instant::now();
        }

        info!(agent_id = %agent_id, "Presence updated via HTTP API");
        Ok(())
    }

    async fn start_call(&self, agent_id: &str) -> anyhow::Result<()> {
        let updates = serde_json::json!({
            "current_calls": 1,
            "presence": "busy",
        });

        self.update_agent_api(agent_id, updates).await?;

        // Update cache
        let mut cache = self.cache.write().await;
        if let Some((record, _)) = cache.get_mut(agent_id) {
            record.current_calls += 1;
            record.presence = PresenceState::Busy { call_id: None };
            record.last_state_change = Instant::now();
        }

        Ok(())
    }

    async fn end_call(&self, agent_id: &str, talk_time_secs: u64) -> anyhow::Result<()> {
        let updates = serde_json::json!({
            "talk_time_secs": talk_time_secs,
        });

        self.update_agent_api(agent_id, updates).await?;

        // Update cache
        let mut cache = self.cache.write().await;
        if let Some((record, _)) = cache.get_mut(agent_id) {
            if record.current_calls > 0 {
                record.current_calls -= 1;
            }
            record.total_calls_handled += 1;
            record.total_talk_time_secs += talk_time_secs;
            record.last_call_end = Some(Instant::now());

            if record.current_calls == 0 {
                record.presence = PresenceState::Wrapup { call_id: None };
            }
        }

        Ok(())
    }

    async fn find_available_agents(&self, required_skills: &[String]) -> Vec<AgentRecord> {
        let agents = self.list_agents().await;
        agents
            .into_iter()
            .filter(|a| a.has_capacity() && a.has_skills(required_skills))
            .collect()
    }

    async fn select_agent(
        &self,
        required_skills: &[String],
        strategy: RoutingStrategy,
    ) -> Option<AgentRecord> {
        let candidates = self.find_available_agents(required_skills).await;
        let mut rr_counter = self.rr_counter.write().await;
        super::select_best_agent(candidates, strategy, &mut rr_counter)
    }

    async fn resolve_target(&self, _target_uri: &str) -> Vec<String> {
        // HTTP registry could query external API for target resolution
        // For now, return empty list - CC addon should override if needed
        vec![]
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_http_registry_creation() {
        let registry = HttpRegistry::new(
            "https://api.example.com".to_string(),
            Some("test-api-key".to_string()),
        );

        assert_eq!(registry.base_url, "https://api.example.com");
        assert_eq!(registry.api_key, Some("test-api-key".to_string()));
    }

    #[test]
    fn test_parse_agent_from_json() {
        let json = serde_json::json!({
            "agent_id": "agent-001",
            "display_name": "Alice",
            "uri": "sip:1001@localhost",
            "skills": ["support", "sales"],
            "max_concurrency": 2,
            "current_calls": 0,
            "presence": "available",
            "total_calls_handled": 10,
            "total_talk_time_secs": 3600,
        });

        let agent = HttpRegistry::parse_agent_from_json(&json).unwrap();
        assert_eq!(agent.agent_id, "agent-001");
        assert_eq!(agent.display_name, "Alice");
        assert_eq!(agent.skills, vec!["support", "sales"]);
        assert_eq!(agent.max_concurrency, 2);
        assert!(matches!(agent.presence, PresenceState::Available));
    }
}