Skip to main content

edge_computing/
orchestrator.rs

1//! Edge Task Orchestrator
2
3use crate::error::EdgeComputingError;
4use crate::models::{EdgeTask, TaskPriority, TaskStatus, TaskType};
5use crate::node::EdgeNodeManager;
6use chrono::Utc;
7use std::sync::Arc;
8use tokio::sync::RwLock;
9use uuid::Uuid;
10
11/// Edge Task Orchestrator
12pub struct EdgeOrchestrator {
13    node_manager: Arc<EdgeNodeManager>,
14    tasks: Arc<RwLock<std::collections::HashMap<Uuid, EdgeTask>>>,
15}
16
17impl EdgeOrchestrator {
18    /// Create a new edge orchestrator
19    pub fn new(node_manager: Arc<EdgeNodeManager>) -> Self {
20        Self {
21            node_manager,
22            tasks: Arc::new(RwLock::new(std::collections::HashMap::new())),
23        }
24    }
25
26    /// Submit a task for execution
27    pub async fn submit_task(
28        &self,
29        task_type: TaskType,
30        payload: serde_json::Value,
31        priority: TaskPriority,
32    ) -> Uuid {
33        let task_id = Uuid::new_v4();
34        let task = EdgeTask {
35            id: task_id,
36            task_type,
37            payload,
38            priority,
39            assigned_node: None,
40            status: TaskStatus::Pending,
41            created_at: Utc::now(),
42            started_at: None,
43            completed_at: None,
44            result: None,
45        };
46
47        self.tasks.write().await.insert(task_id, task);
48        task_id
49    }
50
51    /// Assign task to best available node
52    pub async fn assign_task(&self, task_id: Uuid) -> Result<Uuid, EdgeComputingError> {
53        let online_nodes = self.node_manager.get_online_nodes().await;
54
55        if online_nodes.is_empty() {
56            return Err(EdgeComputingError::ResourceUnavailable(
57                "No online nodes available".to_string(),
58            ));
59        }
60
61        // Simple load balancing: select node with most available resources
62        let best_node = online_nodes
63            .iter()
64            .max_by_key(|node| {
65                (node.capacity.available_cpu * 100.0) as u64 + node.capacity.available_memory_mb
66            })
67            .ok_or_else(|| {
68                EdgeComputingError::ResourceUnavailable("No suitable node found".to_string())
69            })?;
70
71        let mut tasks = self.tasks.write().await;
72        if let Some(task) = tasks.get_mut(&task_id) {
73            task.assigned_node = Some(best_node.id);
74            task.status = TaskStatus::Assigned;
75            Ok(best_node.id)
76        } else {
77            Err(EdgeComputingError::TaskExecutionFailed(
78                "Task not found".to_string(),
79            ))
80        }
81    }
82
83    /// Get task status
84    pub async fn get_task_status(&self, task_id: Uuid) -> Option<TaskStatus> {
85        self.tasks.read().await.get(&task_id).map(|t| t.status)
86    }
87
88    /// Get task result
89    pub async fn get_task_result(&self, task_id: Uuid) -> Option<serde_json::Value> {
90        self.tasks
91            .read()
92            .await
93            .get(&task_id)
94            .and_then(|t| t.result.clone())
95    }
96
97    /// Complete a task
98    pub async fn complete_task(
99        &self,
100        task_id: Uuid,
101        result: serde_json::Value,
102    ) -> Result<(), EdgeComputingError> {
103        let mut tasks = self.tasks.write().await;
104        if let Some(task) = tasks.get_mut(&task_id) {
105            task.status = TaskStatus::Completed;
106            task.completed_at = Some(Utc::now());
107            task.result = Some(result);
108            Ok(())
109        } else {
110            Err(EdgeComputingError::TaskExecutionFailed(
111                "Task not found".to_string(),
112            ))
113        }
114    }
115
116    /// Fail a task
117    pub async fn fail_task(&self, task_id: Uuid, error: String) -> Result<(), EdgeComputingError> {
118        let mut tasks = self.tasks.write().await;
119        if let Some(task) = tasks.get_mut(&task_id) {
120            task.status = TaskStatus::Failed;
121            task.completed_at = Some(Utc::now());
122            task.result = Some(serde_json::json!({ "error": error }));
123            Ok(())
124        } else {
125            Err(EdgeComputingError::TaskExecutionFailed(
126                "Task not found".to_string(),
127            ))
128        }
129    }
130
131    /// Get pending tasks
132    pub async fn get_pending_tasks(&self) -> Vec<EdgeTask> {
133        self.tasks
134            .read()
135            .await
136            .values()
137            .filter(|t| t.status == TaskStatus::Pending)
138            .cloned()
139            .collect()
140    }
141}