clasp_core/
state.rs

1//! State management for Clasp params
2//!
3//! Provides conflict resolution and revision tracking for stateful parameters.
4
5use crate::{ConflictStrategy, Value};
6use std::collections::HashMap;
7use std::time::{SystemTime, UNIX_EPOCH};
8
9/// State of a single parameter
10#[derive(Debug, Clone)]
11pub struct ParamState {
12    /// Current value
13    pub value: Value,
14    /// Monotonic revision number
15    pub revision: u64,
16    /// Session ID of last writer
17    pub writer: String,
18    /// Timestamp of last write (microseconds)
19    pub timestamp: u64,
20    /// Conflict resolution strategy
21    pub strategy: ConflictStrategy,
22    /// Lock holder (if locked)
23    pub lock_holder: Option<String>,
24    /// Metadata
25    pub meta: Option<ParamMeta>,
26}
27
28/// Parameter metadata
29#[derive(Debug, Clone)]
30pub struct ParamMeta {
31    pub unit: Option<String>,
32    pub range: Option<(f64, f64)>,
33    pub default: Option<Value>,
34}
35
36impl ParamState {
37    /// Create a new param state
38    pub fn new(value: Value, writer: String) -> Self {
39        Self {
40            value,
41            revision: 1,
42            writer,
43            timestamp: current_timestamp(),
44            strategy: ConflictStrategy::Lww,
45            lock_holder: None,
46            meta: None,
47        }
48    }
49
50    /// Create with specific strategy
51    pub fn with_strategy(mut self, strategy: ConflictStrategy) -> Self {
52        self.strategy = strategy;
53        self
54    }
55
56    /// Create with metadata
57    pub fn with_meta(mut self, meta: ParamMeta) -> Self {
58        self.meta = Some(meta);
59        self
60    }
61
62    /// Attempt to update the value
63    ///
64    /// Returns Ok(new_revision) if update was accepted,
65    /// Err with reason if rejected.
66    pub fn try_update(
67        &mut self,
68        new_value: Value,
69        writer: &str,
70        expected_revision: Option<u64>,
71        request_lock: bool,
72        release_lock: bool,
73    ) -> Result<u64, UpdateError> {
74        let timestamp = current_timestamp();
75
76        // Check optimistic lock (if revision specified)
77        if let Some(expected) = expected_revision {
78            if expected != self.revision {
79                return Err(UpdateError::RevisionConflict {
80                    expected,
81                    actual: self.revision,
82                });
83            }
84        }
85
86        // Check lock
87        if let Some(ref holder) = self.lock_holder {
88            if holder != writer && !release_lock {
89                return Err(UpdateError::LockHeld {
90                    holder: holder.clone(),
91                });
92            }
93        }
94
95        // Handle lock release
96        if release_lock {
97            if self.lock_holder.as_deref() == Some(writer) {
98                self.lock_holder = None;
99            }
100        }
101
102        // Apply conflict resolution
103        let should_update = match self.strategy {
104            ConflictStrategy::Lww => timestamp >= self.timestamp,
105            ConflictStrategy::Max => {
106                match (&new_value, &self.value) {
107                    (Value::Float(new), Value::Float(old)) => new > old,
108                    (Value::Int(new), Value::Int(old)) => new > old,
109                    _ => true, // Fall back to LWW for non-numeric
110                }
111            }
112            ConflictStrategy::Min => {
113                match (&new_value, &self.value) {
114                    (Value::Float(new), Value::Float(old)) => new < old,
115                    (Value::Int(new), Value::Int(old)) => new < old,
116                    _ => true,
117                }
118            }
119            ConflictStrategy::Lock => {
120                self.lock_holder.is_none() || self.lock_holder.as_deref() == Some(writer)
121            }
122            ConflictStrategy::Merge => true, // App handles merge
123        };
124
125        if !should_update {
126            return Err(UpdateError::ConflictRejected);
127        }
128
129        // Handle lock request
130        if request_lock {
131            if self.lock_holder.is_some() && self.lock_holder.as_deref() != Some(writer) {
132                return Err(UpdateError::LockHeld {
133                    holder: self.lock_holder.clone().unwrap(),
134                });
135            }
136            self.lock_holder = Some(writer.to_string());
137        }
138
139        // Apply update
140        self.value = new_value;
141        self.revision += 1;
142        self.writer = writer.to_string();
143        self.timestamp = timestamp;
144
145        Ok(self.revision)
146    }
147
148    /// Check if value is within range (if specified)
149    pub fn validate_range(&self, value: &Value) -> bool {
150        if let Some(meta) = &self.meta {
151            if let Some((min, max)) = meta.range {
152                if let Some(v) = value.as_f64() {
153                    return v >= min && v <= max;
154                }
155            }
156        }
157        true
158    }
159}
160
161/// Errors that can occur during state updates
162#[derive(Debug, Clone)]
163pub enum UpdateError {
164    RevisionConflict { expected: u64, actual: u64 },
165    LockHeld { holder: String },
166    ConflictRejected,
167    OutOfRange,
168}
169
170/// State store for multiple params
171#[derive(Debug, Default)]
172pub struct StateStore {
173    params: HashMap<String, ParamState>,
174}
175
176impl StateStore {
177    pub fn new() -> Self {
178        Self::default()
179    }
180
181    /// Get a param's current state
182    pub fn get(&self, address: &str) -> Option<&ParamState> {
183        self.params.get(address)
184    }
185
186    /// Get a param's current value
187    pub fn get_value(&self, address: &str) -> Option<&Value> {
188        self.params.get(address).map(|p| &p.value)
189    }
190
191    /// Set a param value, creating if necessary
192    pub fn set(
193        &mut self,
194        address: &str,
195        value: Value,
196        writer: &str,
197        revision: Option<u64>,
198        lock: bool,
199        unlock: bool,
200    ) -> Result<u64, UpdateError> {
201        if let Some(param) = self.params.get_mut(address) {
202            param.try_update(value, writer, revision, lock, unlock)
203        } else {
204            // Create new param
205            let mut param = ParamState::new(value, writer.to_string());
206            if lock {
207                param.lock_holder = Some(writer.to_string());
208            }
209            let rev = param.revision;
210            self.params.insert(address.to_string(), param);
211            Ok(rev)
212        }
213    }
214
215    /// Get all params matching a pattern
216    pub fn get_matching(&self, pattern: &str) -> Vec<(&str, &ParamState)> {
217        use crate::address::glob_match;
218
219        self.params
220            .iter()
221            .filter(|(addr, _)| glob_match(pattern, addr))
222            .map(|(addr, state)| (addr.as_str(), state))
223            .collect()
224    }
225
226    /// Get all params as a snapshot
227    pub fn snapshot(&self) -> Vec<(&str, &ParamState)> {
228        self.params.iter().map(|(k, v)| (k.as_str(), v)).collect()
229    }
230
231    /// Number of params
232    pub fn len(&self) -> usize {
233        self.params.len()
234    }
235
236    /// Check if empty
237    pub fn is_empty(&self) -> bool {
238        self.params.is_empty()
239    }
240
241    /// Remove a param
242    pub fn remove(&mut self, address: &str) -> Option<ParamState> {
243        self.params.remove(address)
244    }
245
246    /// Clear all params
247    pub fn clear(&mut self) {
248        self.params.clear();
249    }
250}
251
252/// Get current timestamp in microseconds
253fn current_timestamp() -> u64 {
254    SystemTime::now()
255        .duration_since(UNIX_EPOCH)
256        .unwrap()
257        .as_micros() as u64
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263
264    #[test]
265    fn test_basic_update() {
266        let mut state = ParamState::new(Value::Float(0.5), "session1".to_string());
267
268        let result = state.try_update(
269            Value::Float(0.75),
270            "session2",
271            None,
272            false,
273            false,
274        );
275
276        assert!(result.is_ok());
277        assert_eq!(state.revision, 2);
278        assert_eq!(state.value, Value::Float(0.75));
279        assert_eq!(state.writer, "session2");
280    }
281
282    #[test]
283    fn test_revision_conflict() {
284        let mut state = ParamState::new(Value::Float(0.5), "session1".to_string());
285
286        let result = state.try_update(
287            Value::Float(0.75),
288            "session2",
289            Some(999), // Wrong revision
290            false,
291            false,
292        );
293
294        assert!(matches!(result, Err(UpdateError::RevisionConflict { .. })));
295    }
296
297    #[test]
298    fn test_locking() {
299        let mut state = ParamState::new(Value::Float(0.5), "session1".to_string());
300
301        // Session 1 takes lock
302        let result = state.try_update(
303            Value::Float(0.6),
304            "session1",
305            None,
306            true, // Request lock
307            false,
308        );
309        assert!(result.is_ok());
310        assert_eq!(state.lock_holder, Some("session1".to_string()));
311
312        // Session 2 tries to update - should fail
313        let result = state.try_update(
314            Value::Float(0.7),
315            "session2",
316            None,
317            false,
318            false,
319        );
320        assert!(matches!(result, Err(UpdateError::LockHeld { .. })));
321
322        // Session 1 can still update
323        let result = state.try_update(
324            Value::Float(0.8),
325            "session1",
326            None,
327            false,
328            false,
329        );
330        assert!(result.is_ok());
331    }
332
333    #[test]
334    fn test_max_strategy() {
335        let mut state = ParamState::new(Value::Float(0.5), "session1".to_string())
336            .with_strategy(ConflictStrategy::Max);
337
338        // Higher value wins
339        let result = state.try_update(Value::Float(0.8), "session2", None, false, false);
340        assert!(result.is_ok());
341        assert_eq!(state.value, Value::Float(0.8));
342
343        // Lower value rejected
344        let result = state.try_update(Value::Float(0.3), "session3", None, false, false);
345        assert!(matches!(result, Err(UpdateError::ConflictRejected)));
346        assert_eq!(state.value, Value::Float(0.8)); // Unchanged
347    }
348
349    #[test]
350    fn test_state_store() {
351        let mut store = StateStore::new();
352
353        store.set("/test/a", Value::Float(1.0), "s1", None, false, false).unwrap();
354        store.set("/test/b", Value::Float(2.0), "s1", None, false, false).unwrap();
355        store.set("/other/c", Value::Float(3.0), "s1", None, false, false).unwrap();
356
357        assert_eq!(store.len(), 3);
358
359        let matching = store.get_matching("/test/*");
360        assert_eq!(matching.len(), 2);
361    }
362}