Skip to main content

ag_runtime/
provider_call_budget.rs

1//! Shared accounting for provider turns, including transport and protocol
2//! retries.
3
4use std::sync::Arc;
5use std::sync::atomic::{AtomicUsize, Ordering};
6
7use crate::OneShotError;
8
9/// A shared limit on underlying provider turns across cloned requests.
10///
11/// Transports must consume one slot immediately before each provider attempt,
12/// including repairs and restart retries. Failed attempts also consume a slot.
13#[derive(Clone, Debug)]
14pub struct ProviderCallBudget {
15    remaining: Arc<AtomicUsize>,
16}
17
18impl ProviderCallBudget {
19    /// Creates a budget shared by all clones.
20    pub fn new(limit: usize) -> Self {
21        Self {
22            remaining: Arc::new(AtomicUsize::new(limit)),
23        }
24    }
25
26    /// Checks for exhaustion without charging a turn at an outer boundary.
27    ///
28    /// # Errors
29    /// Returns an input-size reduction error when no slots remain.
30    pub fn ensure_available(&self) -> Result<(), OneShotError> {
31        if self.remaining.load(Ordering::Relaxed) == 0 {
32            return Err(Self::exhausted());
33        }
34
35        Ok(())
36    }
37
38    /// Charges one underlying provider attempt atomically.
39    ///
40    /// # Errors
41    /// Returns an input-size reduction error before execution when exhausted.
42    pub fn consume(&self) -> Result<(), OneShotError> {
43        self.remaining
44            .try_update(Ordering::Relaxed, Ordering::Relaxed, |remaining| {
45                remaining.checked_sub(1)
46            })
47            .map(|_| ())
48            .map_err(|_| Self::exhausted())
49    }
50
51    /// Keep exhaustion terminal for commit assistance as well as transport
52    /// retries.
53    fn exhausted() -> OneShotError {
54        OneShotError::new(
55            "Input exceeds the maximum length reduction budget: provider call limit reached; \
56             changes are preserved",
57        )
58    }
59}