tiny-counter 0.1.0

Track event counts across time windows with fixed memory and fast queries
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
/// Builder pattern for EventStore configuration.
use std::sync::Arc;

use crate::{
    Clock, EventCounterConfig, EventStore, IntervalConfig, Result, Storage, SystemClock, TimeUnit,
};

/// Builder for creating an EventStore with custom configuration.
///
/// The builder provides a fluent interface for configuring:
/// - Custom clock implementations (for testing or other purposes)
/// - Storage backends (for persistence)
/// - Time interval tracking (minutes, hours, days, weeks, months, years)
/// - Preset configurations (for rate limiting or analytics)
///
/// # Examples
///
/// ```
/// use tiny_counter::EventStore;
///
/// let store = EventStore::builder()
///     .for_rate_limiting()
///     .build()
///     .unwrap();
/// ```
pub struct EventStoreBuilder {
    clock: Option<Arc<dyn Clock>>,
    storage: Option<Box<dyn Storage>>,
    formatter: Option<Arc<dyn crate::Formatter>>,
    configs: Vec<IntervalConfig>,
    #[cfg(feature = "tokio")]
    auto_persist_interval: Option<chrono::Duration>,
}

impl EventStoreBuilder {
    /// Creates a new builder with no configuration.
    pub(crate) fn new() -> Self {
        Self {
            clock: None,
            storage: None,
            formatter: None,
            configs: Vec::new(),
            #[cfg(feature = "tokio")]
            auto_persist_interval: None,
        }
    }

