1use crate::error::EdgeComputingError;
4use crate::models::{EdgeNode, NodeCapacity, NodeStatus};
5use chrono::Utc;
6use std::sync::Arc;
7use tokio::sync::RwLock;
8use uuid::Uuid;
9
10pub struct EdgeNodeManager {
12 nodes: Arc<RwLock<std::collections::HashMap<Uuid, EdgeNode>>>,
13}
14
15impl EdgeNodeManager {
16 pub fn new() -> Self {
18 Self {
19 nodes: Arc::new(RwLock::new(std::collections::HashMap::new())),
20 }
21 }
22
23 pub async fn register_node(
25 &self,
26 name: String,
27 location: String,
28 endpoint: String,
29 capacity: NodeCapacity,
30 ) -> Uuid {
31 let id = Uuid::new_v4();
32 let node = EdgeNode {
33 id,
34 name,
35 location,
36 endpoint,
37 status: NodeStatus::Online,
38 capacity,
39 last_heartbeat: Utc::now(),
40 metadata: serde_json::json!({}),
41 };
42
43 self.nodes.write().await.insert(id, node);
44 id
45 }
46
47 pub async fn update_heartbeat(&self, node_id: Uuid) -> Result<(), EdgeComputingError> {
49 let mut nodes = self.nodes.write().await;
50 if let Some(node) = nodes.get_mut(&node_id) {
51 node.last_heartbeat = Utc::now();
52 Ok(())
53 } else {
54 Err(EdgeComputingError::NodeNotFound(node_id.to_string()))
55 }
56 }
57
58 pub async fn get_node(&self, node_id: Uuid) -> Option<EdgeNode> {
60 self.nodes.read().await.get(&node_id).cloned()
61 }
62
63 pub async fn get_online_nodes(&self) -> Vec<EdgeNode> {
65 self.nodes
66 .read()
67 .await
68 .values()
69 .filter(|n| n.status == NodeStatus::Online)
70 .cloned()
71 .collect()
72 }
73
74 pub async fn update_node_status(
76 &self,
77 node_id: Uuid,
78 status: NodeStatus,
79 ) -> Result<(), EdgeComputingError> {
80 let mut nodes = self.nodes.write().await;
81 if let Some(node) = nodes.get_mut(&node_id) {
82 node.status = status;
83 Ok(())
84 } else {
85 Err(EdgeComputingError::NodeNotFound(node_id.to_string()))
86 }
87 }
88
89 pub async fn update_node_capacity(
91 &self,
92 node_id: Uuid,
93 capacity: NodeCapacity,
94 ) -> Result<(), EdgeComputingError> {
95 let mut nodes = self.nodes.write().await;
96 if let Some(node) = nodes.get_mut(&node_id) {
97 node.capacity = capacity;
98 Ok(())
99 } else {
100 Err(EdgeComputingError::NodeNotFound(node_id.to_string()))
101 }
102 }
103
104 pub async fn remove_node(&self, node_id: Uuid) -> Result<(), EdgeComputingError> {
106 let mut nodes = self.nodes.write().await;
107 if nodes.remove(&node_id).is_some() {
108 Ok(())
109 } else {
110 Err(EdgeComputingError::NodeNotFound(node_id.to_string()))
111 }
112 }
113}
114
115impl Default for EdgeNodeManager {
116 fn default() -> Self {
117 Self::new()
118 }
119}