Skip to main content

ri/protocol/
mod.rs

1//! Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
2//!
3//! This file is part of Ri.
4//! The Ri project belongs to the Dunimd Team.
5//!
6//! Licensed under the Apache License, Version 2.0 (the "License");
7//! You may not use this file except in compliance with the License.
8//! You may obtain a copy of the License at
9//!
10//!     http://www.apache.org/licenses/LICENSE-2.0
11//!
12//! Unless required by applicable law or agreed to in writing, software
13//! distributed under the License is distributed on an "AS IS" BASIS,
14//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15//! See the License for the specific language governing permissions and
16//! limitations under the License.
17
18#![allow(non_snake_case)]
19
20//! # Protocol Module
21//!
22//! This module provides protocol implementations for Ri, including
23//! global protocol, private protocol, post-quantum cryptography, and
24//! integration features.
25//!
26//! ## Features
27//!
28//! - **RiProtocol**: Main protocol interface (trait definition)
29//! - **RiGlobalProtocol**: Global protocol implementation (basic implementation)
30//! - **RiPrivateProtocol**: Private protocol implementation (basic implementation)
31//! - **RiCrypto**: Cryptographic operations
32//! - **Post-Quantum Cryptography**: Kyber, Dilithium, Falcon implementations using liboqs
33//!
34//! ## Security Status
35//!
36//! This module now uses the **liboqs** library for post-quantum cryptography,
37//! which is:
38//! - The reference implementation from the NIST PQC competition
39//! - Actively maintained and regularly audited
40//! - **Suitable for production use**
41//!
42//! Post-Quantum Cryptography algorithms (Kyber, Dilithium, Falcon):
43//! - Based on NIST PQC competition algorithms
44//! - Have undergone formal security analysis
45//! - Constant-time implementations for side-channel resistance
46//! - Recommended for protecting sensitive data
47//!
48//! ## Recommendation
49//!
50//! For cryptographic operations, this module uses audited libraries:
51//! - liboqs - NIST PQC reference implementation
52//! - ring - Modern, audited crypto library
53//! - openssl - Industry-standard crypto library
54
55use std::collections::HashMap as FxHashMap;
56use std::sync::atomic::{AtomicU64, Ordering};
57use std::sync::Arc;
58use std::time::{SystemTime, UNIX_EPOCH};
59use async_trait::async_trait;
60use tokio::sync::RwLock;
61use serde::{Serialize, Deserialize};
62
63use crate::core::{RiResult, RiError};
64
65#[cfg(feature = "pyo3")]
66use pyo3::prelude::*;
67
68/// Frame definitions for binary protocol encoding
69pub mod frames;
70pub use frames::{RiFrameBuilder, RiFrameParser};
71
72/// Post-quantum cryptography modules (requires oqs feature)
73#[cfg(feature = "oqs")]
74pub mod kyber;
75#[cfg(feature = "oqs")]
76pub mod dilithium;
77#[cfg(feature = "oqs")]
78pub mod falcon;
79#[cfg(feature = "oqs")]
80pub mod post_quantum;
81#[cfg(feature = "oqs")]
82pub use post_quantum::{
83    KyberKEM, KyberPublicKey, KyberSecretKey, KyberCiphertext,
84    DilithiumSigner, DilithiumPublicKey, DilithiumSecretKey, DilithiumSignature,
85    FalconSigner, FalconPublicKey, FalconSecretKey, FalconSignature,
86    RiPostQuantumAlgorithm, KEMResult,
87};
88
89/// Advanced protocol features (future/experimental)
90/// These modules are not yet fully stabilized and may change in future versions.
91/// Enable with `protocol-advanced` feature.
92#[cfg(feature = "protocol-advanced")]
93pub mod adapter;
94#[cfg(feature = "protocol-advanced")]
95pub mod crypto;
96#[cfg(feature = "protocol-advanced")]
97pub mod global_state;
98#[cfg(feature = "protocol-advanced")]
99pub mod guomi;
100#[cfg(feature = "protocol-advanced")]
101pub mod hsm;
102#[cfg(feature = "protocol-advanced")]
103pub mod private;
104#[cfg(feature = "protocol-advanced")]
105pub mod security;
106#[cfg(feature = "protocol-advanced")]
107pub mod integration;
108
109/// Protocol type enumeration
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, std::hash::Hash)]
111#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
112pub enum RiProtocolType {
113    /// Standard global protocol
114    Global = 0,
115    /// Enhanced private protocol
116    Private = 1,
117}
118
119/// Protocol status
120#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
121#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
122pub enum RiProtocolStatus {
123    /// Protocol is inactive
124    Inactive,
125    /// Protocol is initializing
126    Initializing,
127    /// Protocol is ready
128    Ready,
129    /// Protocol has an error
130    Error,
131}
132
133/// Connection state
134#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
135#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
136pub enum RiConnectionState {
137    /// Connection is disconnected
138    Disconnected,
139    /// Connection is connecting
140    Connecting,
141    /// Connection is connected
142    Connected,
143    /// Connection is disconnecting
144    Disconnecting,
145}
146
147/// Security level
148#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
149#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
150pub enum RiSecurityLevel {
151    /// No security
152    None,
153    /// Standard security
154    Standard,
155    /// High security
156    High,
157    /// Military-grade security
158    Military,
159}
160
161/// Protocol configuration
162#[derive(Debug, Clone, Serialize, Deserialize)]
163#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
164pub struct RiProtocolConfig {
165    /// Default protocol type
166    pub default_protocol: RiProtocolType,
167    /// Whether security is enabled
168    pub enable_security: bool,
169    /// Security level
170    pub security_level: RiSecurityLevel,
171    /// Whether state synchronization is enabled
172    pub enable_state_sync: bool,
173    /// Whether performance optimization is enabled
174    pub performance_optimization: bool,
175}
176
177impl Default for RiProtocolConfig {
178    fn default() -> Self {
179        Self {
180            default_protocol: RiProtocolType::Global,
181            enable_security: true,
182            security_level: RiSecurityLevel::Standard,
183            enable_state_sync: true,
184            performance_optimization: true,
185        }
186    }
187}
188
189impl RiProtocolConfig {
190    /// Validate the configuration.
191    pub fn validate(&self) -> RiResult<()> {
192        if self.security_level == RiSecurityLevel::None && self.enable_security {
193            return Err(RiError::Config(
194                "Security level cannot be None when security is enabled".to_string()
195            ));
196        }
197
198        Ok(())
199    }
200
201    /// Create a secure configuration.
202    pub fn secure() -> Self {
203        Self {
204            default_protocol: RiProtocolType::Private,
205            enable_security: true,
206            security_level: RiSecurityLevel::High,
207            enable_state_sync: true,
208            performance_optimization: true,
209        }
210    }
211
212    /// Create a maximum security configuration with post-quantum cryptography.
213    pub fn maximum_security() -> Self {
214        Self {
215            default_protocol: RiProtocolType::Private,
216            enable_security: true,
217            security_level: RiSecurityLevel::Military,
218            enable_state_sync: true,
219            performance_optimization: false,
220        }
221    }
222}
223
224/// Protocol statistics
225#[derive(Debug, Clone, Serialize, Deserialize)]
226#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
227pub struct RiProtocolStats {
228    /// Total messages sent
229    pub messages_sent: u64,
230    /// Total messages received
231    pub messages_received: u64,
232    /// Total bytes sent
233    pub bytes_sent: u64,
234    /// Total bytes received
235    pub bytes_received: u64,
236    /// Total errors
237    pub errors: u64,
238    /// Average latency in milliseconds
239    pub avg_latency_ms: f64,
240}
241
242impl RiProtocolStats {
243    pub fn new() -> Self {
244        Self {
245            messages_sent: 0,
246            messages_received: 0,
247            bytes_sent: 0,
248            bytes_received: 0,
249            errors: 0,
250            avg_latency_ms: 0.0,
251        }
252    }
253
254    pub fn record_sent(&mut self, bytes: usize) {
255        self.messages_sent += 1;
256        self.bytes_sent += bytes as u64;
257    }
258
259    pub fn record_received(&mut self, bytes: usize) {
260        self.messages_received += 1;
261        self.bytes_received += bytes as u64;
262    }
263
264    pub fn record_error(&mut self) {
265        self.errors += 1;
266    }
267}
268
269/// Connection statistics
270#[derive(Debug, Clone, Serialize, Deserialize)]
271#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
272pub struct RiConnectionStats {
273    /// Total connections
274    pub total_connections: u64,
275    /// Active connections
276    pub active_connections: u64,
277    /// Total bytes sent
278    pub bytes_sent: u64,
279    /// Total bytes received
280    pub bytes_received: u64,
281    /// Connection duration in seconds
282    pub connection_duration_secs: u64,
283}
284
285impl Default for RiConnectionStats {
286    fn default() -> Self {
287        Self {
288            total_connections: 0,
289            active_connections: 0,
290            bytes_sent: 0,
291            bytes_received: 0,
292            connection_duration_secs: 0,
293        }
294    }
295}
296
297/// Protocol health status
298#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
299#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
300pub enum RiProtocolHealth {
301    /// Healthy
302    Healthy,
303    /// Degraded
304    Degraded,
305    /// Unhealthy
306    Unhealthy,
307    /// Unknown
308    Unknown,
309}
310
311impl Default for RiProtocolHealth {
312    fn default() -> Self {
313        RiProtocolHealth::Unknown
314    }
315}
316
317/// Message flags for protocol messages
318#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
319#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
320pub struct RiMessageFlags {
321    /// Whether the message is compressed
322    pub compressed: bool,
323    /// Whether the message is encrypted
324    pub encrypted: bool,
325    /// Whether the message requires acknowledgment
326    pub requires_ack: bool,
327    /// Whether this is a priority message
328    pub priority: bool,
329}
330
331impl Default for RiMessageFlags {
332    fn default() -> Self {
333        Self {
334            compressed: false,
335            encrypted: false,
336            requires_ack: false,
337            priority: false,
338        }
339    }
340}
341
342/// Connection information
343#[derive(Debug, Clone, Serialize, Deserialize)]
344#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
345pub struct RiConnectionInfo {
346    /// Connection ID
347    pub connection_id: String,
348    /// Remote device ID
349    pub device_id: String,
350    /// Connection address
351    pub address: String,
352    /// Protocol type
353    pub protocol_type: RiProtocolType,
354    /// Connection state
355    pub state: RiConnectionState,
356    /// Security level
357    pub security_level: RiSecurityLevel,
358    /// Connection timestamp
359    pub connected_at: u64,
360    /// Last activity timestamp
361    pub last_activity: u64,
362}
363
364impl Default for RiConnectionInfo {
365    fn default() -> Self {
366        Self {
367            connection_id: String::new(),
368            device_id: String::new(),
369            address: String::new(),
370            protocol_type: RiProtocolType::Global,
371            state: RiConnectionState::Disconnected,
372            security_level: RiSecurityLevel::None,
373            connected_at: 0,
374            last_activity: 0,
375        }
376    }
377}
378
379/// Frame type enumeration
380#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
381#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
382pub enum RiFrameType {
383    /// Data frame
384    Data = 0,
385    /// Control frame
386    Control = 1,
387    /// Heartbeat frame
388    Heartbeat = 2,
389    /// Acknowledgment frame
390    Ack = 3,
391    /// Error frame
392    Error = 4,
393}
394
395/// Frame header
396#[derive(Debug, Clone, Serialize, Deserialize)]
397#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
398pub struct RiFrameHeader {
399    /// Protocol version (major.minor as u8)
400    pub version: u8,
401    /// Frame type
402    pub frame_type: RiFrameType,
403    /// Sequence number
404    pub sequence_number: u64,
405    /// Message length
406    pub length: u32,
407    /// Timestamp
408    pub timestamp: u64,
409    /// Flags
410    pub flags: u16,
411    /// Authentication tag offset (for authenticated frames)
412    pub auth_tag_offset: u16,
413}
414
415impl Default for RiFrameHeader {
416    fn default() -> Self {
417        Self {
418            version: 1,
419            frame_type: RiFrameType::Data,
420            sequence_number: 0,
421            length: 0,
422            timestamp: 0,
423            flags: 0,
424            auth_tag_offset: 0,
425        }
426    }
427}
428
429impl RiFrameHeader {
430    /// Get major version number.
431    pub fn major_version(&self) -> u8 {
432        self.version >> 4
433    }
434
435    /// Get minor version number.
436    pub fn minor_version(&self) -> u8 {
437        self.version & 0x0F
438    }
439
440    /// Check if a feature is supported.
441    pub fn supports_feature(&self, feature: u16) -> bool {
442        (self.flags & feature) != 0
443    }
444}
445
446/// Protocol frame
447#[derive(Debug, Clone, Serialize, Deserialize)]
448#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
449pub struct RiFrame {
450    /// Frame header
451    pub header: RiFrameHeader,
452    /// Frame payload
453    pub payload: Vec<u8>,
454    /// Source device ID
455    pub source_id: String,
456    /// Target device ID
457    pub target_id: String,
458}
459
460impl Default for RiFrame {
461    fn default() -> Self {
462        Self {
463            header: RiFrameHeader::default(),
464            payload: Vec::new(),
465            source_id: String::new(),
466            target_id: String::new(),
467        }
468    }
469}
470
471/// Core protocol trait
472#[async_trait]
473pub trait RiProtocol {
474    /// Get protocol type
475    fn protocol_type(&self) -> RiProtocolType;
476    
477    /// Check if protocol is ready
478    async fn is_ready(&self) -> bool;
479    
480    /// Initialize protocol
481    async fn initialize(&mut self, config: RiProtocolConfig) -> RiResult<()>;
482    
483    /// Send message
484    async fn send_message(&mut self, target: &str, data: &[u8]) -> RiResult<Vec<u8>>;
485    
486    /// Send message with flags
487    async fn send_message_with_flags(&mut self, target: &str, data: &[u8], flags: RiMessageFlags) -> RiResult<Vec<u8>>;
488    
489    /// Receive message
490    async fn receive_message(&mut self) -> RiResult<Vec<u8>>;
491    
492    /// Get connection info
493    async fn get_connection_info(&self, connection_id: &str) -> RiResult<RiConnectionInfo>;
494    
495    /// Close connection
496    async fn close_connection(&mut self, connection_id: &str) -> RiResult<()>;
497    
498    /// Get protocol statistics
499    fn get_stats(&self) -> RiProtocolStats;
500    
501    /// Get protocol health
502    async fn get_health(&self) -> RiProtocolHealth;
503    
504    /// Shutdown protocol
505    async fn shutdown(&mut self) -> RiResult<()>;
506}
507
508/// Protocol connection trait
509#[async_trait]
510pub trait RiProtocolConnection {
511    /// Get connection ID
512    fn connection_id(&self) -> &str;
513    
514    /// Get remote device ID
515    fn remote_device_id(&self) -> &str;
516    
517    /// Get protocol type
518    fn protocol_type(&self) -> RiProtocolType;
519    
520    /// Check if connection is active
521    fn is_active(&self) -> bool;
522    
523    /// Send data
524    async fn send(&mut self, data: &[u8]) -> RiResult<usize>;
525    
526    /// Receive data
527    async fn receive(&mut self, buffer: &mut [u8]) -> RiResult<usize>;
528    
529    /// Get statistics
530    fn get_stats(&self) -> RiConnectionStats;
531    
532    /// Close connection
533    async fn close(&mut self) -> RiResult<()>;
534}
535
536/// Protocol manager
537#[derive(Debug, Clone)]
538#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
539pub struct RiProtocolManager {
540    /// Protocol statistics
541    pub stats: Arc<RwLock<RiProtocolStats>>,
542    /// Default protocol type
543    pub default_protocol: RiProtocolType,
544    /// Active connections
545    connections: Arc<RwLock<FxHashMap<String, RiConnectionInfo>>>,
546    /// Message sequence counter
547    sequence_counter: Arc<AtomicU64>,
548    /// Protocol initialized state
549    /// Exposed to Python bindings; read by the pyo3 wrapper, not by the Rust impl.
550    #[allow(dead_code)]
551    initialized: Arc<RwLock<bool>>,
552}
553
554#[cfg(test)]
555mod protocol_tests {
556    use super::*;
557
558    #[test]
559    fn test_protocol_config_default() {
560        let config = RiProtocolConfig::default();
561        assert_eq!(config.default_protocol, RiProtocolType::Global);
562        assert!(config.enable_security);
563        assert_eq!(config.security_level, RiSecurityLevel::Standard);
564    }
565
566    #[test]
567    fn test_protocol_config_secure() {
568        let config = RiProtocolConfig::secure();
569        assert_eq!(config.default_protocol, RiProtocolType::Private);
570        assert!(config.enable_security);
571        assert_eq!(config.security_level, RiSecurityLevel::High);
572    }
573
574    #[test]
575    fn test_protocol_config_maximum_security() {
576        let config = RiProtocolConfig::maximum_security();
577        assert_eq!(config.default_protocol, RiProtocolType::Private);
578        assert!(config.enable_security);
579        assert_eq!(config.security_level, RiSecurityLevel::Military);
580    }
581
582    #[test]
583    fn test_protocol_config_validation() {
584        let mut config = RiProtocolConfig::default();
585
586        // Valid config should pass
587        assert!(config.validate().is_ok());
588
589        // None security level with security enabled should fail
590        config.security_level = RiSecurityLevel::None;
591        assert!(config.validate().is_err());
592    }
593
594    #[test]
595    fn test_frame_header_version() {
596        let header = RiFrameHeader::default();
597        assert_eq!(header.major_version(), 0);
598        assert_eq!(header.minor_version(), 1);
599    }
600
601    #[test]
602    fn test_frame_header_supports_feature() {
603        let header = RiFrameHeader {
604            flags: 0b00000011,
605            ..Default::default()
606        };
607
608        assert!(header.supports_feature(0b00000001));
609        assert!(header.supports_feature(0b00000010));
610        assert!(!header.supports_feature(0b00000100));
611    }
612
613    #[test]
614    fn test_protocol_stats() {
615        let stats = RiProtocolStats::new();
616        assert_eq!(stats.messages_sent, 0);
617        assert_eq!(stats.messages_received, 0);
618        assert_eq!(stats.errors, 0);
619    }
620
621    #[test]
622    fn test_connection_info() {
623        let mut info = RiConnectionInfo::default();
624        info.device_id = "test-device".to_string();
625        info.state = RiConnectionState::Connected;
626        assert_eq!(info.device_id, "test-device");
627        assert_eq!(info.state, RiConnectionState::Connected);
628        assert_eq!(info.security_level, RiSecurityLevel::None);
629    }
630
631    #[test]
632    fn test_protocol_type_values() {
633        assert_eq!(RiProtocolType::Global as u8, 0);
634        assert_eq!(RiProtocolType::Private as u8, 1);
635    }
636
637    #[test]
638    fn test_security_level_values() {
639        assert_eq!(RiSecurityLevel::None as u8, 0);
640        assert_eq!(RiSecurityLevel::Standard as u8, 1);
641        assert_eq!(RiSecurityLevel::High as u8, 2);
642        assert_eq!(RiSecurityLevel::Military as u8, 3);
643    }
644}
645
646#[cfg(feature = "pyo3")]
647#[pyo3::prelude::pymethods]
648impl RiProtocolManager {
649    #[new]
650    fn new_py() -> Self {
651        Self::new()
652    }
653    
654    #[getter]
655    fn get_stats_py(&self) -> RiProtocolStats {
656        self.stats.try_read()
657            .map(|guard| guard.clone())
658            .unwrap_or_else(|_| RiProtocolStats::new())
659    }
660    
661    #[getter]
662    fn get_default_protocol_py(&self) -> RiProtocolType {
663        self.default_protocol
664    }
665    
666    /// Initialize manager
667    pub fn initialize(&mut self, config: RiProtocolConfig) -> PyResult<()> {
668        self.default_protocol = config.default_protocol;
669        
670        let mut initialized = self.initialized.try_write()
671            .map_err(|_| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(
672                "Failed to acquire write lock on initialized state"))?;
673        *initialized = true;
674        
675        Ok(())
676    }
677}
678
679impl RiProtocolManager {
680    pub fn new() -> Self {
681        Self {
682            stats: Arc::new(RwLock::new(RiProtocolStats::new())),
683            default_protocol: RiProtocolType::Global,
684            connections: Arc::new(RwLock::new(FxHashMap::default())),
685            sequence_counter: Arc::new(AtomicU64::new(0)),
686            initialized: Arc::new(RwLock::new(false)),
687        }
688    }
689
690    /// Returns the number of currently registered connections.
691    pub fn get_connection_count(&self) -> usize {
692        self.connections
693            .try_read()
694            .map(|guard| guard.len())
695            .unwrap_or(0)
696    }
697
698    /// Send message (sync version, also exposed via C FFI and Python).
699    pub fn send_message(&self, target: &str, data: &[u8]) -> Vec<u8> {
700        let timestamp = SystemTime::now()
701            .duration_since(UNIX_EPOCH)
702            .unwrap_or_default()
703            .as_millis() as u64;
704
705        let sequence = self.sequence_counter.fetch_add(1, Ordering::SeqCst);
706
707        let frame = RiFrame {
708            header: RiFrameHeader {
709                version: 1,
710                frame_type: RiFrameType::Data,
711                sequence_number: sequence,
712                length: data.len() as u32,
713                timestamp,
714                flags: 0,
715                auth_tag_offset: 0,
716            },
717            payload: data.to_vec(),
718            source_id: String::from("protocol_manager"),
719            target_id: target.to_string(),
720        };
721
722        let serialized = match serde_json::to_vec(&frame) {
723            Ok(serialized_data) => serialized_data,
724            Err(e) => {
725                if let Ok(mut stats) = self.stats.try_write() {
726                    stats.record_error();
727                }
728                let error_response = RiProtocolResponse {
729                    success: false,
730                    sequence_number: sequence,
731                    target_id: target.to_string(),
732                    response_data: format!("Serialization error: {}", e).into_bytes(),
733                    timestamp,
734                };
735                return serde_json::to_vec(&error_response)
736                    .unwrap_or_else(|_| b"{\"success\":false,\"error\":\"Serialization failed\"}".to_vec());
737            }
738        };
739
740        let payload_len = serialized.len();
741        if let Ok(mut stats) = self.stats.try_write() {
742            stats.record_sent(payload_len);
743        }
744
745        let response_data = self.build_response_data(target, &frame, sequence, timestamp);
746
747        let response = RiProtocolResponse {
748            success: true,
749            sequence_number: sequence,
750            target_id: target.to_string(),
751            response_data,
752            timestamp,
753        };
754
755        self.stats.try_write()
756            .map(|mut stats| stats.record_received(response.response_data.len()))
757            .map_err(|e| tracing::error!("Failed to update protocol stats: {}", e))
758            .ok();
759
760        serde_json::to_vec(&response).unwrap_or_else(|_| b"{\"success\":true,\"message\":\"Message sent\"}".to_vec())
761    }
762
763    fn build_response_data(&self, target: &str, frame: &RiFrame, sequence: u64, timestamp: u64) -> Vec<u8> {
764        let mut response = FxHashMap::<String, serde_json::Value>::new();
765
766        response.insert("status".to_string(), serde_json::Value::String("delivered".to_string()));
767        response.insert("target".to_string(), serde_json::Value::String(target.to_string()));
768        response.insert("source".to_string(), serde_json::Value::String(frame.source_id.clone()));
769        response.insert("sequence".to_string(), serde_json::Value::Number(sequence.into()));
770        response.insert("timestamp".to_string(), serde_json::Value::Number(timestamp.into()));
771        response.insert("frame_type".to_string(), serde_json::Value::String(format!("{:?}", frame.header.frame_type)));
772        response.insert("payload_size".to_string(), serde_json::Value::Number(serde_json::Number::from(frame.payload.len())));
773        response.insert("protocol".to_string(), serde_json::Value::String(format!("{:?}", self.default_protocol)));
774
775        let delivery_info = serde_json::json!({
776            "delivered_at": timestamp,
777            "hops": 1,
778            "route": [frame.source_id.clone(), target.to_string()]
779        });
780        response.insert("delivery".to_string(), delivery_info);
781
782        serde_json::to_vec(&response).unwrap_or_default()
783    }
784
785    /// Send message with flags (sync version).
786    pub fn send_message_with_flags(&self, target: &str, data: &[u8], _flags: RiMessageFlags) -> Vec<u8> {
787        self.send_message(target, data)
788    }
789
790    /// Get connection info (sync version).
791    pub fn get_connection_info(&self, connection_id: &str) -> Option<RiConnectionInfo> {
792        self.connections.try_read()
793            .ok()
794            .and_then(|connections| connections.get(connection_id).cloned())
795    }
796
797    /// Close connection (sync version).
798    pub fn close_connection(&mut self, connection_id: &str) -> bool {
799        self.connections.try_write()
800            .ok()
801            .map(|mut connections| connections.remove(connection_id).is_some())
802            .unwrap_or(false)
803    }
804}
805
806impl Default for RiProtocolManager {
807    fn default() -> Self {
808        Self::new()
809    }
810}
811
812/// Protocol response structure
813#[derive(Debug, Clone, Serialize, Deserialize)]
814#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
815pub struct RiProtocolResponse {
816    /// Whether the operation was successful
817    pub success: bool,
818    /// Sequence number matching the request
819    pub sequence_number: u64,
820    /// Target ID that was addressed
821    pub target_id: String,
822    /// Response data payload
823    pub response_data: Vec<u8>,
824    /// Timestamp of the original request
825    pub timestamp: u64,
826}
827
828impl Default for RiProtocolResponse {
829    fn default() -> Self {
830        Self {
831            success: false,
832            sequence_number: 0,
833            target_id: String::new(),
834            response_data: Vec::new(),
835            timestamp: 0,
836        }
837    }
838}
839
840#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
841pub enum ProtocolError {
842    #[error("Target not found: {target_id}")]
843    TargetNotFound { target_id: String },
844    #[error("Send failed: {message}")]
845    SendFailed { message: String },
846    #[error("Protocol not initialized")]
847    NotInitialized,
848    #[error("Invalid state: {state}")]
849    InvalidState { state: String },
850    #[error("Connection not found: {connection_id}")]
851    ConnectionNotFound { connection_id: String },
852    #[error("Serialization error: {message}")]
853    Serialization { message: String },
854    #[error("Operation not supported for this protocol")]
855    NotSupported,
856}
857
858impl From<ProtocolError> for RiError {
859    fn from(error: ProtocolError) -> Self {
860        RiError::Other(format!("Protocol error: {}", error))
861    }
862}
863
864impl From<serde_json::Error> for ProtocolError {
865    fn from(error: serde_json::Error) -> Self {
866        ProtocolError::Serialization { message: error.to_string() }
867    }
868}
869
870impl From<ProtocolError> for RiResult<()> {
871    fn from(error: ProtocolError) -> Self {
872        Err(error.into())
873    }
874}
875
876#[derive(Debug, Clone)]
877pub struct RiBaseProtocol {
878    config: RiProtocolConfig,
879    stats: Arc<RwLock<RiProtocolStats>>,
880    connections: Arc<RwLock<FxHashMap<String, RiConnectionInfo>>>,
881    sequence_counter: Arc<AtomicU64>,
882    initialized: Arc<RwLock<bool>>,
883    _receiver_id: String,
884}
885
886impl RiBaseProtocol {
887    pub fn new(receiver_id: String) -> Self {
888        Self {
889            config: RiProtocolConfig::default(),
890            stats: Arc::new(RwLock::new(RiProtocolStats::new())),
891            connections: Arc::new(RwLock::new(FxHashMap::default())),
892            sequence_counter: Arc::new(AtomicU64::new(0)),
893            initialized: Arc::new(RwLock::new(false)),
894            _receiver_id: receiver_id,
895        }
896    }
897    
898    pub async fn is_ready(&self) -> bool {
899        *self.initialized.read().await
900    }
901    
902    pub async fn initialize(&mut self, config: RiProtocolConfig) {
903        self.config = config;
904        *self.initialized.write().await = true;
905    }
906
907    pub async fn send_message(&mut self, _target: &str, data: &[u8]) -> RiResult<Vec<u8>> {
908        if !*self.initialized.read().await {
909            return Err(ProtocolError::NotInitialized.into());
910        }
911
912        let sequence = self.sequence_counter.fetch_add(1, Ordering::SeqCst) as u32;
913
914        self.stats.write().await.record_sent(data.len());
915
916        let mut builder = RiFrameBuilder::new();
917        builder.set_sequence(sequence);
918        let frame = builder.build_data_frame(data.to_vec())
919            .map_err(|e| ProtocolError::Serialization {
920                message: e.to_string()
921            })?;
922
923        let frame_bytes = frame.to_bytes()
924            .map_err(|e| ProtocolError::Serialization {
925                message: e.to_string()
926            })?;
927
928        self.stats.write().await.record_received(frame_bytes.len());
929
930        Ok(frame_bytes)
931    }
932    
933    pub async fn receive_message(&mut self) -> RiResult<Vec<u8>> {
934        if !*self.initialized.read().await {
935            return Err(ProtocolError::NotInitialized.into());
936        }
937
938        let sequence = self.sequence_counter.fetch_add(1, Ordering::SeqCst) as u32;
939
940        let mut builder = RiFrameBuilder::new();
941        builder.set_sequence(sequence);
942        let frame = builder.build_keepalive_frame()
943            .map_err(|e| ProtocolError::Serialization {
944                message: e.to_string()
945            })?;
946
947        let frame_bytes = frame.to_bytes()
948            .map_err(|e| ProtocolError::Serialization {
949                message: e.to_string()
950            })?;
951
952        self.stats.write().await.record_received(0);
953
954        Ok(frame_bytes)
955    }
956    
957    pub async fn get_connection_info(&self, connection_id: &str) -> RiResult<RiConnectionInfo> {
958        let connections = self.connections.read().await;
959        connections.get(connection_id)
960            .cloned()
961            .ok_or_else(|| ProtocolError::ConnectionNotFound {
962                connection_id: connection_id.to_string()
963            }.into())
964    }
965    
966    pub async fn close_connection(&mut self, connection_id: &str) -> RiResult<()> {
967        let mut connections = self.connections.write().await;
968        if connections.remove(connection_id).is_some() {
969            Ok(())
970        } else {
971            Err(ProtocolError::ConnectionNotFound {
972                connection_id: connection_id.to_string()
973            }.into())
974        }
975    }
976    
977    pub fn get_stats(&self) -> RiProtocolStats {
978        self.stats.try_read()
979            .map(|guard| guard.clone())
980            .unwrap_or_else(|_| RiProtocolStats::new())
981    }
982    
983    pub async fn get_health(&self) -> RiProtocolHealth {
984        if *self.initialized.read().await {
985            RiProtocolHealth::Healthy
986        } else {
987            RiProtocolHealth::Unknown
988        }
989    }
990    
991    pub async fn shutdown(&mut self) {
992        *self.initialized.write().await = false;
993    }
994}
995
996#[derive(Debug, Clone)]
997#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
998pub struct RiGlobalProtocol {
999    base: RiBaseProtocol,
1000}
1001
1002impl RiGlobalProtocol {
1003    pub fn new() -> Self {
1004        Self {
1005            base: RiBaseProtocol::new(String::from("receiver")),
1006        }
1007    }
1008}
1009
1010impl Default for RiGlobalProtocol {
1011    fn default() -> Self {
1012        Self::new()
1013    }
1014}
1015
1016#[async_trait]
1017impl RiProtocol for RiGlobalProtocol {
1018    fn protocol_type(&self) -> RiProtocolType {
1019        RiProtocolType::Global
1020    }
1021
1022    async fn is_ready(&self) -> bool {
1023        self.base.is_ready().await
1024    }
1025
1026    async fn initialize(&mut self, config: RiProtocolConfig) -> RiResult<()> {
1027        self.base.initialize(config).await;
1028        Ok(())
1029    }
1030
1031    async fn send_message(&mut self, target: &str, data: &[u8]) -> RiResult<Vec<u8>> {
1032        self.base.send_message(target, data).await
1033    }
1034
1035    async fn send_message_with_flags(&mut self, target: &str, data: &[u8], flags: RiMessageFlags) -> RiResult<Vec<u8>> {
1036        let response = self.base.send_message(target, data).await?;
1037        if flags.encrypted {
1038            self.base.stats.write().await.record_error();
1039        }
1040        Ok(response)
1041    }
1042
1043    async fn receive_message(&mut self) -> RiResult<Vec<u8>> {
1044        self.base.receive_message().await
1045    }
1046
1047    async fn get_connection_info(&self, connection_id: &str) -> RiResult<RiConnectionInfo> {
1048        self.base.get_connection_info(connection_id).await
1049    }
1050
1051    async fn close_connection(&mut self, connection_id: &str) -> RiResult<()> {
1052        self.base.close_connection(connection_id).await
1053    }
1054
1055    fn get_stats(&self) -> RiProtocolStats {
1056        self.base.get_stats()
1057    }
1058
1059    async fn get_health(&self) -> RiProtocolHealth {
1060        self.base.get_health().await
1061    }
1062
1063    async fn shutdown(&mut self) -> RiResult<()> {
1064        self.base.shutdown().await;
1065        Ok(())
1066    }
1067}
1068
1069#[derive(Debug, Clone)]
1070#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
1071pub struct RiPrivateProtocol {
1072    base: RiBaseProtocol,
1073}
1074
1075impl RiPrivateProtocol {
1076    pub fn new() -> Self {
1077        Self {
1078            base: RiBaseProtocol::new(String::from("private_receiver")),
1079        }
1080    }
1081}
1082
1083impl Default for RiPrivateProtocol {
1084    fn default() -> Self {
1085        Self::new()
1086    }
1087}
1088
1089#[async_trait]
1090impl RiProtocol for RiPrivateProtocol {
1091    fn protocol_type(&self) -> RiProtocolType {
1092        RiProtocolType::Private
1093    }
1094
1095    async fn is_ready(&self) -> bool {
1096        self.base.is_ready().await
1097    }
1098
1099    async fn initialize(&mut self, config: RiProtocolConfig) -> RiResult<()> {
1100        self.base.initialize(config).await;
1101        Ok(())
1102    }
1103
1104    async fn send_message(&mut self, target: &str, data: &[u8]) -> RiResult<Vec<u8>> {
1105        self.base.send_message(target, data).await
1106    }
1107
1108    async fn send_message_with_flags(&mut self, target: &str, data: &[u8], flags: RiMessageFlags) -> RiResult<Vec<u8>> {
1109        let response = self.base.send_message(target, data).await?;
1110        if !flags.encrypted {
1111            self.base.stats.write().await.record_error();
1112        }
1113        Ok(response)
1114    }
1115
1116    async fn receive_message(&mut self) -> RiResult<Vec<u8>> {
1117        self.base.receive_message().await
1118    }
1119
1120    async fn get_connection_info(&self, connection_id: &str) -> RiResult<RiConnectionInfo> {
1121        self.base.get_connection_info(connection_id).await
1122    }
1123
1124    async fn close_connection(&mut self, connection_id: &str) -> RiResult<()> {
1125        self.base.close_connection(connection_id).await
1126    }
1127
1128    fn get_stats(&self) -> RiProtocolStats {
1129        self.base.get_stats()
1130    }
1131
1132    async fn get_health(&self) -> RiProtocolHealth {
1133        self.base.get_health().await
1134    }
1135
1136    async fn shutdown(&mut self) -> RiResult<()> {
1137        self.base.shutdown().await;
1138        Ok(())
1139    }
1140}
1141
1142#[cfg(feature = "pyo3")]
1143#[pyo3::prelude::pymethods]
1144impl RiGlobalProtocol {
1145    pub fn is_ready_sync(&self) -> bool {
1146        self.base.initialized.try_read()
1147            .map(|guard| *guard)
1148            .unwrap_or(false)
1149    }
1150
1151    pub fn initialize(&mut self, config: RiProtocolConfig) -> bool {
1152        self.base.config = config;
1153        if let Ok(mut guard) = self.base.initialized.try_write() {
1154            *guard = true;
1155            return true;
1156        }
1157        false
1158    }
1159
1160    pub fn get_stats(&self) -> RiProtocolStats {
1161        self.base.stats.try_read()
1162            .map(|guard| guard.clone())
1163            .unwrap_or_else(|_| RiProtocolStats::new())
1164    }
1165
1166    pub fn get_health(&self) -> RiProtocolHealth {
1167        self.base.initialized.try_read()
1168            .map(|guard| {
1169                if *guard {
1170                    RiProtocolHealth::Healthy
1171                } else {
1172                    RiProtocolHealth::Unknown
1173                }
1174            })
1175            .unwrap_or(RiProtocolHealth::Unknown)
1176    }
1177
1178    pub fn shutdown(&mut self) -> bool {
1179        if let Ok(mut guard) = self.base.initialized.try_write() {
1180            *guard = false;
1181            return true;
1182        }
1183        false
1184    }
1185}
1186
1187#[cfg(feature = "pyo3")]
1188#[pyo3::prelude::pymethods]
1189impl RiPrivateProtocol {
1190    pub fn is_ready_sync(&self) -> bool {
1191        self.base.initialized.try_read()
1192            .map(|guard| *guard)
1193            .unwrap_or(false)
1194    }
1195
1196    pub fn initialize(&mut self, config: RiProtocolConfig) -> bool {
1197        self.base.config = config;
1198        if let Ok(mut guard) = self.base.initialized.try_write() {
1199            *guard = true;
1200            return true;
1201        }
1202        false
1203    }
1204
1205    pub fn get_stats(&self) -> RiProtocolStats {
1206        self.base.stats.try_read()
1207            .map(|guard| guard.clone())
1208            .unwrap_or_else(|_| RiProtocolStats::new())
1209    }
1210
1211    pub fn get_health(&self) -> RiProtocolHealth {
1212        if let Ok(guard) = self.base.initialized.try_read() {
1213            if *guard {
1214                return RiProtocolHealth::Healthy;
1215            }
1216        }
1217        RiProtocolHealth::Unknown
1218    }
1219
1220    pub fn shutdown(&mut self) -> bool {
1221        if let Ok(mut guard) = self.base.initialized.try_write() {
1222            *guard = false;
1223            return true;
1224        }
1225        false
1226    }
1227}