    /// Sets a custom clock implementation.
    ///
    /// By default, SystemClock is used.
    ///
    /// Accepts either a concrete Clock implementation or an `Arc<dyn Clock>`.
    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
        self.clock = Some(clock);
        self
    }

    /// Sets a storage backend for persistence.
    ///
    /// By default, no storage is configured.
    pub fn with_storage(mut self, storage: impl Storage + 'static) -> Self {
        self.storage = Some(Box::new(storage));
        self
    }

    /// Sets a serialization format for persistence.
    ///
    /// By default, BincodeFormat is used if available.
    pub fn with_format(mut self, formatter: impl crate::Formatter + 'static) -> Self {
        self.formatter = Some(Arc::new(formatter));
        self
    }

    /// Adds second-level tracking with the specified bucket count.
    pub fn track_seconds(mut self, count: usize) -> Self {
        self.configs
            .push(IntervalConfig::new_unchecked(count, TimeUnit::Seconds));
        self
    }

    /// Adds minute-level tracking with the specified bucket count.
    pub fn track_minutes(mut self, count: usize) -> Self {
        self.configs
            .push(IntervalConfig::new_unchecked(count, TimeUnit::Minutes));
        self
    }

    /// Adds hour-level tracking with the specified bucket count.
    pub fn track_hours(mut self, count: usize) -> Self {
        self.configs
            .push(IntervalConfig::new_unchecked(count, TimeUnit::Hours));
        self
    }

    /// Adds day-level tracking with the specified bucket count.
    pub fn track_days(mut self, count: usize) -> Self {
        self.configs
            .push(IntervalConfig::new_unchecked(count, TimeUnit::Days));
        self
    }

    /// Adds week-level tracking with the specified bucket count.
    pub fn track_weeks(mut self, count: usize) -> Self {
        self.configs
            .push(IntervalConfig::new_unchecked(count, TimeUnit::Weeks));
        self
    }

    /// Adds month-level tracking with the specified bucket count.
    pub fn track_months(mut self, count: usize) -> Self {
        self.configs
            .push(IntervalConfig::new_unchecked(count, TimeUnit::Months));
        self
    }

    /// Adds year-level tracking with the specified bucket count.
    pub fn track_years(mut self, count: usize) -> Self {
        self.configs
            .push(IntervalConfig::new_unchecked(count, TimeUnit::Years));
        self
    }

    /// Configures the store for rate limiting use cases.
    ///
    /// Tracks: 60 minutes, 72 hours (short-term tracking)
    pub fn for_rate_limiting(mut self) -> Self {
        self.configs = vec![
            IntervalConfig::new_unchecked(60, TimeUnit::Minutes),
            IntervalConfig::new_unchecked(72, TimeUnit::Hours),
        ];
        self
    }

    /// Configures the store for analytics use cases.
    ///
    /// Tracks: 56 days, 52 weeks, 12 months (long-term tracking)
    pub fn for_analytics(mut self) -> Self {
        self.configs = vec![
            IntervalConfig::new_unchecked(56, TimeUnit::Days),
            IntervalConfig::new_unchecked(52, TimeUnit::Weeks),
            IntervalConfig::new_unchecked(12, TimeUnit::Months),
        ];
        self
    }

    /// Enables automatic background persistence with the specified interval.
    ///
    /// Requires the `tokio` feature to be enabled, storage to be configured, and a formatter to be available.
    /// A background task will periodically check if the store is dirty and persist
    /// if needed.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use tiny_counter::EventStore;
    /// # use tiny_counter::storage::MemoryStorage;
    /// use chrono::Duration;
    ///
    /// let store = EventStore::builder()
    ///     .with_storage(MemoryStorage::new())
    ///     .auto_persist(Duration::seconds(60))
    ///     .build()
    ///     .unwrap();
    /// ```
    #[cfg(feature = "tokio")]
    pub fn auto_persist(mut self, interval: chrono::Duration) -> Self {
        self.auto_persist_interval = Some(interval);
        self
    }

    /// Builds the EventStore with the configured settings.
    ///
    /// If `auto_persist()` was called with the tokio feature enabled,
    /// a background task will be spawned to automatically persist dirty state.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Storage is configured but loading existing data fails
    /// - Any bucket count is invalid
    /// - `auto_persist()` interval is not positive (zero or negative)
    /// - `auto_persist()` is set but storage is not configured
    /// - Storage is configured but no formatter is available
    pub fn build(self) -> Result<EventStore> {
        // Validate auto_persist interval if configured
        #[cfg(feature = "tokio")]
        if let Some(interval) = self.auto_persist_interval {
            if interval.num_milliseconds() <= 0 {
                return Err(crate::error::Error::InvalidAutoPersistInterval(interval));
            }
            // auto_persist requires storage to be configured
            if self.storage.is_none() {
                return Err(crate::error::Error::AutoPersistRequiresStorage);
            }
        }

        let clock = self.clock.unwrap_or_else(|| SystemClock::new());
        let storage = self.storage;

        // Determine formatter if storage is configured
        let formatter = if storage.is_some() {
            match self.formatter {
                Some(f) => Some(f),
                None => {
                    // Try to default to an available formatter
                    #[cfg(feature = "serde-bincode")]
                    {
                        Some(Arc::new(crate::formatter::BincodeFormat) as Arc<dyn crate::Formatter>)
                    }
                    #[cfg(all(feature = "serde-json", not(feature = "serde-bincode")))]
                    {
                        Some(Arc::new(crate::formatter::JsonFormat) as Arc<dyn crate::Formatter>)
                    }
                    #[cfg(not(any(feature = "serde-bincode", feature = "serde-json")))]
                    {
                        return Err(crate::error::Error::NoFormatterForStorage);
                    }
                }
            }
        } else {
            None
        };

        let config = if self.configs.is_empty() {
            // Use default configuration
            EventCounterConfig::default()
        } else {
            // Validate all bucket counts
            for config in &self.configs {
                config.validate()?;
            }
            EventCounterConfig::new(self.configs)
        };

        // Create the base EventStore using the internal constructor
        #[allow(unused_mut)] // mut needed when tokio feature enabled
        let mut base_store = super::EventStore::from_parts(clock, storage, formatter, config);

        // If tokio feature enabled and auto_persist configured, spawn background task
        #[cfg(feature = "tokio")]
        {
            if let Some(_interval) = self.auto_persist_interval {
                let handle =
                    super::EventStore::spawn_auto_persist(base_store.inner.clone(), _interval);
                base_store.auto_persist_handle = Some(handle);
            }
        }

        // Return EventStore (which is now just BaseEventStore)
        Ok(base_store)
    }
}

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

