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
//! Single time-unit counter with automatic rotation.
//!
//! IntervalCounter stores only time_unit and derives bucket_count from data.len().
//!
//! IntervalConfig is reconstructed on-demand via to_interval_config() for:
//! - Serialization (SerializableSingleEventCounter)
//! - Conversion (config_converter)
//! - Merge operations (SingleEventCounter::merge)
//!
//! This eliminates ~90 bytes of duplicated config per SingleEventCounter.

pub mod config;

use chrono::{DateTime, Utc};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use crate::{CountRing, Result, TimeUnit};

/// A counter that tracks events within a single time unit granularity.
///
/// IntervalCounter maintains a rotating bucket storage (CountRing) and automatically
/// advances time by rotating buckets when the current time moves forward.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub(crate) struct IntervalCounter {
    data: CountRing,
    // This is the beginning of the zeroth bucket. It _will_ be in the past.
    // e.g. if the time_unit is Hours, interval_start is at the top of the hour that we're currently in.
    // e.g. if the time_unit is Days, interval_start will be the previous midnight.
    // e.g. if the time_unit is Years, interval_start will be midnight of the last Jan 1.
    interval_start: DateTime<Utc>,
}

impl IntervalCounter {
    /// Creates a new IntervalCounter with the specified bucket count.
    ///
    /// All buckets start at zero. The starting_instant marks the beginning of
    /// the current time interval (bucket 0).
    pub(crate) fn new(bucket_count: usize, starting_instant: DateTime<Utc>) -> Self {
        Self {
            data: CountRing::new(bucket_count),
            interval_start: starting_instant,
        }
    }

    /// Returns the number of buckets in this counter.
    pub(crate) fn bucket_count(&self) -> usize {
        self.data.len()
    }

    /// Records an event that occurred at a specific time.
    ///
    /// This method:
    /// 1. Calculates which bucket the event belongs in based on 'time'
    /// 2. Increments that bucket
    ///
    /// Returns Error::FutureEvent if the event time is after starting_instant.
    pub(crate) fn increment_at(
        &mut self,
        count: u32,
        time: DateTime<Utc>,
        time_unit: &TimeUnit,
    ) -> Result<()> {
        let bucket_idx = time_unit.bucket_idx(self.interval_start, time)?;

        // Increment the bucket
        self.data.increment(bucket_idx, count);
        Ok(())
    }

    /// Advances time if needed by rotating buckets.
    ///
    /// Calculates how many rotations have occurred since interval_start and
    /// updates both the bucket ring and interval_start accordingly.
    ///
    /// This operation is idempotent: calling it multiple times with the same
    /// 'now' has the same effect as calling it once.
    pub(crate) fn advance_if_needed(&mut self, time_unit: &TimeUnit, now: DateTime<Utc>) {
        // Calculate rotations from interval_start to now
        let rotations = time_unit.num_rotations(self.interval_start, now);

        if rotations > 0 {
            // Rotate the buckets
            self.data.rotate(rotations as usize);

            // Update starting_instant forward
            self.interval_start = time_unit.rotate_start_interval(self.interval_start, rotations);
        }
        // If rotations == 0: no-op (already current)
        // If rotations < 0: impossible (now can't be before starting_instant in normal usage)
    }

    /// Queries the sum of counts in the specified range of buckets.
    ///
    /// Delegates to the underlying CountRing's sum_range method.
    pub(crate) fn sum_range(&self, start: usize, end: usize) -> u32 {
        self.data.sum_range(start, end)
    }

    pub(crate) fn increment_bucket(&mut self, idx: usize, count: u32) {
        self.data.increment(idx, count)
    }

    pub(crate) fn merge(&mut self, other: &IntervalCounter) {
        // Loop over all buckets in other_counter (it may have more buckets than self)
        for i in 0..other.bucket_count() {
            if let Some(other_value) = other.data.get(i) {
                self.data.increment(i, other_value);
            }
        }
    }

    /// Returns the current interval start.
    ///
    /// This is the timestamp marking the beginning of bucket 0.
    #[allow(dead_code)]
    pub(crate) fn interval_start(&self) -> DateTime<Utc> {
        self.interval_start
    }

    pub(crate) fn bucket_value(&self, bucket_idx: usize) -> Option<u32> {
        self.data.get(bucket_idx)
    }

    #[allow(dead_code)]
    pub(crate) fn into_buckets(self) -> Vec<u32> {
        self.data.into_buckets()
    }

