1use std::collections::{HashMap, VecDeque};
4use std::sync::{Arc, Mutex};
5
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub enum ProgressError {
8 InvalidTask,
9 InvalidStage,
10 InvalidProgress,
11 SequenceMismatch,
12 NonMonotonic,
13 Capacity,
14}
15
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct MediaProgressEvent {
18 pub task_id: String,
19 pub sequence: u64,
20 pub progress: u8,
21 pub stage: String,
22 pub detail: Option<String>,
23}
24
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct ProgressSnapshot {
27 pub latest: Option<MediaProgressEvent>,
28 pub history: Vec<MediaProgressEvent>,
29}
30
31#[derive(Debug, Clone)]
32struct TaskProgress {
33 events: VecDeque<MediaProgressEvent>,
34 latest_progress: u8,
35 next_sequence: u64,
36}
37
38#[derive(Debug, Clone)]
39pub struct MediaProgressStore {
40 inner: Arc<Mutex<HashMap<String, TaskProgress>>>,
41 max_tasks: usize,
42 history_limit: usize,
43}
44
45impl MediaProgressStore {
46 pub fn new(max_tasks: usize, history_limit: usize) -> Self {
47 Self {
48 inner: Arc::new(Mutex::new(HashMap::new())),
49 max_tasks: max_tasks.max(1),
50 history_limit: history_limit.max(1),
51 }
52 }
53 pub fn publish(
54 &self,
55 task_id: impl Into<String>,
56 progress: u8,
57 stage: impl Into<String>,
58 detail: Option<String>,
59 ) -> Result<MediaProgressEvent, ProgressError> {
60 let task_id = validate_task(task_id.into())?;
61 let stage = validate_stage(stage.into())?;
62 if progress > 100 {
63 return Err(ProgressError::InvalidProgress);
64 }
65 let mut guard = self.inner.lock().unwrap();
66 if !guard.contains_key(&task_id) && guard.len() >= self.max_tasks {
67 return Err(ProgressError::Capacity);
68 }
69 let task = guard
70 .entry(task_id.clone())
71 .or_insert_with(|| TaskProgress {
72 events: VecDeque::new(),
73 latest_progress: 0,
74 next_sequence: 0,
75 });
76 if progress < task.latest_progress {
77 return Err(ProgressError::NonMonotonic);
78 }
79 let event = MediaProgressEvent {
80 task_id,
81 sequence: task.next_sequence,
82 progress,
83 stage,
84 detail,
85 };
86 task.next_sequence = task
87 .next_sequence
88 .checked_add(1)
89 .ok_or(ProgressError::SequenceMismatch)?;
90 task.latest_progress = progress;
91 task.events.push_back(event.clone());
92 while task.events.len() > self.history_limit {
93 task.events.pop_front();
94 }
95 Ok(event)
96 }
97 pub fn snapshot(&self, task_id: &str) -> Result<ProgressSnapshot, ProgressError> {
98 let task_id = validate_task(task_id.to_string())?;
99 let guard = self.inner.lock().unwrap();
100 let task = guard.get(&task_id);
101 Ok(ProgressSnapshot {
102 latest: task.and_then(|state| state.events.back().cloned()),
103 history: task
104 .map(|state| state.events.iter().cloned().collect())
105 .unwrap_or_default(),
106 })
107 }
108 pub fn remove(&self, task_id: &str) -> Result<(), ProgressError> {
109 let task_id = validate_task(task_id.to_string())?;
110 self.inner
111 .lock()
112 .unwrap()
113 .remove(&task_id)
114 .map(|_| ())
115 .ok_or(ProgressError::InvalidTask)
116 }
117 pub fn len(&self) -> usize {
118 self.inner.lock().unwrap().len()
119 }
120 pub fn is_empty(&self) -> bool {
121 self.len() == 0
122 }
123}
124
125fn validate_task(task: String) -> Result<String, ProgressError> {
126 if task.is_empty()
127 || task.len() > 128
128 || task
129 .chars()
130 .any(|c| c.is_control() || matches!(c, '/' | '\\'))
131 {
132 return Err(ProgressError::InvalidTask);
133 }
134 Ok(task)
135}
136fn validate_stage(stage: String) -> Result<String, ProgressError> {
137 if stage.is_empty() || stage.len() > 128 || stage.chars().any(|c| c.is_control()) {
138 return Err(ProgressError::InvalidStage);
139 }
140 Ok(stage)
141}
142
143#[cfg(test)]
144mod tests {
145 use super::*;
146 #[test]
147 fn publishes_monotonic_events_and_bounded_history() {
148 let store = MediaProgressStore::new(2, 2);
149 let first = store.publish("task-1", 0, "queued", None).unwrap();
150 let second = store
151 .publish("task-1", 50, "encoding", Some("half".into()))
152 .unwrap();
153 let third = store.publish("task-1", 100, "complete", None).unwrap();
154 assert_eq!((first.sequence, second.sequence, third.sequence), (0, 1, 2));
155 let snapshot = store.snapshot("task-1").unwrap();
156 assert_eq!(snapshot.latest, Some(third));
157 assert_eq!(snapshot.history.len(), 2);
158 assert_eq!(snapshot.history[0].progress, 50);
159 }
160 #[test]
161 fn rejects_invalid_and_decreasing_events() {
162 let store = MediaProgressStore::new(2, 2);
163 assert_eq!(
164 store.publish("task-1", 101, "queued", None),
165 Err(ProgressError::InvalidProgress)
166 );
167 assert_eq!(
168 store.publish("task-1", 1, "", None),
169 Err(ProgressError::InvalidStage)
170 );
171 store.publish("task-1", 50, "encoding", None).unwrap();
172 assert_eq!(
173 store.publish("task-1", 49, "encoding", None),
174 Err(ProgressError::NonMonotonic)
175 );
176 }
177 #[test]
178 fn isolates_tasks_and_bounds_task_capacity() {
179 let store = MediaProgressStore::new(1, 2);
180 store.publish("task-1", 1, "queued", None).unwrap();
181 assert_eq!(
182 store.publish("task-2", 1, "queued", None),
183 Err(ProgressError::Capacity)
184 );
185 assert!(store.snapshot("task-2").unwrap().history.is_empty());
186 store.remove("task-1").unwrap();
187 assert!(store.is_empty());
188 }
189}