sonos-sdk-state-store 0.5.2

Generic, type-safe state management with change detection and blocking iteration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
//! Type-erased property storage and state management
//!
//! This module provides the core storage primitives for state management:
//! - `PropertyBag`: Type-erased storage for a single entity's properties
//! - `StateStore<Id>`: Collection of entities with their property bags

use std::any::{Any, TypeId};
use std::collections::{HashMap, HashSet};
use std::hash::Hash;
use std::sync::{mpsc, Arc, Mutex, RwLock};
use std::time::Instant;

use crate::event::ChangeEvent;
use crate::iter::ChangeIterator;
use crate::property::Property;

// ============================================================================
// PropertyBag - type-erased property storage for a single entity
// ============================================================================

/// Type-erased storage for an entity's properties
///
/// Uses `TypeId` to store and retrieve strongly-typed values.
/// Change detection is built-in via `PartialEq` comparison.
///
/// # Example
///
/// ```rust,ignore
/// use state_store::{PropertyBag, Property};
///
/// #[derive(Clone, PartialEq, Debug)]
/// struct Volume(u8);
/// impl Property for Volume {
///     const KEY: &'static str = "volume";
/// }
///
/// let mut bag = PropertyBag::new();
/// assert!(bag.get::<Volume>().is_none());
///
/// // First set returns true (value changed)
/// assert!(bag.set(Volume(50)));
///
/// // Same value returns false (no change)
/// assert!(!bag.set(Volume(50)));
///
/// // Different value returns true
/// assert!(bag.set(Volume(75)));
///
/// assert_eq!(bag.get::<Volume>(), Some(Volume(75)));
/// ```
pub struct PropertyBag {
    values: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
}

impl PropertyBag {
    /// Create a new empty property bag
    pub fn new() -> Self {
        Self {
            values: HashMap::new(),
        }
    }

    /// Get a property value by type
    ///
    /// Returns `None` if the property has not been set.
    pub fn get<P: Property>(&self) -> Option<P> {
        let type_id = TypeId::of::<P>();
        self.values
            .get(&type_id)
            .and_then(|boxed| boxed.downcast_ref::<P>())
            .cloned()
    }

    /// Set a property value, returning whether the value changed
    ///
    /// Uses `PartialEq` comparison to detect actual changes.
    /// Returns `true` if the value was different (or newly set),
    /// `false` if the value was the same.
    pub fn set<P: Property>(&mut self, value: P) -> bool {
        let type_id = TypeId::of::<P>();
        let current = self
            .values
            .get(&type_id)
            .and_then(|boxed| boxed.downcast_ref::<P>());

        if current != Some(&value) {
            self.values.insert(type_id, Box::new(value));
            true
        } else {
            false
        }
    }

    /// Remove a property, returning whether it existed
    pub fn remove<P: Property>(&mut self) -> bool {
        let type_id = TypeId::of::<P>();
        self.values.remove(&type_id).is_some()
    }

    /// Check if a property exists
    pub fn contains<P: Property>(&self) -> bool {
        let type_id = TypeId::of::<P>();
        self.values.contains_key(&type_id)
    }

    /// Get the number of properties stored
    pub fn len(&self) -> usize {
        self.values.len()
    }

    /// Check if the bag is empty
    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }

    /// Clear all properties
    pub fn clear(&mut self) {
        self.values.clear();
    }
}

impl Default for PropertyBag {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Debug for PropertyBag {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PropertyBag")
            .field("property_count", &self.values.len())
            .finish()
    }
}

// ============================================================================
// StateStore<Id> - generic state store for entities
// ============================================================================

