1use crate::error::EdgeComputingError;
4use crate::models::{SyncOperation, SyncStatus};
5use chrono::Utc;
6use std::sync::Arc;
7use tokio::sync::RwLock;
8use uuid::Uuid;
9
10pub struct EdgeSyncService {
12 sync_operations: Arc<RwLock<std::collections::HashMap<Uuid, SyncOperation>>>,
13 _cloud_endpoint: String,
14}
15
16impl EdgeSyncService {
17 pub fn new(cloud_endpoint: String) -> Self {
19 Self {
20 sync_operations: Arc::new(RwLock::new(std::collections::HashMap::new())),
21 _cloud_endpoint: cloud_endpoint,
22 }
23 }
24
25 pub async fn create_sync_operation(
27 &self,
28 source_node: Uuid,
29 target_node: Uuid,
30 data_type: String,
31 data: serde_json::Value,
32 ) -> Uuid {
33 let id = Uuid::new_v4();
34 let operation = SyncOperation {
35 id,
36 source_node,
37 target_node,
38 data_type,
39 data,
40 status: SyncStatus::Pending,
41 created_at: Utc::now(),
42 completed_at: None,
43 };
44
45 self.sync_operations.write().await.insert(id, operation);
46 id
47 }
48
49 pub async fn sync_to_cloud(&self, sync_id: Uuid) -> Result<(), EdgeComputingError> {
51 let mut operations = self.sync_operations.write().await;
52 let operation = operations.get_mut(&sync_id).ok_or_else(|| {
53 EdgeComputingError::SynchronizationFailed("Sync operation not found".to_string())
54 })?;
55
56 operation.status = SyncStatus::InProgress;
57
58 tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
61
62 operation.status = SyncStatus::Completed;
63 operation.completed_at = Some(Utc::now());
64
65 Ok(())
66 }
67
68 pub async fn get_sync_status(&self, sync_id: Uuid) -> Option<SyncStatus> {
70 self.sync_operations
71 .read()
72 .await
73 .get(&sync_id)
74 .map(|op| op.status)
75 }
76
77 pub async fn get_pending_syncs(&self) -> Vec<SyncOperation> {
79 self.sync_operations
80 .read()
81 .await
82 .values()
83 .filter(|op| op.status == SyncStatus::Pending)
84 .cloned()
85 .collect()
86 }
87}