1#![allow(non_snake_case)]
19
20use std::collections::HashMap;
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::{DMSCResult, DMSCError};
64
65#[cfg(feature = "pyo3")]
66use pyo3::prelude::*;
67
68pub mod frames;
70pub use frames::{DMSCFrameBuilder, DMSCFrameParser};
71
72#[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 DMSCPostQuantumAlgorithm, KEMResult,
87};
88
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, std::hash::Hash)]
91#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
92pub enum DMSCProtocolType {
93 Global = 0,
95 Private = 1,
97}
98
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
101#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
102pub enum DMSCProtocolStatus {
103 Inactive,
105 Initializing,
107 Ready,
109 Error,
111}
112
113#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
115#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
116pub enum DMSCConnectionState {
117 Disconnected,
119 Connecting,
121 Connected,
123 Disconnecting,
125}
126
127#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
129#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
130pub enum DMSCSecurityLevel {
131 None,
133 Standard,
135 High,
137 Military,
139}
140
141#[derive(Debug, Clone, Serialize, Deserialize)]
143#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
144pub struct DMSCProtocolConfig {
145 pub default_protocol: DMSCProtocolType,
147 pub enable_security: bool,
149 pub security_level: DMSCSecurityLevel,
151 pub enable_state_sync: bool,
153 pub performance_optimization: bool,
155}
156
157impl Default for DMSCProtocolConfig {
158 fn default() -> Self {
159 Self {
160 default_protocol: DMSCProtocolType::Global,
161 enable_security: true,
162 security_level: DMSCSecurityLevel::Standard,
163 enable_state_sync: true,
164 performance_optimization: true,
165 }
166 }
167}
168
169impl DMSCProtocolConfig {
170 pub fn validate(&self) -> DMSCResult<()> {
172 if self.security_level == DMSCSecurityLevel::None && self.enable_security {
173 return Err(DMSCError::Config(
174 "Security level cannot be None when security is enabled".to_string()
175 ));
176 }
177
178 Ok(())
179 }
180
181 pub fn secure() -> Self {
183 Self {
184 default_protocol: DMSCProtocolType::Private,
185 enable_security: true,
186 security_level: DMSCSecurityLevel::High,
187 enable_state_sync: true,
188 performance_optimization: true,
189 }
190 }
191
192 pub fn maximum_security() -> Self {
194 Self {
195 default_protocol: DMSCProtocolType::Private,
196 enable_security: true,
197 security_level: DMSCSecurityLevel::Military,
198 enable_state_sync: true,
199 performance_optimization: false,
200 }
201 }
202}
203
204#[derive(Debug, Clone, Serialize, Deserialize)]
206#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
207pub struct DMSCProtocolStats {
208 pub messages_sent: u64,
210 pub messages_received: u64,
212 pub bytes_sent: u64,
214 pub bytes_received: u64,
216 pub errors: u64,
218 pub avg_latency_ms: f64,
220}
221
222impl DMSCProtocolStats {
223 pub fn new() -> Self {
224 Self {
225 messages_sent: 0,
226 messages_received: 0,
227 bytes_sent: 0,
228 bytes_received: 0,
229 errors: 0,
230 avg_latency_ms: 0.0,
231 }
232 }
233
234 pub fn record_sent(&mut self, bytes: usize) {
235 self.messages_sent += 1;
236 self.bytes_sent += bytes as u64;
237 }
238
239 pub fn record_received(&mut self, bytes: usize) {
240 self.messages_received += 1;
241 self.bytes_received += bytes as u64;
242 }
243
244 pub fn record_error(&mut self) {
245 self.errors += 1;
246 }
247}
248
249#[derive(Debug, Clone, Serialize, Deserialize)]
251#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
252pub struct DMSCConnectionStats {
253 pub total_connections: u64,
255 pub active_connections: u64,
257 pub bytes_sent: u64,
259 pub bytes_received: u64,
261 pub connection_duration_secs: u64,
263}
264
265impl Default for DMSCConnectionStats {
266 fn default() -> Self {
267 Self {
268 total_connections: 0,
269 active_connections: 0,
270 bytes_sent: 0,
271 bytes_received: 0,
272 connection_duration_secs: 0,
273 }
274 }
275}
276
277#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
279#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
280pub enum DMSCProtocolHealth {
281 Healthy,
283 Degraded,
285 Unhealthy,
287 Unknown,
289}
290
291impl Default for DMSCProtocolHealth {
292 fn default() -> Self {
293 DMSCProtocolHealth::Unknown
294 }
295}
296
297#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
299#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
300pub struct DMSCMessageFlags {
301 pub compressed: bool,
303 pub encrypted: bool,
305 pub requires_ack: bool,
307 pub priority: bool,
309}
310
311impl Default for DMSCMessageFlags {
312 fn default() -> Self {
313 Self {
314 compressed: false,
315 encrypted: false,
316 requires_ack: false,
317 priority: false,
318 }
319 }
320}
321
322#[derive(Debug, Clone, Serialize, Deserialize)]
324#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
325pub struct DMSCConnectionInfo {
326 pub connection_id: String,
328 pub device_id: String,
330 pub address: String,
332 pub protocol_type: DMSCProtocolType,
334 pub state: DMSCConnectionState,
336 pub security_level: DMSCSecurityLevel,
338 pub connected_at: u64,
340 pub last_activity: u64,
342}
343
344impl Default for DMSCConnectionInfo {
345 fn default() -> Self {
346 Self {
347 connection_id: String::new(),
348 device_id: String::new(),
349 address: String::new(),
350 protocol_type: DMSCProtocolType::Global,
351 state: DMSCConnectionState::Disconnected,
352 security_level: DMSCSecurityLevel::None,
353 connected_at: 0,
354 last_activity: 0,
355 }
356 }
357}
358
359#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
361#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
362pub enum DMSCFrameType {
363 Data = 0,
365 Control = 1,
367 Heartbeat = 2,
369 Ack = 3,
371 Error = 4,
373}
374
375#[derive(Debug, Clone, Serialize, Deserialize)]
377#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
378pub struct DMSCFrameHeader {
379 pub version: u8,
381 pub frame_type: DMSCFrameType,
383 pub sequence_number: u64,
385 pub length: u32,
387 pub timestamp: u64,
389 pub flags: u16,
391 pub auth_tag_offset: u16,
393}
394
395impl Default for DMSCFrameHeader {
396 fn default() -> Self {
397 Self {
398 version: 1,
399 frame_type: DMSCFrameType::Data,
400 sequence_number: 0,
401 length: 0,
402 timestamp: 0,
403 flags: 0,
404 auth_tag_offset: 0,
405 }
406 }
407}
408
409impl DMSCFrameHeader {
410 pub fn major_version(&self) -> u8 {
412 self.version >> 4
413 }
414
415 pub fn minor_version(&self) -> u8 {
417 self.version & 0x0F
418 }
419
420 pub fn supports_feature(&self, feature: u16) -> bool {
422 (self.flags & feature) != 0
423 }
424}
425
426#[derive(Debug, Clone, Serialize, Deserialize)]
428#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
429pub struct DMSCFrame {
430 pub header: DMSCFrameHeader,
432 pub payload: Vec<u8>,
434 pub source_id: String,
436 pub target_id: String,
438}
439
440impl Default for DMSCFrame {
441 fn default() -> Self {
442 Self {
443 header: DMSCFrameHeader::default(),
444 payload: Vec::new(),
445 source_id: String::new(),
446 target_id: String::new(),
447 }
448 }
449}
450
451#[async_trait]
453pub trait DMSCProtocol {
454 fn protocol_type(&self) -> DMSCProtocolType;
456
457 async fn is_ready(&self) -> bool;
459
460 async fn initialize(&mut self, config: DMSCProtocolConfig) -> DMSCResult<()>;
462
463 async fn send_message(&mut self, target: &str, data: &[u8]) -> DMSCResult<Vec<u8>>;
465
466 async fn send_message_with_flags(&mut self, target: &str, data: &[u8], flags: DMSCMessageFlags) -> DMSCResult<Vec<u8>>;
468
469 async fn receive_message(&mut self) -> DMSCResult<Vec<u8>>;
471
472 async fn get_connection_info(&self, connection_id: &str) -> DMSCResult<DMSCConnectionInfo>;
474
475 async fn close_connection(&mut self, connection_id: &str) -> DMSCResult<()>;
477
478 fn get_stats(&self) -> DMSCProtocolStats;
480
481 async fn get_health(&self) -> DMSCProtocolHealth;
483
484 async fn shutdown(&mut self) -> DMSCResult<()>;
486}
487
488#[async_trait]
490pub trait DMSCProtocolConnection {
491 fn connection_id(&self) -> &str;
493
494 fn remote_device_id(&self) -> &str;
496
497 fn protocol_type(&self) -> DMSCProtocolType;
499
500 fn is_active(&self) -> bool;
502
503 async fn send(&mut self, data: &[u8]) -> DMSCResult<usize>;
505
506 async fn receive(&mut self, buffer: &mut [u8]) -> DMSCResult<usize>;
508
509 fn get_stats(&self) -> DMSCConnectionStats;
511
512 async fn close(&mut self) -> DMSCResult<()>;
514}
515
516#[derive(Debug, Clone)]
518#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
519pub struct DMSCProtocolManager {
520 pub stats: Arc<RwLock<DMSCProtocolStats>>,
522 pub default_protocol: DMSCProtocolType,
524 connections: Arc<RwLock<HashMap<String, DMSCConnectionInfo>>>,
526 sequence_counter: Arc<AtomicU64>,
528 initialized: Arc<RwLock<bool>>,
530}
531
532#[cfg(test)]
533mod protocol_tests {
534 use super::*;
535
536 #[test]
537 fn test_protocol_config_default() {
538 let config = DMSCProtocolConfig::default();
539 assert_eq!(config.default_protocol, DMSCProtocolType::Global);
540 assert!(config.enable_security);
541 assert_eq!(config.security_level, DMSCSecurityLevel::Standard);
542 }
543
544 #[test]
545 fn test_protocol_config_secure() {
546 let config = DMSCProtocolConfig::secure();
547 assert_eq!(config.default_protocol, DMSCProtocolType::Private);
548 assert!(config.enable_security);
549 assert_eq!(config.security_level, DMSCSecurityLevel::High);
550 }
551
552 #[test]
553 fn test_protocol_config_maximum_security() {
554 let config = DMSCProtocolConfig::maximum_security();
555 assert_eq!(config.default_protocol, DMSCProtocolType::Private);
556 assert!(config.enable_security);
557 assert_eq!(config.security_level, DMSCSecurityLevel::Military);
558 }
559
560 #[test]
561 fn test_protocol_config_validation() {
562 let mut config = DMSCProtocolConfig::default();
563
564 assert!(config.validate().is_ok());
566
567 config.security_level = DMSCSecurityLevel::None;
569 assert!(config.validate().is_err());
570 }
571
572 #[test]
573 fn test_frame_header_version() {
574 let header = DMSCFrameHeader::default();
575 assert_eq!(header.major_version(), 0);
576 assert_eq!(header.minor_version(), 1);
577 }
578
579 #[test]
580 fn test_frame_header_supports_feature() {
581 let header = DMSCFrameHeader {
582 flags: 0b00000011,
583 ..Default::default()
584 };
585
586 assert!(header.supports_feature(0b00000001));
587 assert!(header.supports_feature(0b00000010));
588 assert!(!header.supports_feature(0b00000100));
589 }
590
591 #[test]
592 fn test_protocol_stats() {
593 let stats = DMSCProtocolStats::new();
594 assert_eq!(stats.messages_sent, 0);
595 assert_eq!(stats.messages_received, 0);
596 assert_eq!(stats.errors, 0);
597 }
598
599 #[test]
600 fn test_connection_info() {
601 let mut info = DMSCConnectionInfo::default();
602 info.device_id = "test-device".to_string();
603 info.state = DMSCConnectionState::Connected;
604 assert_eq!(info.device_id, "test-device");
605 assert_eq!(info.state, DMSCConnectionState::Connected);
606 assert_eq!(info.security_level, DMSCSecurityLevel::None);
607 }
608
609 #[test]
610 fn test_protocol_type_values() {
611 assert_eq!(DMSCProtocolType::Global as u8, 0);
612 assert_eq!(DMSCProtocolType::Private as u8, 1);
613 }
614
615 #[test]
616 fn test_security_level_values() {
617 assert_eq!(DMSCSecurityLevel::None as u8, 0);
618 assert_eq!(DMSCSecurityLevel::Standard as u8, 1);
619 assert_eq!(DMSCSecurityLevel::High as u8, 2);
620 assert_eq!(DMSCSecurityLevel::Military as u8, 3);
621 }
622}
623
624#[cfg(feature = "pyo3")]
625#[pyo3::prelude::pymethods]
626impl DMSCProtocolManager {
627 #[new]
628 fn new_py() -> Self {
629 Self::new()
630 }
631
632 #[getter]
633 fn get_stats_py(&self) -> DMSCProtocolStats {
634 self.stats.try_read()
635 .map(|guard| guard.clone())
636 .unwrap_or_else(|_| DMSCProtocolStats::new())
637 }
638
639 #[getter]
640 fn get_default_protocol_py(&self) -> DMSCProtocolType {
641 self.default_protocol
642 }
643
644 pub fn initialize(&mut self, config: DMSCProtocolConfig) -> PyResult<()> {
646 self.default_protocol = config.default_protocol;
647
648 let mut initialized = self.initialized.try_write()
649 .map_err(|_| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(
650 "Failed to acquire write lock on initialized state"))?;
651 *initialized = true;
652
653 Ok(())
654 }
655
656 pub fn send_message(&self, target: &str, data: &[u8]) -> Vec<u8> {
658 let timestamp = SystemTime::now()
659 .duration_since(UNIX_EPOCH)
660 .unwrap_or_default()
661 .as_millis() as u64;
662
663 let sequence = self.sequence_counter.fetch_add(1, Ordering::SeqCst);
664
665 let frame = DMSCFrame {
666 header: DMSCFrameHeader {
667 version: 1,
668 frame_type: DMSCFrameType::Data,
669 sequence_number: sequence,
670 length: data.len() as u32,
671 timestamp,
672 flags: 0,
673 auth_tag_offset: 0,
674 },
675 payload: data.to_vec(),
676 source_id: String::from("protocol_manager"),
677 target_id: target.to_string(),
678 };
679
680 let serialized = match serde_json::to_vec(&frame) {
681 Ok(serialized_data) => serialized_data,
682 Err(e) => {
683 if let Ok(mut stats) = self.stats.try_write() {
684 stats.record_error();
685 }
686 let error_response = DMSCProtocolResponse {
687 success: false,
688 sequence_number: sequence,
689 target_id: target.to_string(),
690 response_data: format!("Serialization error: {}", e).into_bytes(),
691 timestamp,
692 };
693 return serde_json::to_vec(&error_response)
694 .unwrap_or_else(|_| b"{\"success\":false,\"error\":\"Serialization failed\"}".to_vec());
695 }
696 };
697
698 let payload_len = serialized.len();
699 if let Ok(mut stats) = self.stats.try_write() {
700 stats.record_sent(payload_len);
701 }
702
703 let response_data = self.build_response_data(target, &frame, sequence, timestamp);
704
705 let response = DMSCProtocolResponse {
706 success: true,
707 sequence_number: sequence,
708 target_id: target.to_string(),
709 response_data,
710 timestamp,
711 };
712
713 self.stats.try_write()
714 .map(|mut stats| stats.record_received(response.response_data.len()))
715 .map_err(|e| tracing::error!("Failed to update protocol stats: {}", e))
716 .ok();
717
718 serde_json::to_vec(&response).unwrap_or_else(|_| b"{\"success\":true,\"message\":\"Message sent\"}".to_vec())
719 }
720
721 fn build_response_data(&self, target: &str, frame: &DMSCFrame, sequence: u64, timestamp: u64) -> Vec<u8> {
722 let mut response = HashMap::<String, serde_json::Value>::new();
723
724 response.insert("status".to_string(), serde_json::Value::String("delivered".to_string()));
725 response.insert("target".to_string(), serde_json::Value::String(target.to_string()));
726 response.insert("source".to_string(), serde_json::Value::String(frame.source_id.clone()));
727 response.insert("sequence".to_string(), serde_json::Value::Number(sequence.into()));
728 response.insert("timestamp".to_string(), serde_json::Value::Number(timestamp.into()));
729 response.insert("frame_type".to_string(), serde_json::Value::String(format!("{:?}", frame.header.frame_type)));
730 response.insert("payload_size".to_string(), serde_json::Value::Number(serde_json::Number::from(frame.payload.len())));
731 response.insert("protocol".to_string(), serde_json::Value::String(format!("{:?}", self.default_protocol)));
732
733 let delivery_info = serde_json::json!({
734 "delivered_at": timestamp,
735 "hops": 1,
736 "route": [frame.source_id.clone(), target.to_string()]
737 });
738 response.insert("delivery".to_string(), delivery_info);
739
740 serde_json::to_vec(&response).unwrap_or_default()
741 }
742
743 pub fn send_message_with_flags(&self, target: &str, data: &[u8], _flags: DMSCMessageFlags) -> Vec<u8> {
745 self.send_message(target, data)
746 }
747
748 pub fn get_connection_info(&self, connection_id: &str) -> Option<DMSCConnectionInfo> {
750 self.connections.try_read()
751 .ok()
752 .and_then(|connections| connections.get(connection_id).cloned())
753 }
754
755 pub fn close_connection(&mut self, connection_id: &str) -> bool {
757 self.connections.try_write()
758 .ok()
759 .map(|mut connections| connections.remove(connection_id).is_some())
760 .unwrap_or(false)
761 }
762}
763
764impl DMSCProtocolManager {
765 pub fn new() -> Self {
766 Self {
767 stats: Arc::new(RwLock::new(DMSCProtocolStats::new())),
768 default_protocol: DMSCProtocolType::Global,
769 connections: Arc::new(RwLock::new(HashMap::new())),
770 sequence_counter: Arc::new(AtomicU64::new(0)),
771 initialized: Arc::new(RwLock::new(false)),
772 }
773 }
774}
775
776impl Default for DMSCProtocolManager {
777 fn default() -> Self {
778 Self::new()
779 }
780}
781
782#[derive(Debug, Clone, Serialize, Deserialize)]
784#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
785pub struct DMSCProtocolResponse {
786 pub success: bool,
788 pub sequence_number: u64,
790 pub target_id: String,
792 pub response_data: Vec<u8>,
794 pub timestamp: u64,
796}
797
798impl Default for DMSCProtocolResponse {
799 fn default() -> Self {
800 Self {
801 success: false,
802 sequence_number: 0,
803 target_id: String::new(),
804 response_data: Vec::new(),
805 timestamp: 0,
806 }
807 }
808}
809
810#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
811pub enum ProtocolError {
812 #[error("Target not found: {target_id}")]
813 TargetNotFound { target_id: String },
814 #[error("Send failed: {message}")]
815 SendFailed { message: String },
816 #[error("Protocol not initialized")]
817 NotInitialized,
818 #[error("Invalid state: {state}")]
819 InvalidState { state: String },
820 #[error("Connection not found: {connection_id}")]
821 ConnectionNotFound { connection_id: String },
822 #[error("Serialization error: {message}")]
823 Serialization { message: String },
824 #[error("Operation not supported for this protocol")]
825 NotSupported,
826}
827
828impl From<ProtocolError> for DMSCError {
829 fn from(error: ProtocolError) -> Self {
830 DMSCError::Other(format!("Protocol error: {}", error))
831 }
832}
833
834impl From<serde_json::Error> for ProtocolError {
835 fn from(error: serde_json::Error) -> Self {
836 ProtocolError::Serialization { message: error.to_string() }
837 }
838}
839
840impl From<ProtocolError> for DMSCResult<()> {
841 fn from(error: ProtocolError) -> Self {
842 Err(error.into())
843 }
844}
845
846#[derive(Debug, Clone)]
847pub struct DMSCBaseProtocol {
848 config: DMSCProtocolConfig,
849 stats: Arc<RwLock<DMSCProtocolStats>>,
850 connections: Arc<RwLock<HashMap<String, DMSCConnectionInfo>>>,
851 sequence_counter: Arc<AtomicU64>,
852 initialized: Arc<RwLock<bool>>,
853 _receiver_id: String,
854}
855
856impl DMSCBaseProtocol {
857 pub fn new(receiver_id: String) -> Self {
858 Self {
859 config: DMSCProtocolConfig::default(),
860 stats: Arc::new(RwLock::new(DMSCProtocolStats::new())),
861 connections: Arc::new(RwLock::new(HashMap::new())),
862 sequence_counter: Arc::new(AtomicU64::new(0)),
863 initialized: Arc::new(RwLock::new(false)),
864 _receiver_id: receiver_id,
865 }
866 }
867
868 pub async fn is_ready(&self) -> bool {
869 *self.initialized.read().await
870 }
871
872 pub async fn initialize(&mut self, config: DMSCProtocolConfig) {
873 self.config = config;
874 *self.initialized.write().await = true;
875 }
876
877 pub async fn send_message(&mut self, _target: &str, data: &[u8]) -> DMSCResult<Vec<u8>> {
878 if !*self.initialized.read().await {
879 return Err(ProtocolError::NotInitialized.into());
880 }
881
882 let sequence = self.sequence_counter.fetch_add(1, Ordering::SeqCst) as u32;
883
884 self.stats.write().await.record_sent(data.len());
885
886 let mut builder = DMSCFrameBuilder::new();
887 builder.set_sequence(sequence);
888 let frame = builder.build_data_frame(data.to_vec())
889 .map_err(|e| ProtocolError::Serialization {
890 message: e.to_string()
891 })?;
892
893 let frame_bytes = frame.to_bytes()
894 .map_err(|e| ProtocolError::Serialization {
895 message: e.to_string()
896 })?;
897
898 self.stats.write().await.record_received(frame_bytes.len());
899
900 Ok(frame_bytes)
901 }
902
903 pub async fn receive_message(&mut self) -> DMSCResult<Vec<u8>> {
904 if !*self.initialized.read().await {
905 return Err(ProtocolError::NotInitialized.into());
906 }
907
908 let sequence = self.sequence_counter.fetch_add(1, Ordering::SeqCst) as u32;
909
910 let mut builder = DMSCFrameBuilder::new();
911 builder.set_sequence(sequence);
912 let frame = builder.build_keepalive_frame()
913 .map_err(|e| ProtocolError::Serialization {
914 message: e.to_string()
915 })?;
916
917 let frame_bytes = frame.to_bytes()
918 .map_err(|e| ProtocolError::Serialization {
919 message: e.to_string()
920 })?;
921
922 self.stats.write().await.record_received(0);
923
924 Ok(frame_bytes)
925 }
926
927 pub async fn get_connection_info(&self, connection_id: &str) -> DMSCResult<DMSCConnectionInfo> {
928 let connections = self.connections.read().await;
929 connections.get(connection_id)
930 .cloned()
931 .ok_or_else(|| ProtocolError::ConnectionNotFound {
932 connection_id: connection_id.to_string()
933 }.into())
934 }
935
936 pub async fn close_connection(&mut self, connection_id: &str) -> DMSCResult<()> {
937 let mut connections = self.connections.write().await;
938 if connections.remove(connection_id).is_some() {
939 Ok(())
940 } else {
941 Err(ProtocolError::ConnectionNotFound {
942 connection_id: connection_id.to_string()
943 }.into())
944 }
945 }
946
947 pub fn get_stats(&self) -> DMSCProtocolStats {
948 self.stats.try_read()
949 .map(|guard| guard.clone())
950 .unwrap_or_else(|_| DMSCProtocolStats::new())
951 }
952
953 pub async fn get_health(&self) -> DMSCProtocolHealth {
954 if *self.initialized.read().await {
955 DMSCProtocolHealth::Healthy
956 } else {
957 DMSCProtocolHealth::Unknown
958 }
959 }
960
961 pub async fn shutdown(&mut self) {
962 *self.initialized.write().await = false;
963 }
964}
965
966#[derive(Debug, Clone)]
967#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
968pub struct DMSCGlobalProtocol {
969 base: DMSCBaseProtocol,
970}
971
972impl DMSCGlobalProtocol {
973 pub fn new() -> Self {
974 Self {
975 base: DMSCBaseProtocol::new(String::from("receiver")),
976 }
977 }
978}
979
980impl Default for DMSCGlobalProtocol {
981 fn default() -> Self {
982 Self::new()
983 }
984}
985
986#[async_trait]
987impl DMSCProtocol for DMSCGlobalProtocol {
988 fn protocol_type(&self) -> DMSCProtocolType {
989 DMSCProtocolType::Global
990 }
991
992 async fn is_ready(&self) -> bool {
993 self.base.is_ready().await
994 }
995
996 async fn initialize(&mut self, config: DMSCProtocolConfig) -> DMSCResult<()> {
997 self.base.initialize(config).await;
998 Ok(())
999 }
1000
1001 async fn send_message(&mut self, target: &str, data: &[u8]) -> DMSCResult<Vec<u8>> {
1002 self.base.send_message(target, data).await
1003 }
1004
1005 async fn send_message_with_flags(&mut self, target: &str, data: &[u8], flags: DMSCMessageFlags) -> DMSCResult<Vec<u8>> {
1006 let response = self.base.send_message(target, data).await?;
1007 if flags.encrypted {
1008 self.base.stats.write().await.record_error();
1009 }
1010 Ok(response)
1011 }
1012
1013 async fn receive_message(&mut self) -> DMSCResult<Vec<u8>> {
1014 self.base.receive_message().await
1015 }
1016
1017 async fn get_connection_info(&self, connection_id: &str) -> DMSCResult<DMSCConnectionInfo> {
1018 self.base.get_connection_info(connection_id).await
1019 }
1020
1021 async fn close_connection(&mut self, connection_id: &str) -> DMSCResult<()> {
1022 self.base.close_connection(connection_id).await
1023 }
1024
1025 fn get_stats(&self) -> DMSCProtocolStats {
1026 self.base.get_stats()
1027 }
1028
1029 async fn get_health(&self) -> DMSCProtocolHealth {
1030 self.base.get_health().await
1031 }
1032
1033 async fn shutdown(&mut self) -> DMSCResult<()> {
1034 self.base.shutdown().await;
1035 Ok(())
1036 }
1037}
1038
1039#[derive(Debug, Clone)]
1040#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
1041pub struct DMSCPrivateProtocol {
1042 base: DMSCBaseProtocol,
1043}
1044
1045impl DMSCPrivateProtocol {
1046 pub fn new() -> Self {
1047 Self {
1048 base: DMSCBaseProtocol::new(String::from("private_receiver")),
1049 }
1050 }
1051}
1052
1053impl Default for DMSCPrivateProtocol {
1054 fn default() -> Self {
1055 Self::new()
1056 }
1057}
1058
1059#[async_trait]
1060impl DMSCProtocol for DMSCPrivateProtocol {
1061 fn protocol_type(&self) -> DMSCProtocolType {
1062 DMSCProtocolType::Private
1063 }
1064
1065 async fn is_ready(&self) -> bool {
1066 self.base.is_ready().await
1067 }
1068
1069 async fn initialize(&mut self, config: DMSCProtocolConfig) -> DMSCResult<()> {
1070 self.base.initialize(config).await;
1071 Ok(())
1072 }
1073
1074 async fn send_message(&mut self, target: &str, data: &[u8]) -> DMSCResult<Vec<u8>> {
1075 self.base.send_message(target, data).await
1076 }
1077
1078 async fn send_message_with_flags(&mut self, target: &str, data: &[u8], flags: DMSCMessageFlags) -> DMSCResult<Vec<u8>> {
1079 let response = self.base.send_message(target, data).await?;
1080 if !flags.encrypted {
1081 self.base.stats.write().await.record_error();
1082 }
1083 Ok(response)
1084 }
1085
1086 async fn receive_message(&mut self) -> DMSCResult<Vec<u8>> {
1087 self.base.receive_message().await
1088 }
1089
1090 async fn get_connection_info(&self, connection_id: &str) -> DMSCResult<DMSCConnectionInfo> {
1091 self.base.get_connection_info(connection_id).await
1092 }
1093
1094 async fn close_connection(&mut self, connection_id: &str) -> DMSCResult<()> {
1095 self.base.close_connection(connection_id).await
1096 }
1097
1098 fn get_stats(&self) -> DMSCProtocolStats {
1099 self.base.get_stats()
1100 }
1101
1102 async fn get_health(&self) -> DMSCProtocolHealth {
1103 self.base.get_health().await
1104 }
1105
1106 async fn shutdown(&mut self) -> DMSCResult<()> {
1107 self.base.shutdown().await;
1108 Ok(())
1109 }
1110}
1111
1112#[cfg(feature = "pyo3")]
1113#[pyo3::prelude::pymethods]
1114impl DMSCGlobalProtocol {
1115 pub fn is_ready_sync(&self) -> bool {
1116 self.base.initialized.try_read()
1117 .map(|guard| *guard)
1118 .unwrap_or(false)
1119 }
1120
1121 pub fn initialize(&mut self, config: DMSCProtocolConfig) -> bool {
1122 self.base.config = config;
1123 if let Ok(mut guard) = self.base.initialized.try_write() {
1124 *guard = true;
1125 return true;
1126 }
1127 false
1128 }
1129
1130 pub fn get_stats(&self) -> DMSCProtocolStats {
1131 self.base.stats.try_read()
1132 .map(|guard| guard.clone())
1133 .unwrap_or_else(|_| DMSCProtocolStats::new())
1134 }
1135
1136 pub fn get_health(&self) -> DMSCProtocolHealth {
1137 self.base.initialized.try_read()
1138 .map(|guard| {
1139 if *guard {
1140 DMSCProtocolHealth::Healthy
1141 } else {
1142 DMSCProtocolHealth::Unknown
1143 }
1144 })
1145 .unwrap_or(DMSCProtocolHealth::Unknown)
1146 }
1147
1148 pub fn shutdown(&mut self) -> bool {
1149 if let Ok(mut guard) = self.base.initialized.try_write() {
1150 *guard = false;
1151 return true;
1152 }
1153 false
1154 }
1155}
1156
1157#[cfg(feature = "pyo3")]
1158#[pyo3::prelude::pymethods]
1159impl DMSCPrivateProtocol {
1160 pub fn is_ready_sync(&self) -> bool {
1161 self.base.initialized.try_read()
1162 .map(|guard| *guard)
1163 .unwrap_or(false)
1164 }
1165
1166 pub fn initialize(&mut self, config: DMSCProtocolConfig) -> bool {
1167 self.base.config = config;
1168 if let Ok(mut guard) = self.base.initialized.try_write() {
1169 *guard = true;
1170 return true;
1171 }
1172 false
1173 }
1174
1175 pub fn get_stats(&self) -> DMSCProtocolStats {
1176 self.base.stats.try_read()
1177 .map(|guard| guard.clone())
1178 .unwrap_or_else(|_| DMSCProtocolStats::new())
1179 }
1180
1181 pub fn get_health(&self) -> DMSCProtocolHealth {
1182 if let Ok(guard) = self.base.initialized.try_read() {
1183 if *guard {
1184 return DMSCProtocolHealth::Healthy;
1185 }
1186 }
1187 DMSCProtocolHealth::Unknown
1188 }
1189
1190 pub fn shutdown(&mut self) -> bool {
1191 if let Ok(mut guard) = self.base.initialized.try_write() {
1192 *guard = false;
1193 return true;
1194 }
1195 false
1196 }
1197}