Skip to content

Commit cfe1e8e

Browse files
committed
Operate sensibly if the timing of requests isn't monotonic
1 parent 9262c9e commit cfe1e8e

File tree

1 file changed

+24
-3
lines changed

1 file changed

+24
-3
lines changed

src/stats/mod.rs

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -89,9 +89,20 @@ impl<W: Write + Send + 'static> AggregatedStats<W> {
8989
fn maybe_update_counter<'a>(&'a self, now: DateTime<Utc>, guard: &'a impl Guard) -> &'a Counts {
9090
let now = mk_num(now);
9191

92-
let prev_day = self.today.swap(now, Ordering::Relaxed);
92+
let mut prev_day = self.today.load(Ordering::Relaxed);
93+
94+
// If our "now" time is in the past (perhaps tasks got out of order or something), we want to count this redirect towards the most recent day rather than getting rid of the newest day and replacing it with data intended for the oldest day.
95+
96+
while prev_day < now {
97+
match self.today.compare_exchange(prev_day, now, Ordering::Relaxed, Ordering::Relaxed) {
98+
Ok(_) => break,
99+
Err(new_prev_day) => {
100+
prev_day = new_prev_day;
101+
},
102+
}
103+
}
93104

94-
if prev_day != now {
105+
if prev_day < now {
95106
let new_counter: *mut Counts = Box::into_raw(Box::new(HashMap::new()));
96107

97108
// We need this guard to go into our task so it needs to be owned
@@ -340,10 +351,20 @@ mod tests {
340351
0,b.com,homepage.com,a.com,1
341352
0,homepage.com,c.com,a.com,1
342353
"}).await;
354+
stats.redirected_impl(a("0.0.0.0"), i("b.com"), i("c.com"), t(4));
343355
stats.redirected_impl(a("0.0.0.0"), i("c.com"), i("a.com"), t(2) + day);
344356

345357
assert_eq!(stats.aggregated.counter(&guard).len(), 2);
346-
stats.assert_stat_entry(("b.com", "c.com", "b.com"), 1);
358+
stats.assert_stat_entry(("b.com", "c.com", "b.com"), 2);
359+
stats.assert_stat_entry(("c.com", "a.com", "b.com"), 1);
360+
361+
stats.redirected_impl(a("0.0.0.0"), i("c.com"), i("a.com"), t(2) + day + day);
362+
assert_same_data(&mut rx, indoc! {"
363+
1,b.com,c.com,b.com,2
364+
1,c.com,a.com,b.com,1
365+
"}).await;
366+
367+
assert_eq!(stats.aggregated.counter(&guard).len(), 1);
347368
stats.assert_stat_entry(("c.com", "a.com", "b.com"), 1);
348369
}
349370
}

0 commit comments

Comments
 (0)