From 622677e2e398a33c0b705f67e212632b083b3249 Mon Sep 17 00:00:00 2001 From: David Herberth Date: Thu, 29 Feb 2024 13:42:14 +0100 Subject: [PATCH] fix(accumulator): Allow zero duration granularity --- src/accumulator.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/accumulator.rs b/src/accumulator.rs index dc22fad..30453a1 100644 --- a/src/accumulator.rs +++ b/src/accumulator.rs @@ -51,8 +51,11 @@ impl UsageAccumulator { amount: u64, usage_unit: UsageUnit, ) { - let quantized_timestamp: DateTime = - usage_time.duration_trunc(self.granularity).unwrap(); + let quantized_timestamp = if self.granularity.is_zero() { + usage_time + } else { + usage_time.duration_trunc(self.granularity).unwrap() + }; if self.first_timestamp.is_none() { self.first_timestamp = Some(quantized_timestamp); @@ -75,9 +78,12 @@ impl UsageAccumulator { /// and at least `granularity` seconds have passed since /// the first chunk of data was added. pub fn should_flush(&self, current_time: DateTime) -> bool { - return self.first_timestamp.is_some() - && self.usage_batch.keys().len() > 0 - && current_time - self.first_timestamp.unwrap() > self.granularity; + let Some(first_timestamp) = self.first_timestamp else { + return false; + }; + + return self.usage_batch.keys().len() > 0 + && current_time - first_timestamp >= self.granularity; } /// Return the current bucket and clears up the state.