/// Generic state store for managing entity properties with change detection
///
/// The store is generic over the entity ID type, allowing it to be used
/// with any identifier (strings, custom IDs, etc.).
///
/// # Features
///
/// - Type-safe property storage and retrieval
/// - Change detection (only emits events when values actually change)
/// - Watch pattern (register interest in property changes)
/// - Blocking iteration over change events
///
/// # Example
///
/// ```rust,ignore
/// use state_store::{StateStore, Property};
///
/// #[derive(Clone, PartialEq, Debug)]
/// struct Temperature(f32);
/// impl Property for Temperature {
///     const KEY: &'static str = "temperature";
/// }
///
/// let store = StateStore::<String>::new();
/// let sensor_id = "sensor-1".to_string();
///
/// // Watch for temperature changes on sensor-1
/// store.watch(sensor_id.clone(), Temperature::KEY);
///
/// // Set temperature (will emit change event since watched)
/// store.set(&sensor_id, Temperature(72.5));
///
/// // Get current value
/// let temp = store.get::<Temperature>(&sensor_id);
/// assert_eq!(temp, Some(Temperature(72.5)));
/// ```
pub struct StateStore<Id>
where
    Id: Clone + Eq + Hash + Send + Sync + 'static,
{
    /// Entity property storage: entity_id -> PropertyBag
    entities: Arc<RwLock<HashMap<Id, PropertyBag>>>,

    /// Watched properties: (entity_id, property_key)
    watched: Arc<RwLock<HashSet<(Id, &'static str)>>>,

    /// Channel sender for change events
    event_tx: mpsc::Sender<ChangeEvent<Id>>,

    /// Channel receiver for change events (wrapped for cloning)
    event_rx: Arc<Mutex<mpsc::Receiver<ChangeEvent<Id>>>>,
}

impl<Id> StateStore<Id>
where
    Id: Clone + Eq + Hash + Send + Sync + 'static,
{
    /// Create a new empty state store
    pub fn new() -> Self {
        let (event_tx, event_rx) = mpsc::channel();

        Self {
            entities: Arc::new(RwLock::new(HashMap::new())),
            watched: Arc::new(RwLock::new(HashSet::new())),
            event_tx,
            event_rx: Arc::new(Mutex::new(event_rx)),
        }
    }

    /// Get a property value for an entity
    ///
    /// Returns `None` if the entity doesn't exist or the property isn't set.
    pub fn get<P: Property>(&self, entity_id: &Id) -> Option<P> {
        let entities = self.entities.read().ok()?;
        entities.get(entity_id)?.get::<P>()
    }

    /// Set a property value for an entity
    ///
    /// If the value changes and the property is being watched,
    /// a change event is emitted.
    pub fn set<P: Property>(&self, entity_id: &Id, value: P) {
        let changed = {
            let mut entities = match self.entities.write() {
                Ok(e) => e,
                Err(_) => return,
            };
            let bag = entities
                .entry(entity_id.clone())
                .or_insert_with(PropertyBag::new);
            bag.set(value)
        };

        if changed {
            self.maybe_emit_change(entity_id, P::KEY);
        }
    }

    /// Register interest in a property for an entity
    ///
    /// After watching, changes to this property will appear in `iter()`.
    pub fn watch(&self, entity_id: Id, property_key: &'static str) {
        if let Ok(mut watched) = self.watched.write() {
            watched.insert((entity_id, property_key));
        }
    }

    /// Unregister interest in a property
    pub fn unwatch(&self, entity_id: &Id, property_key: &'static str) {
        if let Ok(mut watched) = self.watched.write() {
            watched.remove(&(entity_id.clone(), property_key));
        }
    }

    /// Check if a property is being watched
    pub fn is_watched(&self, entity_id: &Id, property_key: &'static str) -> bool {
        self.watched
            .read()
            .map(|w| w.contains(&(entity_id.clone(), property_key)))
            .unwrap_or(false)
    }

    /// Create a blocking iterator over change events
    ///
    /// Only emits events for properties that have been watched.
    pub fn iter(&self) -> ChangeIterator<Id> {
        ChangeIterator::new(Arc::clone(&self.event_rx))
    }

    /// Get the number of entities in the store
    pub fn entity_count(&self) -> usize {
        self.entities.read().map(|e| e.len()).unwrap_or(0)
    }

    /// Check if the store is empty
    pub fn is_empty(&self) -> bool {
        self.entity_count() == 0
    }

    /// Get all entity IDs
    pub fn entity_ids(&self) -> Vec<Id> {
        self.entities
            .read()
            .map(|e| e.keys().cloned().collect())
            .unwrap_or_default()
    }

    /// Remove an entity and all its properties
    pub fn remove_entity(&self, entity_id: &Id) -> bool {
        self.entities
            .write()
            .map(|mut e| e.remove(entity_id).is_some())
            .unwrap_or(false)
    }

    /// Clear all entities and properties
    pub fn clear(&self) {
        if let Ok(mut entities) = self.entities.write() {
            entities.clear();
        }
        if let Ok(mut watched) = self.watched.write() {
            watched.clear();
        }
    }

    /// Get the event sender for external event injection
    ///
    /// This is useful for testing or for injecting events from
    /// external sources (e.g., network callbacks).
    pub fn event_sender(&self) -> mpsc::Sender<ChangeEvent<Id>> {
        self.event_tx.clone()
    }

    /// Emit a change event if the property is being watched
    fn maybe_emit_change(&self, entity_id: &Id, property_key: &'static str) {
        let is_watched = self
            .watched
            .read()
            .map(|w| w.contains(&(entity_id.clone(), property_key)))
            .unwrap_or(false);

        if is_watched {
            let event = ChangeEvent {
                entity_id: entity_id.clone(),
                property_key,
                timestamp: Instant::now(),
            };
            let _ = self.event_tx.send(event);
        }
    }
}

impl<Id> Default for StateStore<Id>
where
    Id: Clone + Eq + Hash + Send + Sync + 'static,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<Id> Clone for StateStore<Id>
where
    Id: Clone + Eq + Hash + Send + Sync + 'static,
{
    fn clone(&self) -> Self {
        Self {
            entities: Arc::clone(&self.entities),
            watched: Arc::clone(&self.watched),
            event_tx: self.event_tx.clone(),
            event_rx: Arc::clone(&self.event_rx),
        }
    }
}

impl<Id> std::fmt::Debug for StateStore<Id>
where
    Id: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StateStore")
            .field("entity_count", &self.entity_count())
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Clone, PartialEq, Debug)]
    struct TestProp(i32);

    impl Property for TestProp {
        const KEY: &'static str = "test";
    }

    #[derive(Clone, PartialEq, Debug)]
    struct OtherProp(String);

    impl Property for OtherProp {
        const KEY: &'static str = "other";
    }

    #[test]
    fn test_property_bag_basic() {
        let mut bag = PropertyBag::new();

        // Initially empty
        assert!(bag.is_empty());
        assert!(bag.get::<TestProp>().is_none());

        // Set returns true (value changed)
        assert!(bag.set(TestProp(42)));
        assert!(!bag.is_empty());
        assert_eq!(bag.get::<TestProp>(), Some(TestProp(42)));

        // Same value returns false
        assert!(!bag.set(TestProp(42)));

        // Different value returns true
        assert!(bag.set(TestProp(99)));
        assert_eq!(bag.get::<TestProp>(), Some(TestProp(99)));
    }

    #[test]
    fn test_property_bag_multiple_types() {
        let mut bag = PropertyBag::new();

        bag.set(TestProp(42));
        bag.set(OtherProp("hello".to_string()));

        assert_eq!(bag.len(), 2);
        assert_eq!(bag.get::<TestProp>(), Some(TestProp(42)));
        assert_eq!(bag.get::<OtherProp>(), Some(OtherProp("hello".to_string())));
    }

    #[test]
    fn test_state_store_basic() {
        let store = StateStore::<String>::new();

        // Initially empty
        assert!(store.is_empty());
        assert!(store.get::<TestProp>(&"entity-1".to_string()).is_none());

        // Set creates entity
        store.set(&"entity-1".to_string(), TestProp(42));
        assert_eq!(store.entity_count(), 1);
        assert_eq!(
            store.get::<TestProp>(&"entity-1".to_string()),
            Some(TestProp(42))
        );
    }

    #[test]
    fn test_state_store_watch() {
        let store = StateStore::<String>::new();
        let entity_id = "entity-1".to_string();

        // Not watched initially
        assert!(!store.is_watched(&entity_id, TestProp::KEY));

        // Watch
        store.watch(entity_id.clone(), TestProp::KEY);
        assert!(store.is_watched(&entity_id, TestProp::KEY));

        // Unwatch
        store.unwatch(&entity_id, TestProp::KEY);
        assert!(!store.is_watched(&entity_id, TestProp::KEY));
    }

    #[test]
    fn test_state_store_change_event() {
        let store = StateStore::<String>::new();
        let entity_id = "entity-1".to_string();

        // Watch the property
        store.watch(entity_id.clone(), TestProp::KEY);

        // Set value (should emit event)
        store.set(&entity_id, TestProp(42));

        // Get event via iter
        let iter = store.iter();
        let event = iter.recv_timeout(std::time::Duration::from_millis(100));
        assert!(event.is_some());

        let event = event.unwrap();
        assert_eq!(event.entity_id, entity_id);
        assert_eq!(event.property_key, TestProp::KEY);
    }

    #[test]
    fn test_state_store_no_event_when_not_watched() {
        let store = StateStore::<String>::new();
        let entity_id = "entity-1".to_string();

        // Set without watching
        store.set(&entity_id, TestProp(42));

        // No event should be emitted
        let iter = store.iter();
        let event = iter.recv_timeout(std::time::Duration::from_millis(50));
        assert!(event.is_none());
    }

    #[test]
    fn test_state_store_no_event_when_same_value() {
        let store = StateStore::<String>::new();
        let entity_id = "entity-1".to_string();

        store.watch(entity_id.clone(), TestProp::KEY);

        // First set emits event
        store.set(&entity_id, TestProp(42));

        let iter = store.iter();
        let event = iter.recv_timeout(std::time::Duration::from_millis(100));
        assert!(event.is_some());

        // Same value does not emit event
        store.set(&entity_id, TestProp(42));
        let event = iter.recv_timeout(std::time::Duration::from_millis(50));
        assert!(event.is_none());
    }

    #[test]
    fn test_state_store_clone() {
        let store = StateStore::<String>::new();
        let cloned = store.clone();

        // Both share the same state
        store.set(&"entity-1".to_string(), TestProp(42));
        assert_eq!(
            cloned.get::<TestProp>(&"entity-1".to_string()),
            Some(TestProp(42))
        );
    }
}