    #[cfg(test)]
    pub(crate) fn non_zero_idx(&self) -> Vec<usize> {
        (0..self.bucket_count())
            .filter(|idx| self.bucket_value(*idx).unwrap_or_default() > 0)
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use chrono::{Duration, TimeZone};

    use super::*;

    use crate::{Error, TimeUnit};

    #[test]
    fn test_new_creates_counter_with_zero_buckets() {
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let counter = IntervalCounter::new(10, start);

        assert_eq!(counter.bucket_count(), 10); // Buckets are eagerly allocated
        assert_eq!(counter.interval_start(), start);
        // All buckets should be zero
        for i in 0..10 {
            assert_eq!(counter.bucket_value(i), Some(0));
        }
    }

    #[test]
    fn test_increment_adds_to_bucket_0() {
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let mut counter = IntervalCounter::new(10, start);

        counter.increment_bucket(0, 5);
        assert_eq!(counter.sum_range(0, 1), 5);

        counter.increment_bucket(0, 3);
        assert_eq!(counter.sum_range(0, 1), 8);
    }

    #[test]
    fn test_advance_if_needed_with_no_time_jump() {
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let mut counter = IntervalCounter::new(10, start);

        counter.increment_bucket(0, 5);

        // Advance with same time (no rotation)
        counter.advance_if_needed(&TimeUnit::Days, start);

        assert_eq!(counter.interval_start(), start);
        assert_eq!(counter.sum_range(0, 1), 5);
    }

    #[test]
    fn test_advance_if_needed_with_small_time_jump() {
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 10, 0, 0).unwrap();
        let mut counter = IntervalCounter::new(10, start);

        counter.increment_bucket(0, 5);

        // Advance by 1 hour
        let now = start + Duration::hours(1);
        counter.advance_if_needed(&TimeUnit::Hours, now);

        assert_eq!(counter.interval_start(), now);
        // Old data should have shifted to bucket 1
        assert_eq!(counter.sum_range(0, 1), 0); // Bucket 0 is new (zero)
        assert_eq!(counter.sum_range(1, 2), 5); // Bucket 1 has old data
    }

    #[test]
    fn test_advance_if_needed_with_large_time_jump() {
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let mut counter = IntervalCounter::new(10, start);

        counter.increment_bucket(0, 5);

        // Advance by 100 days (beyond bucket_count)
        let now = start + Duration::days(100);
        counter.advance_if_needed(&TimeUnit::Days, now);

        // All old data should be rotated out
        assert_eq!(counter.sum_range(0, 10), 0);
    }

    #[test]
    fn test_increment_at_with_past_event_2_days_ago() {
        let time_unit = TimeUnit::Days;
        let start = Utc.with_ymd_and_hms(2025, 1, 10, 0, 0, 0).unwrap();
        let mut counter = IntervalCounter::new(10, start);

        let event_time = start - Duration::days(2);

        counter.increment_at(5, event_time, &time_unit).unwrap();

        // Event 2 days ago should be in bucket 2 (0=current, 1=same interval before instant, 2=2 days ago)
        assert_eq!(counter.sum_range(2, 3), 5);
    }

    #[test]
    fn test_increment_at_with_past_event_1_hour_ago() {
        let time_unit = TimeUnit::Minutes;
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 10, 0, 0).unwrap();
        let mut counter = IntervalCounter::new(60, start);

        let event_time = start - Duration::minutes(30);

        counter.increment_at(10, event_time, &time_unit).unwrap();

