Skip to main content

yaiko_core/
worker.rs

1//! Bounded worker task state machine.
2use std::collections::BTreeMap;
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4pub enum WorkerState {
5    Queued,
6    Running,
7    Succeeded,
8    Failed,
9    Cancelled,
10}
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub enum WorkerError {
13    Capacity,
14    NotFound,
15    InvalidState,
16    InvalidRetries,
17}
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct WorkerTask {
20    pub id: String,
21    pub name: String,
22    pub attempts: u32,
23    pub max_retries: u32,
24    pub state: WorkerState,
25}
26#[derive(Debug, Clone)]
27pub struct WorkerPool {
28    tasks: BTreeMap<String, WorkerTask>,
29    capacity: usize,
30    next_id: u64,
31}
32impl WorkerPool {
33    pub fn new(capacity: usize) -> Self {
34        Self {
35            tasks: BTreeMap::new(),
36            capacity,
37            next_id: 0,
38        }
39    }
40    pub fn submit(
41        &mut self,
42        name: impl Into<String>,
43        max_retries: u32,
44    ) -> Result<WorkerTask, WorkerError> {
45        if self.tasks.len() >= self.capacity {
46            return Err(WorkerError::Capacity);
47        }
48        if max_retries > 32 {
49            return Err(WorkerError::InvalidRetries);
50        }
51        self.next_id += 1;
52        let t = WorkerTask {
53            id: format!("worker-{}", self.next_id),
54            name: name.into(),
55            attempts: 0,
56            max_retries,
57            state: WorkerState::Queued,
58        };
59        self.tasks.insert(t.id.clone(), t.clone());
60        Ok(t)
61    }
62    pub fn start(&mut self, id: &str) -> Result<WorkerTask, WorkerError> {
63        let t = self.tasks.get_mut(id).ok_or(WorkerError::NotFound)?;
64        if t.state != WorkerState::Queued {
65            return Err(WorkerError::InvalidState);
66        }
67        t.state = WorkerState::Running;
68        Ok(t.clone())
69    }
70    pub fn succeed(&mut self, id: &str) -> Result<WorkerTask, WorkerError> {
71        let t = self.tasks.get_mut(id).ok_or(WorkerError::NotFound)?;
72        if t.state != WorkerState::Running {
73            return Err(WorkerError::InvalidState);
74        }
75        t.state = WorkerState::Succeeded;
76        Ok(t.clone())
77    }
78    pub fn fail(&mut self, id: &str) -> Result<WorkerTask, WorkerError> {
79        let t = self.tasks.get_mut(id).ok_or(WorkerError::NotFound)?;
80        if t.state != WorkerState::Running {
81            return Err(WorkerError::InvalidState);
82        }
83        t.attempts += 1;
84        if t.attempts <= t.max_retries {
85            t.state = WorkerState::Queued
86        } else {
87            t.state = WorkerState::Failed
88        }
89        Ok(t.clone())
90    }
91    pub fn cancel(&mut self, id: &str) -> Result<WorkerTask, WorkerError> {
92        let t = self.tasks.get_mut(id).ok_or(WorkerError::NotFound)?;
93        if matches!(
94            t.state,
95            WorkerState::Succeeded | WorkerState::Failed | WorkerState::Cancelled
96        ) {
97            return Err(WorkerError::InvalidState);
98        }
99        t.state = WorkerState::Cancelled;
100        Ok(t.clone())
101    }
102    pub fn snapshot(&self) -> Vec<WorkerTask> {
103        self.tasks.values().cloned().collect()
104    }
105}
106impl Default for WorkerPool {
107    fn default() -> Self {
108        Self::new(1024)
109    }
110}
111#[cfg(test)]
112mod tests {
113    use super::*;
114    #[test]
115    fn retries_then_succeeds() {
116        let mut p = WorkerPool::new(2);
117        let t = p.submit("render", 1).unwrap();
118        p.start(&t.id).unwrap();
119        assert_eq!(p.fail(&t.id).unwrap().state, WorkerState::Queued);
120        p.start(&t.id).unwrap();
121        assert_eq!(p.succeed(&t.id).unwrap().state, WorkerState::Succeeded)
122    }
123    #[test]
124    fn enforces_capacity_cancellation_and_retry_bounds() {
125        let mut p = WorkerPool::new(1);
126        let t = p.submit("x", 0).unwrap();
127        assert_eq!(p.submit("y", 0), Err(WorkerError::Capacity));
128        assert!(p.submit("z", 33).is_err());
129        assert_eq!(p.cancel(&t.id).unwrap().state, WorkerState::Cancelled);
130    }
131}