actionqueue_core/
budget.rs1#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
9#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
10pub enum BudgetDimension {
11 Token,
13 CostCents,
15 TimeSecs,
17}
18
19impl std::fmt::Display for BudgetDimension {
20 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21 let name = match self {
22 BudgetDimension::Token => "token",
23 BudgetDimension::CostCents => "cost_cents",
24 BudgetDimension::TimeSecs => "time_secs",
25 };
26 write!(f, "{name}")
27 }
28}
29
30#[derive(Debug, Clone, PartialEq, Eq)]
36#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
37pub struct BudgetConsumption {
38 pub dimension: BudgetDimension,
40 pub amount: u64,
42}
43
44impl BudgetConsumption {
45 pub fn new(dimension: BudgetDimension, amount: u64) -> Self {
47 Self { dimension, amount }
48 }
49}
50
51#[derive(Debug, Clone, PartialEq, Eq)]
56#[cfg_attr(feature = "serde", derive(serde::Serialize))]
57pub struct BudgetAllocation {
58 dimension: BudgetDimension,
59 limit: u64,
60}
61
62#[derive(Debug, Clone, PartialEq, Eq)]
64pub enum BudgetAllocationError {
65 ZeroLimit,
67}
68
69impl std::fmt::Display for BudgetAllocationError {
70 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71 match self {
72 BudgetAllocationError::ZeroLimit => write!(f, "budget limit must be greater than zero"),
73 }
74 }
75}
76
77impl std::error::Error for BudgetAllocationError {}
78
79impl BudgetAllocation {
80 pub fn new(dimension: BudgetDimension, limit: u64) -> Result<Self, BudgetAllocationError> {
86 if limit == 0 {
87 return Err(BudgetAllocationError::ZeroLimit);
88 }
89 Ok(Self { dimension, limit })
90 }
91
92 pub fn dimension(&self) -> BudgetDimension {
94 self.dimension
95 }
96
97 pub fn limit(&self) -> u64 {
99 self.limit
100 }
101}
102
103#[cfg(feature = "serde")]
104impl<'de> serde::Deserialize<'de> for BudgetAllocation {
105 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
106 where
107 D: serde::Deserializer<'de>,
108 {
109 #[derive(serde::Deserialize)]
110 struct Wire {
111 dimension: BudgetDimension,
112 limit: u64,
113 }
114
115 let wire = Wire::deserialize(deserializer)?;
116 BudgetAllocation::new(wire.dimension, wire.limit)
117 .map_err(|_| serde::de::Error::custom("budget limit must be greater than zero"))
118 }
119}