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 => match (&new_value, &self.value) {
113                (Value::Float(new), Value::Float(old)) => new < old,
114                (Value::Int(new), Value::Int(old)) => new < old,
115                _ => true,
116            },
117            ConflictStrategy::Lock => {
118                self.lock_holder.is_none() || self.lock_holder.as_deref() == Some(writer)
119            }
120            ConflictStrategy::Merge => true, // App handles merge
121        };
122
123        if !should_update {
124            return Err(UpdateError::ConflictRejected);
125        }
126
127        // Handle lock request
128        if request_lock {
129            if self.lock_holder.is_some() && self.lock_holder.as_deref() != Some(writer) {
130                return Err(UpdateError::LockHeld {
131                    holder: self.lock_holder.clone().unwrap(),
132                });
133            }
134            self.lock_holder = Some(writer.to_string());
135        }
136
137        // Apply update
138        self.value = new_value;
139        self.revision += 1;
140        self.writer = writer.to_string();
141        self.timestamp = timestamp;
142
143        Ok(self.revision)
144    }
145
146    /// Check if value is within range (if specified)
147    pub fn validate_range(&self, value: &Value) -> bool {
148        if let Some(meta) = &self.meta {
149            if let Some((min, max)) = meta.range {
150                if let Some(v) = value.as_f64() {
151                    return v >= min && v <= max;
152                }
153            }
154        }
155        true
156    }
157}
158
159/// Errors that can occur during state updates
160#[derive(Debug, Clone)]
161pub enum UpdateError {
162    RevisionConflict { expected: u64, actual: u64 },
163    LockHeld { holder: String },
164    ConflictRejected,
165    OutOfRange,
166}
167
168/// State store for multiple params
169#[derive(Debug, Default)]
170pub struct StateStore {
171    params: HashMap<String, ParamState>,
172}
173
174impl StateStore {
175    pub fn new() -> Self {
176        Self::default()
177    }
178
179    /// Get a param's current state
180    pub fn get(&self, address: &str) -> Option<&ParamState> {
181        self.params.get(address)
182    }
183
184    /// Get a param's current value
185    pub fn get_value(&self, address: &str) -> Option<&Value> {
186        self.params.get(address).map(|p| &p.value)
187    }
188
189    /// Set a param value, creating if necessary
190    pub fn set(
191        &mut self,
192        address: &str,
193        value: Value,
194        writer: &str,
195        revision: Option<u64>,
196        lock: bool,
197        unlock: bool,
198    ) -> Result<u64, UpdateError> {
199        if let Some(param) = self.params.get_mut(address) {
200            param.try_update(value, writer, revision, lock, unlock)
201        } else {
202            // Create new param
203            let mut param = ParamState::new(value, writer.to_string());
204            if lock {
205                param.lock_holder = Some(writer.to_string());
206            }
207            let rev = param.revision;
208            self.params.insert(address.to_string(), param);
209            Ok(rev)
210        }
211    }
212
213    /// Get all params matching a pattern
214    pub fn get_matching(&self, pattern: &str) -> Vec<(&str, &ParamState)> {
215        use crate::address::glob_match;
216
217        self.params
218            .iter()
219            .filter(|(addr, _)| glob_match(pattern, addr))
220            .map(|(addr, state)| (addr.as_str(), state))
221            .collect()
222    }
223
224    /// Get all params as a snapshot
225    pub fn snapshot(&self) -> Vec<(&str, &ParamState)> {
226        self.params.iter().map(|(k, v)| (k.as_str(), v)).collect()
227    }
228
229    /// Number of params
230    pub fn len(&self) -> usize {
231        self.params.len()
232    }
233
234    /// Check if empty
235    pub fn is_empty(&self) -> bool {
236        self.params.is_empty()
237    }
238
239    /// Remove a param
240    pub fn remove(&mut self, address: &str) -> Option<ParamState> {
241        self.params.remove(address)
242    }
243
244    /// Clear all params
245    pub fn clear(&mut self) {
246        self.params.clear();
247    }
248}
249
250/// Get current timestamp in microseconds
251fn current_timestamp() -> u64 {
252    SystemTime::now()
253        .duration_since(UNIX_EPOCH)
254        .unwrap()
255        .as_micros() as u64
256}
257
258#[cfg(test)]
259mod tests {
260    use super::*;
261
262    #[test]
263    fn test_basic_update() {
264        let mut state = ParamState::new(Value::Float(0.5), "session1".to_string());
265
266        let result = state.try_update(Value::Float(0.75), "session2", None, false, false);
267
268        assert!(result.is_ok());
269        assert_eq!(state.revision, 2);
270        assert_eq!(state.value, Value::Float(0.75));
271        assert_eq!(state.writer, "session2");
272    }
273
274    #[test]
275    fn test_revision_conflict() {
276        let mut state = ParamState::new(Value::Float(0.5), "session1".to_string());
277
278        let result = state.try_update(
279            Value::Float(0.75),
280            "session2",
281            Some(999), // Wrong revision
282            false,
283            false,
284        );
285
286        assert!(matches!(result, Err(UpdateError::RevisionConflict { .. })));
287    }
288
289    #[test]
290    fn test_locking() {
291        let mut state = ParamState::new(Value::Float(0.5), "session1".to_string());
292
293        // Session 1 takes lock
294        let result = state.try_update(
295            Value::Float(0.6),
296            "session1",
297            None,
298            true, // Request lock
299            false,
300        );
301        assert!(result.is_ok());
302        assert_eq!(state.lock_holder, Some("session1".to_string()));
303
304        // Session 2 tries to update - should fail
305        let result = state.try_update(Value::Float(0.7), "session2", None, false, false);
306        assert!(matches!(result, Err(UpdateError::LockHeld { .. })));
307
308        // Session 1 can still update
309        let result = state.try_update(Value::Float(0.8), "session1", None, false, false);
310        assert!(result.is_ok());
311    }
312
313    #[test]
314    fn test_max_strategy() {
315        let mut state = ParamState::new(Value::Float(0.5), "session1".to_string())
316            .with_strategy(ConflictStrategy::Max);
317
318        // Higher value wins
319        let result = state.try_update(Value::Float(0.8), "session2", None, false, false);
320        assert!(result.is_ok());
321        assert_eq!(state.value, Value::Float(0.8));
322
323        // Lower value rejected
324        let result = state.try_update(Value::Float(0.3), "session3", None, false, false);
325        assert!(matches!(result, Err(UpdateError::ConflictRejected)));
326        assert_eq!(state.value, Value::Float(0.8)); // Unchanged
327    }
328
329    #[test]
330    fn test_state_store() {
331        let mut store = StateStore::new();
332
333        store
334            .set("/test/a", Value::Float(1.0), "s1", None, false, false)
335            .unwrap();
336        store
337            .set("/test/b", Value::Float(2.0), "s1", None, false, false)
338            .unwrap();
339        store
340            .set("/other/c", Value::Float(3.0), "s1", None, false, false)
341            .unwrap();
342
343        assert_eq!(store.len(), 3);
344
345        let matching = store.get_matching("/test/*");
346        assert_eq!(matching.len(), 2);
347    }
348}