use crate::credits::{Credits, WholeCredits};
use crate::error::BudgetKind;
use crate::params::RequestParams;
use std::time::Duration;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Budget {
pub credits: Option<Credits>,
pub per_page_credits: Option<Credits>,
pub wall: Option<Duration>,
pub attempts: u8,
}
pub const DEFAULT_ATTEMPTS: u8 = 5;
pub const DEFAULT_WALL: Duration = Duration::from_secs(15 * 60);
pub const ASSUMED_MINIMUM_COST: Credits = Credits::new(0.1);
impl Default for Budget {
fn default() -> Budget {
Budget {
credits: None,
per_page_credits: None,
wall: Some(DEFAULT_WALL),
attempts: DEFAULT_ATTEMPTS,
}
}
}
impl Budget {
pub fn preflight(&self, made: u8, spent: Credits, estimate: Credits) -> Result<(), BudgetKind> {
self.allows_attempt(made)?;
self.allows_spend(spent, estimate)
}
pub fn unlimited() -> Budget {
Budget {
attempts: u8::MAX,
wall: None,
..Budget::default()
}
}
pub fn with_credits(mut self, credits: Credits) -> Budget {
self.credits = Some(credits);
self
}
pub fn with_per_page_credits(mut self, credits: Credits) -> Budget {
self.per_page_credits = Some(credits);
self
}
pub fn with_wall(mut self, wall: Duration) -> Budget {
self.wall = Some(wall);
self
}
pub fn without_wall(mut self) -> Budget {
self.wall = None;
self
}
pub fn with_attempts(mut self, attempts: u8) -> Budget {
self.attempts = attempts;
self
}
pub fn apply(&self, params: &mut RequestParams) {
if let Some(cap) = self.credits.map(WholeCredits::floor) {
params.max_credits_allowed = Some(
params
.max_credits_allowed
.map_or(cap, |old| WholeCredits::new(old.get().min(cap.get()))),
);
}
if let Some(cap) = self.per_page_credits {
params.max_credits_per_page = Some(
params
.max_credits_per_page
.map_or(cap, |old| Credits(old.get().min(cap.get()))),
);
}
}
pub fn remaining_credits(&self, spent: Credits) -> Option<Credits> {
self.credits
.map(|cap| Credits((cap.get() - spent.get()).max(0.0)))
}
pub fn remaining_wall(&self, elapsed: Duration) -> Option<Duration> {
self.wall.map(|cap| cap.saturating_sub(elapsed))
}
pub fn allows_attempt(&self, made: u8) -> Result<(), BudgetKind> {
if made >= self.attempts {
return Err(BudgetKind::Attempts);
}
Ok(())
}
pub fn floor(basis: Credits) -> Credits {
if basis.get() > 0.0 {
basis
} else {
ASSUMED_MINIMUM_COST
}
}
pub fn allows_spend(&self, spent: Credits, estimate: Credits) -> Result<(), BudgetKind> {
let estimate = Budget::floor(estimate);
if let Some(per_page) = self.per_page_credits {
if estimate.get() > per_page.get() {
return Err(BudgetKind::Credits);
}
}
if let Some(cap) = self.credits {
if spent.get() + estimate.get() > cap.get() {
return Err(BudgetKind::Credits);
}
}
Ok(())
}
pub fn allows_sleep(&self, elapsed: Duration, sleep: Duration) -> Result<(), BudgetKind> {
match self.wall {
Some(cap) if elapsed.saturating_add(sleep) >= cap => Err(BudgetKind::Time),
_ => Ok(()),
}
}
}
#[cfg(test)]
mod tests {
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::unreachable,
clippy::indexing_slicing,
clippy::string_slice
)]
use super::*;
use crate::credits::Usd;
use crate::response::costs::Costs;
#[test]
fn the_caps_are_copied_onto_the_request() {
let budget = Budget::default()
.with_credits(Credits(500.0))
.with_per_page_credits(Credits(50.0));
let mut params = RequestParams::url("https://example.com");
budget.apply(&mut params);
assert_eq!(params.max_credits_allowed, Some(WholeCredits::new(500)));
assert_eq!(params.max_credits_per_page, Some(Credits(50.0)));
}
#[test]
fn a_tighter_cap_set_by_hand_survives() {
let budget = Budget::default().with_credits(Credits(500.0));
let mut params = RequestParams::url("https://example.com");
params.max_credits_allowed = Some(WholeCredits::new(10));
budget.apply(&mut params);
assert_eq!(params.max_credits_allowed, Some(WholeCredits::new(10)));
}
#[test]
fn spend_is_refused_once_the_estimate_runs_past_the_cap() {
let budget = Budget::default().with_credits(Credits(100.0));
assert_eq!(budget.allows_spend(Credits(60.0), Credits(30.0)), Ok(()));
assert_eq!(
budget.allows_spend(Credits(60.0), Credits(50.0)),
Err(BudgetKind::Credits)
);
}
#[test]
fn the_per_page_cap_refuses_one_expensive_step_on_its_own() {
let budget = Budget::unlimited().with_per_page_credits(Credits(20.0));
assert_eq!(budget.allows_spend(Credits::ZERO, Credits(19.0)), Ok(()));
assert_eq!(
budget.allows_spend(Credits::ZERO, Credits(21.0)),
Err(BudgetKind::Credits)
);
}
#[test]
fn a_free_attempt_does_not_turn_the_cap_off() {
assert_eq!(Budget::floor(Credits::ZERO), ASSUMED_MINIMUM_COST);
assert_eq!(Budget::floor(Credits(4.0)), Credits(4.0));
let budget =
Budget::unlimited().with_per_page_credits(Credits(ASSUMED_MINIMUM_COST.get() / 2.0));
assert_eq!(
budget.allows_spend(Credits::ZERO, Credits::ZERO),
Err(BudgetKind::Credits)
);
}
#[test]
fn a_credit_cap_refuses_a_real_measured_spend_that_runs_past_it() {
let cheap = Costs {
total_cost: Usd::new(1.0870316666666668e-05),
..Costs::default()
}
.total();
assert!((cheap.get() - 0.108703).abs() < 1e-6, "{cheap}");
let page = Credits::from_usd(1.7282492833333333e-04);
let budget = Budget::default().with_credits(Credits(2.0));
assert_eq!(budget.allows_spend(Credits::ZERO, page), Ok(()));
assert_eq!(
budget.allows_spend(page, page),
Err(BudgetKind::Credits),
"two of these is more than the cap allows"
);
assert_eq!(
budget.allows_spend(Credits::ZERO, Credits(2.5)),
Err(BudgetKind::Credits)
);
assert_eq!(
budget.allows_spend(Credits::ZERO, Credits(1.7282492833333333e-04)),
Ok(())
);
}
#[test]
fn nothing_is_capped_when_nothing_was_capped() {
let budget = Budget::unlimited();
assert_eq!(budget.allows_spend(Credits(1e9), Credits(1e9)), Ok(()));
assert_eq!(budget.remaining_credits(Credits(5.0)), None);
assert_eq!(budget.remaining_wall(Duration::from_secs(5)), None);
assert_eq!(
budget.allows_sleep(Duration::from_secs(86_400), Duration::from_secs(86_400)),
Ok(())
);
}
#[test]
fn a_sleep_that_would_eat_the_clock_is_refused() {
let budget = Budget::default().with_wall(Duration::from_secs(10));
assert_eq!(
budget.allows_sleep(Duration::from_secs(2), Duration::from_secs(3)),
Ok(())
);
assert_eq!(
budget.allows_sleep(Duration::from_secs(8), Duration::from_secs(3)),
Err(BudgetKind::Time)
);
}
#[test]
fn the_attempt_count_runs_out() {
let budget = Budget::default().with_attempts(2);
assert_eq!(budget.allows_attempt(0), Ok(()));
assert_eq!(budget.allows_attempt(1), Ok(()));
assert_eq!(budget.allows_attempt(2), Err(BudgetKind::Attempts));
}
#[test]
fn remaining_never_goes_below_zero() {
let budget = Budget::default().with_credits(Credits(10.0));
assert_eq!(budget.remaining_credits(Credits(25.0)), Some(Credits::ZERO));
assert_eq!(
Budget::default()
.with_wall(Duration::from_secs(1))
.remaining_wall(Duration::from_secs(9)),
Some(Duration::ZERO)
);
}
}