Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 40 additions & 3 deletions crates/price-estimation/src/native_price_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,9 +197,16 @@ impl Cache {
/// in the past, to avoid spikes of expired prices all being fetched at
/// once.
fn random_updated_at(max_age: Duration, now: Instant, rng: &mut impl Rng) -> Instant {
let percent_expired = rng.random_range(50..=90);
let age = max_age.as_secs() * percent_expired / 100;
now - Duration::from_secs(age)
let percent_expired: u32 = rng.random_range(50..=90);

let age = max_age
.checked_mul(percent_expired)
.map(|age| age / 100)
.unwrap_or(Duration::MAX);
Comment on lines +202 to +205
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use saturating_mul instead


now.checked_sub(age)
.or_else(|| now.checked_sub(Duration::from_secs(1)))
.unwrap_or(now)
Comment on lines +207 to +209
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use saturating_sub instead

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not available for an Instant.

}

fn len(&self) -> usize {
Expand Down Expand Up @@ -1143,4 +1150,34 @@ mod tests {
anyhow!("protocol")
))));
}

#[test]
fn random_updated_at_underflow_check() {
let now = Instant::now();
let max_age = Duration::MAX;
let mut rng = rand::rng();
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

seed the rng for determinism


let updated_at = Cache::random_updated_at(max_age, now, &mut rng);

assert!(updated_at < now);
assert!(updated_at >= now - Duration::from_secs(1));
}

#[test]
fn random_updated_at_range() {
let now = Instant::now();
let max_age = Duration::from_secs(600);
let mut rng = rand::rng();

for _ in 0..100 {
let updated_at = Cache::random_updated_at(max_age, now, &mut rng);

let min_age = max_age * 50 / 100;
let max_age_check = max_age * 90 / 100;

assert!(updated_at < now);
assert!(updated_at <= now - min_age);
assert!(updated_at >= now - max_age_check);
}
}
}
Loading