impl EventStore {
    /// Creates a builder for configuring an EventStore.
    pub fn builder() -> EventStoreBuilder {
        EventStoreBuilder::new()
    }
}

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

    use crate::storage::MemoryStorage;
    use crate::TestClock;

    #[test]
    fn test_new_builder() {
        let builder = EventStoreBuilder::new();
        assert!(builder.clock.is_none());
        assert!(builder.storage.is_none());
        assert_eq!(builder.configs.len(), 0);
    }

    #[test]
    fn test_default_builder() {
        let builder = EventStoreBuilder::default();
        assert!(builder.clock.is_none());
        assert!(builder.storage.is_none());
        assert_eq!(builder.configs.len(), 0);
    }

    #[test]
    fn test_with_clock() {
        let clock = TestClock::new();
        let builder = EventStoreBuilder::new().with_clock(clock);
        assert!(builder.clock.is_some());
    }

    #[test]
    fn test_with_storage() {
        let storage = MemoryStorage::new();
        let builder = EventStoreBuilder::new().with_storage(storage);
        assert!(builder.storage.is_some());
    }

    #[test]
    fn test_track_minutes() {
        let builder = EventStoreBuilder::new().track_minutes(60);
        assert_eq!(builder.configs.len(), 1);
        assert_eq!(builder.configs[0].bucket_count(), 60);
        assert_eq!(builder.configs[0].time_unit(), TimeUnit::Minutes);
    }

    #[test]
    fn test_track_hours() {
        let builder = EventStoreBuilder::new().track_hours(72);
        assert_eq!(builder.configs.len(), 1);
        assert_eq!(builder.configs[0].bucket_count(), 72);
        assert_eq!(builder.configs[0].time_unit(), TimeUnit::Hours);
    }

    #[test]
    fn test_track_days() {
        let builder = EventStoreBuilder::new().track_days(56);
        assert_eq!(builder.configs.len(), 1);
        assert_eq!(builder.configs[0].bucket_count(), 56);
        assert_eq!(builder.configs[0].time_unit(), TimeUnit::Days);
    }

    #[test]
    fn test_track_weeks() {
        let builder = EventStoreBuilder::new().track_weeks(52);
        assert_eq!(builder.configs.len(), 1);
        assert_eq!(builder.configs[0].bucket_count(), 52);
        assert_eq!(builder.configs[0].time_unit(), TimeUnit::Weeks);
    }

    #[test]
    fn test_track_months() {
        let builder = EventStoreBuilder::new().track_months(12);
        assert_eq!(builder.configs.len(), 1);
        assert_eq!(builder.configs[0].bucket_count(), 12);
        assert_eq!(builder.configs[0].time_unit(), TimeUnit::Months);
    }

    #[test]
    fn test_track_years() {
        let builder = EventStoreBuilder::new().track_years(4);
        assert_eq!(builder.configs.len(), 1);
        assert_eq!(builder.configs[0].bucket_count(), 4);
        assert_eq!(builder.configs[0].time_unit(), TimeUnit::Years);
    }

    #[test]
    fn test_for_rate_limiting_preset() {
        let builder = EventStoreBuilder::new().for_rate_limiting();
        assert_eq!(builder.configs.len(), 2);

        // 60 minutes
        assert_eq!(builder.configs[0].bucket_count(), 60);
        assert_eq!(builder.configs[0].time_unit(), TimeUnit::Minutes);

        // 72 hours
        assert_eq!(builder.configs[1].bucket_count(), 72);
        assert_eq!(builder.configs[1].time_unit(), TimeUnit::Hours);
    }

    #[test]
    fn test_for_analytics_preset() {
        let builder = EventStoreBuilder::new().for_analytics();
        assert_eq!(builder.configs.len(), 3);

        // 56 days
        assert_eq!(builder.configs[0].bucket_count(), 56);
        assert_eq!(builder.configs[0].time_unit(), TimeUnit::Days);

        // 52 weeks
        assert_eq!(builder.configs[1].bucket_count(), 52);
        assert_eq!(builder.configs[1].time_unit(), TimeUnit::Weeks);

        // 12 months
        assert_eq!(builder.configs[2].bucket_count(), 12);
        assert_eq!(builder.configs[2].time_unit(), TimeUnit::Months);
    }

    #[test]
    fn test_build_default() {
        let store = EventStoreBuilder::new().build().unwrap();

        // Default configuration has 6 time units
        let intervals = store.tracked_intervals();
        assert_eq!(intervals.len(), 6);

        // Verify default configuration
        assert!(intervals.contains(&(TimeUnit::Minutes, 60)));
        assert!(intervals.contains(&(TimeUnit::Hours, 72)));
        assert!(intervals.contains(&(TimeUnit::Days, 56)));
        assert!(intervals.contains(&(TimeUnit::Weeks, 52)));
        assert!(intervals.contains(&(TimeUnit::Months, 12)));
        assert!(intervals.contains(&(TimeUnit::Years, 4)));
    }

    #[test]
    fn test_build_with_custom_config() {
        let store = EventStoreBuilder::new()
            .track_minutes(30)
            .track_hours(24)
            .build()
            .unwrap();

        let intervals = store.tracked_intervals();
        assert_eq!(intervals.len(), 2);
        assert!(intervals.contains(&(TimeUnit::Minutes, 30)));
        assert!(intervals.contains(&(TimeUnit::Hours, 24)));
    }

    #[test]
    fn test_build_with_rate_limiting_preset() {
        let store = EventStoreBuilder::new()
            .for_rate_limiting()
            .build()
            .unwrap();

        let intervals = store.tracked_intervals();
        assert_eq!(intervals.len(), 2);
        assert!(intervals.contains(&(TimeUnit::Minutes, 60)));
        assert!(intervals.contains(&(TimeUnit::Hours, 72)));
    }

    #[test]
    fn test_build_with_analytics_preset() {
        let store = EventStoreBuilder::new().for_analytics().build().unwrap();

        let intervals = store.tracked_intervals();
        assert_eq!(intervals.len(), 3);
        assert!(intervals.contains(&(TimeUnit::Days, 56)));
        assert!(intervals.contains(&(TimeUnit::Weeks, 52)));
        assert!(intervals.contains(&(TimeUnit::Months, 12)));
    }

    #[test]
    fn test_build_with_clock() {
        let test_clock = TestClock::new();
        let _expected_time = test_clock.now();

        let store = EventStoreBuilder::new()
            .with_clock(test_clock)
            .build()
            .unwrap();

        // Verify the clock is used (indirectly by checking that store works)
        store.record("test");
        assert_eq!(store.query("test").last_days(1).sum(), Some(1));
    }

    #[test]
    #[cfg(any(feature = "serde-bincode", feature = "serde-json"))]
    fn test_build_with_storage() {
        let storage = MemoryStorage::new();
        let store = EventStoreBuilder::new()
            .with_storage(storage)
            .build()
            .unwrap();

        // Storage is configured, so we should be able to persist
        // We can't directly check storage, but we can verify the store was built
        assert_eq!(store.tracked_intervals().len(), 6);
    }

    #[test]
    #[cfg(any(feature = "serde-bincode", feature = "serde-json"))]
    fn test_build_with_all_options() {
        let test_clock = TestClock::new();
        let storage = MemoryStorage::new();

        let store = EventStoreBuilder::new()
            .with_clock(test_clock)
            .with_storage(storage)
            .track_minutes(120)
            .track_hours(48)
            .build()
            .unwrap();

        let intervals = store.tracked_intervals();
        assert_eq!(intervals.len(), 2);
        assert!(intervals.contains(&(TimeUnit::Minutes, 120)));
        assert!(intervals.contains(&(TimeUnit::Hours, 48)));
    }

    #[test]
    fn test_event_store_builder_method() {
        let builder = EventStore::builder();
        assert!(builder.clock.is_none());
        assert!(builder.storage.is_none());
        assert_eq!(builder.configs.len(), 0);
    }

    #[test]
    fn test_builder_fluent_api() {
        // Test chaining multiple methods
        let store = EventStore::builder()
            .track_minutes(60)
            .track_hours(24)
            .track_days(7)
            .build()
            .unwrap();

        let intervals = store.tracked_intervals();
        assert_eq!(intervals.len(), 3);
    }

    #[test]
    fn test_preset_overwrites_previous_config() {
        // If you call a preset after setting custom intervals, it should replace them
        let builder = EventStoreBuilder::new()
            .track_minutes(30)
            .track_hours(12)
            .for_rate_limiting();

        // Should have rate limiting config, not the custom one
        assert_eq!(builder.configs.len(), 2);
        assert_eq!(builder.configs[0].bucket_count(), 60);
        assert_eq!(builder.configs[1].bucket_count(), 72);
    }

    #[test]
    fn test_custom_config_after_preset() {
        // You can add custom intervals after a preset
        let builder = EventStoreBuilder::new().for_rate_limiting().track_days(30);

        // Should have rate limiting + days
        assert_eq!(builder.configs.len(), 3);
        assert_eq!(builder.configs[0].time_unit(), TimeUnit::Minutes);
        assert_eq!(builder.configs[1].time_unit(), TimeUnit::Hours);
        assert_eq!(builder.configs[2].time_unit(), TimeUnit::Days);
    }

    // Validation tests for track_* methods
    #[test]
    fn test_track_minutes_rejects_zero() {
        let result = EventStoreBuilder::new().track_minutes(0).build();
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(e.to_string().contains("bucket count"));
        }
    }

    #[test]
    fn test_track_minutes_rejects_too_large() {
        let result = EventStoreBuilder::new().track_minutes(100_001).build();
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(e.to_string().contains("bucket count"));
        }
    }

    #[test]
    fn test_track_hours_rejects_zero() {
        let result = EventStoreBuilder::new().track_hours(0).build();
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(e.to_string().contains("bucket count"));
        }
    }

    #[test]
    fn test_track_hours_rejects_too_large() {
        let result = EventStoreBuilder::new().track_hours(100_001).build();
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(e.to_string().contains("bucket count"));
        }
    }

    #[test]
    fn test_track_days_rejects_zero() {
        let result = EventStoreBuilder::new().track_days(0).build();
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(e.to_string().contains("bucket count"));
        }
    }

    #[test]
    fn test_track_days_rejects_too_large() {
        let result = EventStoreBuilder::new().track_days(100_001).build();
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(e.to_string().contains("bucket count"));
        }
    }

    #[test]
    fn test_track_weeks_rejects_zero() {
        let result = EventStoreBuilder::new().track_weeks(0).build();
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(e.to_string().contains("bucket count"));
        }
    }

    #[test]
    fn test_track_weeks_rejects_too_large() {
        let result = EventStoreBuilder::new().track_weeks(100_001).build();
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(e.to_string().contains("bucket count"));
        }
    }

    #[test]
    fn test_track_months_rejects_zero() {
        let result = EventStoreBuilder::new().track_months(0).build();
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(e.to_string().contains("bucket count"));
        }
    }

    #[test]
    fn test_track_months_rejects_too_large() {
        let result = EventStoreBuilder::new().track_months(100_001).build();
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(e.to_string().contains("bucket count"));
        }
    }

    #[test]
    fn test_track_years_rejects_zero() {
        let result = EventStoreBuilder::new().track_years(0).build();
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(e.to_string().contains("bucket count"));
        }
    }

    #[test]
    fn test_track_years_rejects_too_large() {
        let result = EventStoreBuilder::new().track_years(100_001).build();
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(e.to_string().contains("bucket count"));
        }
    }

    #[test]
    fn test_track_minutes_accepts_valid_values() {
        let result = EventStoreBuilder::new().track_minutes(1).build();
        assert!(result.is_ok());

        let result = EventStoreBuilder::new().track_minutes(100_000).build();
        assert!(result.is_ok());
    }

    #[test]
    fn test_track_hours_accepts_valid_values() {
        let result = EventStoreBuilder::new().track_hours(1).build();
        assert!(result.is_ok());

        let result = EventStoreBuilder::new().track_hours(100_000).build();
        assert!(result.is_ok());
    }

    #[cfg(feature = "tokio")]
    #[test]
    fn test_auto_persist_method_exists() {
        use chrono::Duration;

        let builder = EventStoreBuilder::new().auto_persist(Duration::seconds(60));

        assert!(builder.auto_persist_interval.is_some());
        assert_eq!(
            builder.auto_persist_interval.unwrap(),
            Duration::seconds(60)
        );
    }

    // New tests for unified build() API
    #[cfg(all(feature = "tokio", feature = "serde"))]
    #[tokio::test]
    async fn test_unified_build_without_auto_persist() {
        let store = EventStoreBuilder::new()
            .with_storage(MemoryStorage::new())
            .build()
            .unwrap();

        // Should work normally
        store.record("test");
        assert_eq!(store.query("test").last_days(1).sum(), Some(1));
    }

    #[cfg(all(feature = "tokio", feature = "serde"))]
    #[tokio::test]
    async fn test_unified_build_with_auto_persist() {
        use chrono::Duration;

        let store = EventStoreBuilder::new()
            .with_storage(MemoryStorage::new())
            .auto_persist(Duration::milliseconds(50))
            .build()
            .unwrap();

        // Should work the same - API is unified
        store.record("test");
        assert_eq!(store.query("test").last_days(1).sum(), Some(1));

        // Wait for auto-persist
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        assert!(!store.is_dirty());
    }

    #[cfg(all(feature = "tokio", feature = "serde"))]
    #[tokio::test]
    async fn test_unified_build_auto_persist_no_locking_needed() {
        use chrono::Duration;

        let store = EventStoreBuilder::new()
            .with_storage(MemoryStorage::new())
            .auto_persist(Duration::milliseconds(50))
            .build()
            .unwrap();

        // Record directly - no .lock() calls needed
        store.record("event1");
        store.record("event2");
        store.record("event3");

        // Query directly - no .lock() calls needed
        assert_eq!(store.query("event1").last_days(1).sum(), Some(1));
        assert_eq!(store.query("event2").last_days(1).sum(), Some(1));
        assert_eq!(store.query("event3").last_days(1).sum(), Some(1));
    }

    // Formatter tests
    #[cfg(feature = "serde-bincode")]
    #[test]
    fn test_with_format_bincode() {
        use crate::formatter::BincodeFormat;

        let builder = EventStoreBuilder::new()
            .with_storage(MemoryStorage::new())
            .with_format(BincodeFormat);

        assert!(builder.formatter.is_some());
    }

    #[cfg(feature = "serde-json")]
    #[test]
    fn test_with_format_json() {
        use crate::formatter::JsonFormat;

        let builder = EventStoreBuilder::new()
            .with_storage(MemoryStorage::new())
            .with_format(JsonFormat);

        assert!(builder.formatter.is_some());
    }

    #[cfg(feature = "serde-bincode")]
    #[test]
    fn test_default_formatter_is_bincode() {
        let store = EventStoreBuilder::new()
            .with_storage(MemoryStorage::new())
            .build()
            .unwrap();

        // Verify store works (uses bincode by default)
        store.record("test");
        assert_eq!(store.query("test").last_days(1).sum(), Some(1));
    }

    #[cfg(all(feature = "serde-bincode", feature = "serde"))]
    #[test]
    fn test_formatter_used_in_persistence() {
        use crate::formatter::BincodeFormat;

        let store = EventStoreBuilder::new()
            .with_storage(MemoryStorage::new())
            .with_format(BincodeFormat)
            .build()
            .unwrap();

        store.record("event1");
        store.record("event2");

        // Should persist successfully
        let result = store.persist();
        assert!(result.is_ok());
    }

    #[cfg(all(feature = "serde-json", feature = "serde"))]
    #[test]
    fn test_json_formatter_used_in_persistence() {
        use crate::formatter::JsonFormat;

        let store = EventStoreBuilder::new()
            .with_storage(MemoryStorage::new())
            .with_format(JsonFormat)
            .build()
            .unwrap();

        store.record("event1");
        store.record("event2");

        // Should persist successfully with JSON format
        let result = store.persist();
        assert!(result.is_ok());
    }

    #[test]
    #[cfg(feature = "tokio")]
    fn test_auto_persist_negative_interval_fails() {
        use chrono::Duration;

        let result = EventStoreBuilder::new()
            .with_storage(MemoryStorage::new())
            .auto_persist(Duration::seconds(-60))
            .build();

        assert!(result.is_err());
        match result {
            Err(crate::error::Error::InvalidAutoPersistInterval(d)) => {
                assert_eq!(d.num_seconds(), -60);
            }
            _ => panic!("Expected InvalidAutoPersistInterval error"),
        }
    }

    #[test]
    #[cfg(feature = "tokio")]
    fn test_auto_persist_zero_interval_fails() {
        use chrono::Duration;

        let result = EventStoreBuilder::new()
            .with_storage(MemoryStorage::new())
            .auto_persist(Duration::zero())
            .build();

        assert!(result.is_err());
        match result {
            Err(crate::error::Error::InvalidAutoPersistInterval(d)) => {
                assert!(d.num_milliseconds() <= 0);
            }
            _ => panic!("Expected InvalidAutoPersistInterval error"),
        }
    }
}