Skip to main content

yaiko_core/
media_annotations.rs

1//! Collaborative timeline annotations for shared media-editor projects.
2
3use std::collections::HashMap;
4use std::sync::{Arc, Mutex};
5
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub enum AnnotationError {
8    InvalidId,
9    InvalidText,
10    InvalidRange,
11    NotFound,
12    ScopeMismatch,
13    RevisionConflict,
14    Capacity,
15    StateConflict,
16}
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum AnnotationState {
19    Open,
20    Resolved,
21}
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct AnnotationReply {
24    pub id: String,
25    pub author: String,
26    pub text: String,
27}
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct MediaAnnotation {
30    pub id: String,
31    pub project_id: String,
32    pub scope: String,
33    pub author: String,
34    pub start_ms: u64,
35    pub end_ms: u64,
36    pub revision: u64,
37    pub text: String,
38    pub state: AnnotationState,
39    pub replies: Vec<AnnotationReply>,
40}
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct AnnotationSnapshot {
43    pub project_id: String,
44    pub scope: String,
45    pub annotations: Vec<MediaAnnotation>,
46}
47#[derive(Debug, Clone)]
48pub struct MediaAnnotationStore {
49    inner: Arc<Mutex<HashMap<String, Vec<MediaAnnotation>>>>,
50    max_projects: usize,
51    max_annotations: usize,
52    max_replies: usize,
53}
54impl MediaAnnotationStore {
55    pub fn new(max_projects: usize, max_annotations: usize, max_replies: usize) -> Self {
56        Self {
57            inner: Arc::new(Mutex::new(HashMap::new())),
58            max_projects: max_projects.max(1),
59            max_annotations: max_annotations.max(1),
60            max_replies: max_replies.max(1),
61        }
62    }
63    #[allow(clippy::too_many_arguments)]
64    pub fn create(
65        &self,
66        project_id: impl Into<String>,
67        scope: impl Into<String>,
68        author: impl Into<String>,
69        id: impl Into<String>,
70        start_ms: u64,
71        end_ms: u64,
72        revision: u64,
73        text: impl Into<String>,
74    ) -> Result<AnnotationSnapshot, AnnotationError> {
75        let project_id = valid(project_id.into())?;
76        let scope = valid(scope.into())?;
77        let author = valid(author.into())?;
78        let id = valid(id.into())?;
79        let text = valid_text(text.into())?;
80        if end_ms <= start_ms {
81            return Err(AnnotationError::InvalidRange);
82        }
83        if revision == 0 {
84            return Err(AnnotationError::RevisionConflict);
85        }
86        let mut guard = self.inner.lock().unwrap();
87        if !guard.contains_key(&project_id) && guard.len() >= self.max_projects {
88            return Err(AnnotationError::Capacity);
89        }
90        let annotations = guard.entry(project_id.clone()).or_default();
91        if annotations.len() >= self.max_annotations
92            || annotations.iter().any(|annotation| annotation.id == id)
93        {
94            return Err(if annotations.len() >= self.max_annotations {
95                AnnotationError::Capacity
96            } else {
97                AnnotationError::StateConflict
98            });
99        }
100        annotations.push(MediaAnnotation {
101            id,
102            project_id: project_id.clone(),
103            scope: scope.clone(),
104            author,
105            start_ms,
106            end_ms,
107            revision,
108            text,
109            state: AnnotationState::Open,
110            replies: Vec::new(),
111        });
112        Ok(snapshot(&project_id, &scope, annotations))
113    }
114    #[allow(clippy::too_many_arguments)]
115    pub fn reply(
116        &self,
117        project_id: &str,
118        scope: &str,
119        annotation_id: &str,
120        expected_revision: u64,
121        reply_id: impl Into<String>,
122        author: impl Into<String>,
123        text: impl Into<String>,
124    ) -> Result<AnnotationSnapshot, AnnotationError> {
125        let reply_id = valid(reply_id.into())?;
126        let author = valid(author.into())?;
127        let text = valid_text(text.into())?;
128        let mut guard = self.inner.lock().unwrap();
129        let annotations = guard.get_mut(project_id).ok_or(AnnotationError::NotFound)?;
130        let annotation = annotations
131            .iter_mut()
132            .find(|annotation| annotation.id == annotation_id)
133            .ok_or(AnnotationError::NotFound)?;
134        if annotation.scope != scope {
135            return Err(AnnotationError::ScopeMismatch);
136        }
137        if annotation.revision != expected_revision {
138            return Err(AnnotationError::RevisionConflict);
139        }
140        if annotation.replies.len() >= self.max_replies
141            || annotation.replies.iter().any(|reply| reply.id == reply_id)
142        {
143            return Err(AnnotationError::Capacity);
144        }
145        annotation.replies.push(AnnotationReply {
146            id: reply_id,
147            author,
148            text,
149        });
150        Ok(snapshot(project_id, scope, annotations))
151    }
152    pub fn set_state(
153        &self,
154        project_id: &str,
155        scope: &str,
156        annotation_id: &str,
157        expected_revision: u64,
158        state: AnnotationState,
159    ) -> Result<AnnotationSnapshot, AnnotationError> {
160        let mut guard = self.inner.lock().unwrap();
161        let annotations = guard.get_mut(project_id).ok_or(AnnotationError::NotFound)?;
162        let annotation = annotations
163            .iter_mut()
164            .find(|annotation| annotation.id == annotation_id)
165            .ok_or(AnnotationError::NotFound)?;
166        if annotation.scope != scope {
167            return Err(AnnotationError::ScopeMismatch);
168        }
169        if annotation.revision != expected_revision {
170            return Err(AnnotationError::RevisionConflict);
171        }
172        if annotation.state == state {
173            return Err(AnnotationError::StateConflict);
174        }
175        annotation.state = state;
176        annotation.revision = annotation
177            .revision
178            .checked_add(1)
179            .ok_or(AnnotationError::RevisionConflict)?;
180        Ok(snapshot(project_id, scope, annotations))
181    }
182    pub fn snapshot(
183        &self,
184        project_id: &str,
185        scope: &str,
186    ) -> Result<AnnotationSnapshot, AnnotationError> {
187        let guard = self.inner.lock().unwrap();
188        let annotations = guard.get(project_id).ok_or(AnnotationError::NotFound)?;
189        if annotations
190            .iter()
191            .any(|annotation| annotation.scope != scope)
192        {
193            return Err(AnnotationError::ScopeMismatch);
194        }
195        Ok(snapshot(project_id, scope, annotations))
196    }
197}
198fn valid(value: String) -> Result<String, AnnotationError> {
199    if value.is_empty()
200        || value.len() > 128
201        || value
202            .chars()
203            .any(|c| c.is_control() || matches!(c, '/' | '\\'))
204    {
205        return Err(AnnotationError::InvalidId);
206    }
207    Ok(value)
208}
209fn valid_text(value: String) -> Result<String, AnnotationError> {
210    if value.is_empty() || value.len() > 4096 || value.chars().any(char::is_control) {
211        return Err(AnnotationError::InvalidText);
212    }
213    Ok(value)
214}
215fn snapshot(project_id: &str, scope: &str, annotations: &[MediaAnnotation]) -> AnnotationSnapshot {
216    let mut annotations = annotations.to_vec();
217    annotations.sort_by(|a, b| a.start_ms.cmp(&b.start_ms).then_with(|| a.id.cmp(&b.id)));
218    AnnotationSnapshot {
219        project_id: project_id.into(),
220        scope: scope.into(),
221        annotations,
222    }
223}
224
225#[cfg(test)]
226mod tests {
227    #[allow(unused_imports)]
228    use super::*;
229    #[test]
230    fn creates_replies_resolves_and_orders() {
231        let store = MediaAnnotationStore::new(2, 4, 2);
232        let first = store
233            .create(
234                "project", "tenant", "author", "note-b", 100, 200, 1, "later",
235            )
236            .unwrap();
237        let second = store
238            .create("project", "tenant", "author", "note-a", 0, 50, 1, "intro")
239            .unwrap();
240        assert_eq!(second.annotations[0].id, "note-a");
241        let replied = store
242            .reply(
243                "project",
244                "tenant",
245                "note-a",
246                1,
247                "reply-1",
248                "reviewer",
249                "looks good",
250            )
251            .unwrap();
252        assert_eq!(replied.annotations[0].replies.len(), 1);
253        let resolved = store
254            .set_state("project", "tenant", "note-a", 1, AnnotationState::Resolved)
255            .unwrap();
256        assert_eq!(resolved.annotations[0].state, AnnotationState::Resolved);
257        assert_eq!(first.annotations.len(), 1);
258    }
259    #[test]
260    fn rejects_invalid_scope_revision_and_bounds() {
261        let store = MediaAnnotationStore::new(1, 1, 1);
262        store
263            .create("project", "tenant", "author", "note", 0, 100, 1, "text")
264            .unwrap();
265        assert_eq!(
266            store.reply("project", "other", "note", 1, "reply", "author", "text"),
267            Err(AnnotationError::ScopeMismatch)
268        );
269        assert_eq!(
270            store.set_state("project", "tenant", "note", 2, AnnotationState::Resolved),
271            Err(AnnotationError::RevisionConflict)
272        );
273        assert_eq!(
274            store.create("project", "tenant", "author", "second", 0, 1, 1, "text"),
275            Err(AnnotationError::Capacity)
276        );
277    }
278}