tiny-counter 0.1.0

Track event counts across time windows with fixed memory and fast queries
Documentation
//! Compact operation tests - storage compression and memory cleanup.
//!
//! Tests compacting storage by loading all events, advancing counters,
//! persisting updated data, and freeing memory.

use tiny_counter::EventStore;

#[cfg(feature = "serde")]
#[test]
fn compact_updates_config_and_clears_memory() {
    use tiny_counter::storage::MemoryStorage;

    // Create store with initial config
    let mut store = EventStore::builder()
        .track_days(7)
        .with_storage(MemoryStorage::new())
        .build()
        .unwrap();

    // Record events
    store.record_count("event1", 100);
    store.record_count("event2", 50);

    // Persist to storage
    store.persist_all().unwrap();

    // Get memory usage before compact
    let memory_before = store.memory_usage();
    assert!(memory_before > 0);

    // Compact storage
    store.compact().unwrap();

    // Memory should be cleared
    let memory_after = store.memory_usage();
    assert_eq!(memory_after, 0);

    // Events should still be queryable (lazy-loaded from storage)
    assert_eq!(store.query("event1").last_days(7).sum(), Some(100));
    assert_eq!(store.query("event2").last_days(7).sum(), Some(50));

    // Memory should be used again after loading
    assert!(store.memory_usage() > 0);
}

#[cfg(feature = "serde")]
#[test]
fn compact_persists_to_storage() {
    use tiny_counter::storage::MemoryStorage;

    let mut store = EventStore::builder()
        .track_days(7)
        .with_storage(MemoryStorage::new())
        .build()
        .unwrap();

    store.record_count("event1", 100);
    store.record_count("event2", 50);

    // Compact (advances, persists, clears memory)
    store.compact().unwrap();

    // Memory should be cleared
    assert_eq!(store.memory_usage(), 0);

    // But data is in storage - querying should load it
    assert_eq!(store.query("event1").last_days(7).sum(), Some(100));
    assert_eq!(store.query("event2").last_days(7).sum(), Some(50));
}

#[cfg(feature = "serde")]
#[test]
fn scenario_config_migration() {
    use tiny_counter::storage::MemoryStorage;

    let mut store = EventStore::builder()
        .track_days(7)
        .with_storage(MemoryStorage::new())
        .build()
        .unwrap();

    // Phase 1: Record with old config (7 days)
    store.record_count("user_signups", 100);
    store.persist_all().unwrap();

    // Phase 2: Change config (simulate app upgrade with longer retention)
    // In real usage, you'd recreate the store with new builder config
    // Here we'll test that compact works with current config
    store.compact().unwrap();

    // Memory cleared, but data persisted
    assert_eq!(store.memory_usage(), 0);

    // Phase 3: Verify data survived compaction
    assert_eq!(store.query("user_signups").last_days(7).sum(), Some(100));
}