        // 30 minutes ago = 30 rotations = bucket 30 (0=current, 1=same interval before, 2-30=past)
        assert_eq!(counter.sum_range(30, 31), 10);
    }

    #[test]
    fn test_increment_at_with_future_event_returns_error() {
        let time_unit = TimeUnit::Days;
        let start = Utc.with_ymd_and_hms(2025, 1, 10, 0, 0, 0).unwrap();
        let mut counter = IntervalCounter::new(10, start);

        let future_time = start + Duration::days(5);

        let result = counter.increment_at(5, future_time, &time_unit);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), Error::FutureEvent));
    }

    #[test]
    fn test_increment_at_same_interval_after_starting_instant() {
        let time_unit = TimeUnit::Hours;
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 10, 0, 0).unwrap();
        let mut counter = IntervalCounter::new(10, start);

        // Event 30 minutes after start (same hour, after instant)
        let event_time = start + Duration::minutes(30);

        counter.increment_at(5, event_time, &time_unit).unwrap();

        // Should go to bucket 0 (current interval, after instant)
        assert_eq!(counter.sum_range(0, 1), 5);
    }

    #[test]
    fn test_increment_at_same_interval_before_starting_instant() {
        let time_unit = TimeUnit::Hours;
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 10, 30, 0).unwrap();
        let mut counter = IntervalCounter::new(10, start);

        // Event at 10:15 (same hour as 10:30, but before instant)
        let event_time = Utc.with_ymd_and_hms(2025, 1, 1, 10, 15, 0).unwrap();

        counter.increment_at(5, event_time, &time_unit).unwrap();

        // Should go to bucket 1 (current interval, before instant)
        assert_eq!(counter.sum_range(1, 2), 5);
    }

    #[test]
    fn test_query_range_delegates_correctly() {
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let mut counter = IntervalCounter::new(10, start);

        // Add data to multiple buckets
        counter.increment_bucket(0, 10);
        counter.increment_bucket(1, 20);
        counter.increment_bucket(2, 30);

        assert_eq!(counter.sum_range(0, 1), 10);
        assert_eq!(counter.sum_range(1, 3), 50);
        assert_eq!(counter.sum_range(0, 3), 60);
    }

    // Property test: starting_instant only moves forward
    #[test]
    fn test_property_starting_instant_monotonic() {
        let time_unit = TimeUnit::Days;
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let mut counter = IntervalCounter::new(10, start);

        let instant1 = counter.interval_start();

        // Advance time forward
        let now = start + Duration::days(5);
        counter.advance_if_needed(&time_unit, now);

        let instant2 = counter.interval_start();
        assert!(instant2 >= instant1);

        // Advance again
        let now2 = now + Duration::days(3);
        counter.advance_if_needed(&time_unit, now2);

        let instant3 = counter.interval_start();
        assert!(instant3 >= instant2);
    }

    // Property test: advance_if_needed is idempotent
    #[test]
    fn test_property_advance_idempotent() {
        let time_unit = TimeUnit::Days;
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let mut counter = IntervalCounter::new(10, start);

        counter.increment_bucket(0, 5);

        let now = start + Duration::days(3);

        // Advance once
        counter.advance_if_needed(&time_unit, now);
        let instant_after_first = counter.interval_start();
        let sum_after_first = counter.sum_range(0, 10);

        // Advance again with same time
        counter.advance_if_needed(&time_unit, now);
        let instant_after_second = counter.interval_start();
        let sum_after_second = counter.sum_range(0, 10);

        // Should be identical
        assert_eq!(instant_after_first, instant_after_second);
        assert_eq!(sum_after_first, sum_after_second);
    }

    // Property test: increment_at then query_range retrieves the count
    #[test]
    fn test_property_increment_at_then_query() {
        let time_unit = TimeUnit::Hours;
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let mut counter = IntervalCounter::new(10, start);

        // Record events at various times
        let events = [
            (start - Duration::hours(1), 10u32),
            (start - Duration::hours(3), 20u32),
            (start - Duration::hours(5), 30u32),
        ];

        for (time, count) in events.iter() {
            counter.increment_at(*count, *time, &time_unit).unwrap();
        }

        // Query sum of all events
        let total = counter.sum_range(0, 20);
        assert_eq!(total, 60); // 10 + 20 + 30
    }

    #[test]
    fn test_complex_workflow_with_time_advancement() {
        let time_unit = TimeUnit::Days;
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let mut counter = IntervalCounter::new(7, start);

        // Day 1: Record some events
        counter.increment_bucket(0, 5);
        assert_eq!(counter.sum_range(0, 1), 5);

        // Day 2: Advance and record more
        let now = start + Duration::days(1);
        counter.advance_if_needed(&time_unit, now);
        counter.increment_bucket(0, 10);

        assert_eq!(counter.sum_range(0, 1), 10); // Today
        assert_eq!(counter.sum_range(1, 2), 5); // Yesterday
        assert_eq!(counter.sum_range(0, 2), 15); // Last 2 days

        // Day 5: Large jump
        let now = start + Duration::days(4);
        counter.advance_if_needed(&time_unit, now);
        counter.increment_bucket(0, 20);

        assert_eq!(counter.sum_range(0, 1), 20); // Today
        assert_eq!(counter.sum_range(4, 5), 5); // 4 days ago (day 1)
        assert_eq!(counter.sum_range(0, 7), 35); // All data still retained
    }
}