rvoip_call_engine/
lib.rs

1//! # RVOIP Call Engine
2//!
3//! A comprehensive call center orchestration engine built on top of the RVOIP SIP stack.
4//! This crate provides enterprise-grade call center functionality including agent management,
5//! call queuing, intelligent routing, and real-time monitoring.
6//!
7//! ## Overview
8//!
9//! The Call Engine is the heart of a modern call center system, providing:
10//!
11//! - **Call Orchestration**: Central coordination of agent-customer calls with SIP bridge management
12//! - **Agent Management**: Registration, availability tracking, skill-based routing, and performance monitoring
13//! - **Call Queuing**: Priority-based queues with overflow policies and wait time management
14//! - **Intelligent Routing**: Business rules engine with skill matching and load balancing
15//! - **Real-time Monitoring**: Live dashboards, quality metrics, and supervisor tools
16//! - **Database Integration**: Persistent storage with SQLite (Limbo) for scalability
17//!
18//! ## Architecture
19//!
20//! The call center is built on a modular architecture:
21//!
22//! ```text
23//! ┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
24//! │   Client API    │    │  Supervisor API │    │    Admin API    │
25//! └─────────────────┘    └─────────────────┘    └─────────────────┘
26//!           │                       │                       │
27//!           └───────────────────────┼───────────────────────┘
28//!                                   │
29//!                      ┌─────────────────┐
30//!                      │ CallCenterEngine │
31//!                      └─────────────────┘
32//!                                   │
33//!           ┌───────────────────────┼───────────────────────┐
34//!           │                       │                       │
35//!  ┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
36//!  │  Agent Registry │    │  Queue Manager  │    │ Routing Engine  │
37//!  └─────────────────┘    └─────────────────┘    └─────────────────┘
38//!           │                       │                       │
39//!           └───────────────────────┼───────────────────────┘
40//!                                   │
41//!                        ┌─────────────────┐
42//!                        │ Session Manager │ (rvoip-session-core)
43//!                        └─────────────────┘
44//! ```
45//!
46//! ## Quick Start
47//!
48//! ### Basic Call Center Setup
49//!
50//! ```
51//! use rvoip_call_engine::prelude::*;
52//! 
53//! # async fn example() -> Result<()> {
54//! // Create configuration with sensible defaults
55//! let config = CallCenterConfig::default();
56//! 
57//! // Create call center with in-memory database for this example
58//! let call_center = CallCenterEngine::new(config, None).await?;
59//! 
60//! println!("Call center engine created successfully!");
61//! # Ok(())
62//! # }
63//! ```
64//!
65//! ### Agent Registration
66//!
67//! ```
68//! use rvoip_call_engine::prelude::*;
69//! 
70//! # async fn example() -> Result<()> {
71//! # let call_center = CallCenterEngine::new(CallCenterConfig::default(), None).await?;
72//! // Define an agent with skills and capabilities
73//! let agent = Agent {
74//!     id: "agent-001".to_string(),
75//!     sip_uri: "sip:alice@call-center.local".to_string(),
76//!     display_name: "Alice Johnson".to_string(),
77//!     skills: vec!["english".to_string(), "sales".to_string(), "tier1".to_string()],
78//!     max_concurrent_calls: 2,
79//!     status: AgentStatus::Available,
80//!     department: Some("sales".to_string()),
81//!     extension: Some("1001".to_string()),
82//! };
83//! 
84//! // Register the agent (this creates a SIP session)
85//! let session_id = call_center.register_agent(&agent).await?;
86//! println!("Agent {} registered with session ID: {}", agent.display_name, session_id);
87//! # Ok(())
88//! # }
89//! ```
90//!
91//! ### Advanced Routing Configuration
92//!
93//! ```
94//! use rvoip_call_engine::prelude::*;
95//! 
96//! # async fn example() -> Result<()> {
97//! let mut config = CallCenterConfig::default();
98//! 
99//! // Configure skill-based routing
100//! config.routing.default_strategy = RoutingStrategy::SkillBased;
101//! config.routing.enable_load_balancing = true;
102//! config.routing.load_balance_strategy = LoadBalanceStrategy::LeastBusy;
103//! 
104//! // Configure queue settings
105//! config.queues.default_max_wait_time = 300; // 5 minutes max wait
106//! config.queues.max_queue_size = 50;
107//! config.queues.enable_priorities = true;
108//! 
109//! // Configure agent settings
110//! config.agents.enable_skill_based_routing = true;
111//! config.agents.default_skills = vec!["general".to_string(), "english".to_string()];
112//! 
113//! let call_center = CallCenterEngine::new(config, None).await?;
114//! # Ok(())
115//! # }
116//! ```
117//!
118//! ### Monitoring and Statistics
119//!
120//! ```
121//! use rvoip_call_engine::prelude::*;
122//! 
123//! # async fn example() -> Result<()> {
124//! # let call_center = CallCenterEngine::new(CallCenterConfig::default(), None).await?;
125//! // Get real-time statistics
126//! let stats = call_center.get_stats().await;
127//! println!("Call Center Status:");
128//! println!("  Active calls: {}", stats.active_calls);
129//! println!("  Available agents: {}", stats.available_agents);
130//! println!("  Queued calls: {}", stats.queued_calls);
131//! println!("  Total calls handled: {}", stats.total_calls_handled);
132//! 
133//! // Get detailed routing statistics
134//! println!("Routing Performance:");
135//! println!("  Direct routes: {}", stats.routing_stats.calls_routed_directly);
136//! println!("  Queued calls: {}", stats.routing_stats.calls_queued);
137//! println!("  Rejected calls: {}", stats.routing_stats.calls_rejected);
138//! # Ok(())
139//! # }
140//! ```
141//!
142//! ## Key Modules
143//!
144//! - [`orchestrator`]: Core call center coordination and bridge management
145//! - [`agent`]: Agent registration, status tracking, and skill-based routing
146//! - [`queue`]: Call queuing with priorities and overflow handling
147//! - [`routing`]: Intelligent call routing engine with business rules
148//! - [`monitoring`]: Real-time monitoring, metrics collection, and analytics
149//! - [`api`]: Public APIs for client applications, supervisors, and administrators
150//! - [`integration`]: Session-core integration adapters and handlers
151//! - [`database`]: Persistent storage with Limbo SQLite database
152//! - [`config`]: Configuration management and validation
153//! - [`error`]: Comprehensive error handling and result types
154//!
155//! ## Integration with RVOIP Stack
156//!
157//! This crate integrates seamlessly with other RVOIP components:
158//!
159//! - **rvoip-session-core**: SIP session management and call handling
160//! - **rvoip-sip-core**: Low-level SIP protocol handling
161//! - **rvoip-media-core**: Audio processing and codec management
162//! - **rvoip-client-core**: Client-side integration for softphones
163//!
164//! ## Network Configuration
165//!
166//! The call engine properly respects and propagates configured bind addresses:
167//!
168//! ```
169//! use rvoip_call_engine::prelude::*;
170//! 
171//! # async fn example() -> Result<()> {
172//! // Configure specific IP addresses for your deployment
173//! let mut config = CallCenterConfig::default();
174//! config.general.local_signaling_addr = "127.0.0.1:5060".parse().unwrap();  // Use localhost for test
175//! config.general.local_media_addr = "127.0.0.1:20000".parse().unwrap();     // Same IP for media
176//! 
177//! // The engine ensures these addresses propagate to all layers
178//! let engine = CallCenterEngine::new(config, None).await?;
179//! # Ok(())
180//! # }
181//! ```
182//!
183//! Key points:
184//! - Configured IPs propagate through session-core to dialog-core and transport
185//! - No more hardcoded 0.0.0.0 addresses - your specific IP is used everywhere  
186//! - Media port range starts from the configured `local_media_addr` port
187//!
188//! For automatic media port allocation, the engine uses the port from `local_media_addr`
189//! as the base and allocates a range from there (typically +1000 ports).
190//!
191//! ## Production Deployment
192//!
193//! For production deployments, consider:
194//!
195//! - **Database**: Use a dedicated database file with regular backups
196//! - **Monitoring**: Enable real-time monitoring and quality alerts
197//! - **Security**: Configure proper authentication and authorization
198//! - **Scaling**: Monitor agent and call limits, scale horizontally as needed
199//! - **Network**: Ensure proper SIP and RTP port configuration with specific bind addresses
200//!
201//! ## Examples
202//!
203//! See the `examples/` directory for complete working examples:
204//!
205//! - `e2e_test/`: End-to-end call center testing setup
206//! - Basic call center server implementation
207//! - Agent client simulation
208//! - Load testing scenarios
209
210// Core modules
211pub mod error;
212pub mod config;
213
214// Call center functionality modules
215pub mod orchestrator;
216pub mod agent;
217pub mod queue;
218pub mod routing;
219pub mod monitoring;
220
221// External interfaces
222pub mod api;
223pub mod integration;
224pub mod server;
225
226// Database integration
227pub mod database;
228
229// Re-exports for convenience
230pub use error::{CallCenterError, Result};
231pub use config::CallCenterConfig;
232
233// **NEW**: Import the REAL CallCenterEngine with session-core integration
234pub use orchestrator::core::CallCenterEngine;
235
236// Export API types
237pub use api::{CallCenterClient, SupervisorApi, AdminApi};
238
239/// Call center statistics and performance metrics
240///
241/// This struct provides a snapshot of the call center's current operational state,
242/// including active calls, agent availability, and routing performance.
243#[derive(Debug, Clone)]
244pub struct CallCenterStats {
245    /// Number of currently active calls in the system
246    pub active_calls: usize,
247    /// Number of active SIP bridges connecting agents to customers
248    pub active_bridges: usize,
249    /// Total number of calls handled since startup
250    pub total_calls_handled: u64,
251}
252
253/// Prelude module for convenient imports
254///
255/// Import this module to get access to the most commonly used types and traits:
256///
257/// ```
258/// use rvoip_call_engine::prelude::*;
259/// ```
260pub mod prelude {
261    //! Commonly used types and traits for call center applications
262    //!
263    //! This module re-exports the most frequently used items from the call engine,
264    //! making it easy to get started with a single import.
265    
266    // **UPDATED**: Core types - now using REAL CallCenterEngine
267    pub use crate::{CallCenterError, CallCenterConfig, Result, CallCenterStats};
268    
269    // **NEW**: Real CallCenterEngine with session-core integration
270    pub use crate::orchestrator::core::CallCenterEngine;
271    
272    // Configuration types
273    pub use crate::config::{
274        GeneralConfig, AgentConfig, QueueConfig, RoutingConfig, MonitoringConfig, DatabaseConfig,
275        RoutingStrategy, LoadBalanceStrategy,
276    };
277    
278    // Orchestrator types - import from correct modules
279    pub use crate::orchestrator::{
280        BridgeManager, CallLifecycleManager,
281        CallInfo, CallStatus, RoutingDecision, OrchestratorStats,
282    };
283    pub use crate::orchestrator::bridge::{BridgeType, CallCenterBridgeConfig, BridgeStats};
284    
285    // Agent types - import from correct modules
286    pub use crate::agent::{
287        AgentRegistry, Agent, AgentId, AgentStatus, SkillBasedRouter, AvailabilityTracker,
288    };
289    pub use crate::agent::registry::AgentStats;
290    
291    // Queue types - import from correct modules
292    pub use crate::queue::{
293        QueueManager, CallQueue, QueuePolicies, OverflowHandler,
294    };
295    pub use crate::queue::manager::{QueuedCall, QueueStats};
296    
297    // Routing types
298    pub use crate::routing::{
299        RoutingEngine, RoutingPolicies, SkillMatcher,
300    };
301    
302    // Monitoring types
303    pub use crate::monitoring::{
304        SupervisorMonitor, MetricsCollector, CallCenterEvents,
305    };
306    
307    // Database types
308    pub use crate::database::{
309        DatabaseManager,
310        DbAgent,
311        DbAgentStatus,
312        DbQueuedCall,
313        DbActiveCall,
314    };
315    
316    // Session-core integration types
317    pub use rvoip_session_core::{
318        // Basic session types
319        SessionId, CallSession, CallState,
320        // Session management
321        SessionCoordinator, SessionManagerBuilder,
322        // Call handling
323        CallHandler, IncomingCall, CallDecision,
324        // Bridge management  
325        BridgeId, BridgeInfo, BridgeEvent,
326    };
327    // StatusCode is available from session-core's types module
328    pub use rvoip_session_core::types::StatusCode;
329    
330    // Note: Uri, Request, Response, Method are no longer directly accessible
331    // Use session-core's high-level APIs instead
332    
333    // Common external types
334    pub use chrono::{DateTime, Utc};
335    pub use uuid::Uuid;
336} 
337
338pub use server::{CallCenterServer, CallCenterServerBuilder};