1use std::fmt;
16use std::sync::atomic::fence;
17use std::sync::atomic::AtomicU64;
18use std::sync::atomic::AtomicUsize;
19use std::sync::atomic::Ordering;
20use std::sync::Arc;
21use std::sync::Mutex;
22use std::sync::MutexGuard;
23
24use smallvec::SmallVec;
25use std::time::Duration;
26use tokio::sync::futures::Notified;
27use tokio::sync::Notify;
28
29use super::clock::MonotonicClock;
30use super::clock::SystemMonotonicClock;
31use super::dynamic::DynamicBudgetKey;
32use super::dynamic::DynamicKeyRegistrationFailure;
33use super::dynamic::DynamicKeyRegistry;
34use super::limit::BudgetClass;
35use super::limit::BudgetDimension;
36use super::limit::BudgetLimit;
37use super::limit::FullPolicy;
38use super::limit::RateLimit;
39
40#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct BudgetSnapshot {
43 pub path: Arc<str>,
45 pub current_count: usize,
47 pub current_bytes: usize,
49 pub admitted_count: u64,
51 pub released_count: u64,
53 pub rejected_count: u64,
55 pub throttled_count: u64,
57 pub dropped_count: u64,
59 pub coalesced_count: u64,
61 pub closed_slow_consumer_count: u64,
63}
64
65#[derive(Debug, Clone, PartialEq, Eq)]
67pub struct BudgetRejection {
68 path: Arc<str>,
69 exhausted_path: Arc<str>,
70 reason: BudgetRejectionReason,
71 policy: FullPolicy,
72}
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum BudgetRejectionReason {
77 Capacity(BudgetDimension),
79 Closed,
81}
82
83impl BudgetRejection {
84 #[must_use]
85 pub fn path(&self) -> &str {
87 &self.path
88 }
89
90 #[must_use]
91 pub fn exhausted_path(&self) -> &str {
93 &self.exhausted_path
94 }
95
96 #[must_use]
97 pub const fn dimension(&self) -> Option<BudgetDimension> {
99 match self.reason {
100 BudgetRejectionReason::Capacity(dimension) => Some(dimension),
101 BudgetRejectionReason::Closed => None,
102 }
103 }
104
105 #[must_use]
107 pub const fn reason(&self) -> BudgetRejectionReason {
108 self.reason
109 }
110
111 #[must_use]
113 pub const fn is_closed(&self) -> bool {
114 matches!(self.reason, BudgetRejectionReason::Closed)
115 }
116
117 #[must_use]
118 pub const fn policy(&self) -> FullPolicy {
120 self.policy
121 }
122}
123
124#[derive(Debug, Clone, PartialEq, Eq)]
130pub enum PermitBudgetTransferStatus {
131 Rebound,
133 Unchanged,
135 Rejected(BudgetRejection),
137}
138
139pub struct ResourceBudgetTree {
141 root: ResourceBudget,
142}
143
144impl fmt::Debug for ResourceBudgetTree {
145 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
146 formatter
147 .debug_struct("ResourceBudgetTree")
148 .field("root", &self.root)
149 .finish()
150 }
151}
152
153impl ResourceBudgetTree {
154 pub fn new(name: impl Into<String>, limit: BudgetLimit) -> Result<Self, crate::RuntimeContractViolation> {
161 Self::with_clock(name, limit, Arc::new(SystemMonotonicClock::new()))
162 }
163
164 pub fn with_clock(
171 name: impl Into<String>,
172 limit: BudgetLimit,
173 clock: Arc<dyn MonotonicClock>,
174 ) -> Result<Self, crate::RuntimeContractViolation> {
175 let name = validated_name(name.into())?;
176 limit.validate(&name)?;
177 let admission_gates: Arc<[Arc<AdmissionGate>]> = Arc::from([]);
178 let capacity_notify = Arc::new(CapacitySignal::default());
179 let node = Arc::new(BudgetNode::new(
180 Arc::from(name.as_str()),
181 limit,
182 clock,
183 admission_gates.clone(),
184 Arc::clone(&capacity_notify),
185 true,
186 ));
187 Ok(Self {
188 root: ResourceBudget {
189 node: Arc::clone(&node),
190 chain: Arc::from([node]),
191 capacity_notify,
192 keys: DynamicKeyRegistry::new(),
193 admission_gates,
194 },
195 })
196 }
197
198 pub fn with_clock_and_key_capacity(
206 name: impl Into<String>,
207 limit: BudgetLimit,
208 clock: Arc<dyn MonotonicClock>,
209 max_entries: usize,
210 ) -> Result<Self, crate::RuntimeContractViolation> {
211 let mut tree = Self::with_clock(name, limit, clock)?;
212 tree.root.keys = DynamicKeyRegistry::with_max_entries(max_entries);
213 Ok(tree)
214 }
215
216 #[must_use]
217 pub fn root(&self) -> ResourceBudget {
219 self.root.clone()
220 }
221}
222
223#[derive(Clone)]
225pub struct ResourceBudget {
226 node: Arc<BudgetNode>,
227 chain: Arc<[Arc<BudgetNode>]>,
228 capacity_notify: Arc<CapacitySignal>,
229 keys: DynamicKeyRegistry,
230 admission_gates: Arc<[Arc<AdmissionGate>]>,
231}
232
233#[derive(Default)]
242pub(crate) struct CapacitySignal {
243 notify: Notify,
244 waiters: AtomicUsize,
245}
246
247impl CapacitySignal {
248 pub(crate) fn notified(&self) -> Notified<'_> {
250 self.notify.notified()
251 }
252
253 pub(crate) fn register_waiter(&self) -> CapacityWaiter<'_> {
258 self.waiters.fetch_add(1, Ordering::SeqCst);
259 fence(Ordering::SeqCst);
260 CapacityWaiter { signal: self }
261 }
262
263 fn signal(&self) {
265 fence(Ordering::SeqCst);
266 if self.waiters.load(Ordering::Acquire) != 0 {
267 self.notify.notify_waiters();
268 }
269 }
270
271 fn signal_closed(&self) {
273 self.notify.notify_waiters();
274 }
275}
276
277pub(crate) struct CapacityWaiter<'a> {
279 signal: &'a CapacitySignal,
280}
281
282impl Drop for CapacityWaiter<'_> {
283 fn drop(&mut self) {
284 self.signal.waiters.fetch_sub(1, Ordering::Release);
285 }
286}
287
288struct AdmissionGate {
289 path: Arc<str>,
290 closed: Mutex<bool>,
291}
292
293pub(super) struct BudgetAdmission<'a> {
297 budget: &'a ResourceBudget,
298 _guards: SmallVec<[MutexGuard<'a, bool>; 2]>,
299}
300
301impl BudgetAdmission<'_> {
302 pub(super) fn try_acquire(&self, bytes: usize, class: BudgetClass) -> Result<ResourcePermit, BudgetRejection> {
303 self.budget.try_acquire_open(bytes, class, true)
304 }
305
306 pub(super) fn try_acquire_waiting(
307 &self,
308 bytes: usize,
309 class: BudgetClass,
310 ) -> Result<ResourcePermit, BudgetRejection> {
311 self.budget.try_acquire_open(bytes, class, false)
312 }
313}
314
315impl fmt::Debug for ResourceBudget {
316 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
317 formatter
318 .debug_struct("ResourceBudget")
319 .field("path", &self.node.path)
320 .field("limit", &self.node.limit)
321 .finish()
322 }
323}
324
325impl ResourceBudget {
326 pub fn child(&self, name: impl Into<String>, limit: BudgetLimit) -> Result<Self, crate::RuntimeContractViolation> {
336 self.child_with_gates(name, limit, self.admission_gates.clone(), true)
337 }
338
339 pub fn child_group<const N: usize>(
353 &self,
354 name: impl Into<String>,
355 limit: BudgetLimit,
356 children: [(&str, BudgetLimit); N],
357 ) -> Result<[Self; N], crate::RuntimeContractViolation> {
358 let counted = !children_fit_within(limit, children.iter().map(|(_, child)| *child));
359 let group = self.child_with_gates(name, limit, self.admission_gates.clone(), counted)?;
360 let mut created = Vec::with_capacity(N);
361 for (child_name, child_limit) in children {
362 created.push(group.child(child_name, child_limit)?);
363 }
364 Ok(created
365 .try_into()
366 .unwrap_or_else(|_: Vec<Self>| unreachable!("one budget is created for each of the N children")))
367 }
368
369 fn child_with_gates(
370 &self,
371 name: impl Into<String>,
372 limit: BudgetLimit,
373 admission_gates: Arc<[Arc<AdmissionGate>]>,
374 counted: bool,
375 ) -> Result<Self, crate::RuntimeContractViolation> {
376 let name = validated_name(name.into())?;
377 let path: Arc<str> = Arc::from(format!("{}/{}", self.node.path, name));
378 limit.validate_child(self.node.limit, &path)?;
379 let node = Arc::new(BudgetNode::new(
380 path,
381 limit,
382 Arc::clone(&self.node.clock),
383 admission_gates.clone(),
384 Arc::clone(&self.capacity_notify),
385 counted,
386 ));
387 let mut chain = Vec::with_capacity(self.chain.len() + 1);
388 chain.extend(self.chain.iter().cloned());
389 chain.push(Arc::clone(&node));
390 Ok(Self {
391 node,
392 chain: Arc::from(chain),
393 capacity_notify: Arc::clone(&self.capacity_notify),
394 keys: self.keys.clone(),
395 admission_gates,
396 })
397 }
398
399 pub fn register_dynamic_child(
414 &self,
415 name: impl Into<String>,
416 limit: BudgetLimit,
417 ) -> Result<DynamicBudgetKey, DynamicKeyRegistrationFailure> {
418 let _admission = self.admit().map_err(|_| DynamicKeyRegistrationFailure::Closed)?;
419 let name = validated_name(name.into()).map_err(DynamicKeyRegistrationFailure::Invalid)?;
420 let path: Arc<str> = Arc::from(format!("{}/{}", self.node.path, name));
421 let mut gates = self.admission_gates.to_vec();
422 gates.push(Arc::new(AdmissionGate {
423 path: path.clone(),
424 closed: Mutex::new(false),
425 }));
426 let child = self
427 .child_with_gates(name, limit, Arc::from(gates), true)
428 .map_err(DynamicKeyRegistrationFailure::Invalid)?;
429 self.keys.register(child, path)
430 }
431
432 #[must_use]
435 pub fn is_closed(&self) -> bool {
436 self.admission_gates
437 .iter()
438 .any(|gate| *gate.closed.lock().unwrap_or_else(std::sync::PoisonError::into_inner))
439 }
440
441 pub(super) fn close_dynamic(&self) {
442 if let Some(gate) = self.admission_gates.last() {
443 *gate.closed.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = true;
444 self.capacity_notify.signal_closed();
445 }
446 }
447
448 pub(super) fn admit(&self) -> Result<BudgetAdmission<'_>, BudgetRejection> {
449 let mut guards = SmallVec::new();
450 for gate in self.admission_gates.iter() {
451 let guard = gate.closed.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
452 if *guard {
453 let rejection = BudgetRejection {
454 path: self.node.path.clone(),
455 exhausted_path: gate.path.clone(),
456 reason: BudgetRejectionReason::Closed,
457 policy: self.node.limit.full_policy,
458 };
459 self.record_budget_rejection(&rejection);
460 return Err(rejection);
461 }
462 guards.push(guard);
463 }
464 Ok(BudgetAdmission {
465 budget: self,
466 _guards: guards,
467 })
468 }
469
470 pub fn try_acquire(&self, bytes: usize, class: BudgetClass) -> Result<ResourcePermit, BudgetRejection> {
475 self.try_acquire_internal(bytes, class, true)
476 }
477
478 fn try_acquire_internal(
479 &self,
480 bytes: usize,
481 class: BudgetClass,
482 record_failure: bool,
483 ) -> Result<ResourcePermit, BudgetRejection> {
484 let _admission = self.admit()?;
485 self.try_acquire_open(bytes, class, record_failure)
486 }
487
488 fn try_acquire_open(
489 &self,
490 bytes: usize,
491 class: BudgetClass,
492 record_failure: bool,
493 ) -> Result<ResourcePermit, BudgetRejection> {
494 let mut reservations = PendingReservations::new(&self.chain, bytes, class);
495 if let Err((node, dimension)) = reservations.reserve_all() {
496 if record_failure {
497 self.record_node_rejection(node, BudgetRejectionReason::Capacity(dimension));
498 }
499 return Err(BudgetRejection {
500 path: Arc::clone(&self.node.path),
501 exhausted_path: Arc::clone(&node.path),
502 reason: BudgetRejectionReason::Capacity(dimension),
503 policy: self.node.limit.full_policy,
504 });
505 }
506 reservations.commit();
507 Ok(ResourcePermit {
508 chain: Arc::clone(&self.chain),
509 bytes,
510 class,
511 })
512 }
513
514 pub(crate) fn permanent_acquire_rejection(&self, bytes: usize, class: BudgetClass) -> Option<BudgetRejection> {
515 let _admission = match self.admit() {
516 Ok(admission) => admission,
517 Err(rejection) => return Some(rejection),
518 };
519 self.chain.iter().find_map(|node| {
520 let dimension = node.permanent_exhaustion_dimension(bytes, class)?;
521 self.record_node_rejection(node, BudgetRejectionReason::Capacity(dimension));
522 Some(BudgetRejection {
523 path: Arc::clone(&self.node.path),
524 exhausted_path: Arc::clone(&node.path),
525 reason: BudgetRejectionReason::Capacity(dimension),
526 policy: self.node.limit.full_policy,
527 })
528 })
529 }
530
531 pub(crate) fn record_budget_rejection(&self, error: &BudgetRejection) {
532 if let Some(node) = self
533 .chain
534 .iter()
535 .find(|node| node.path.as_ref() == error.exhausted_path())
536 {
537 self.record_node_rejection(node, error.reason());
538 }
539 }
540
541 fn record_node_rejection(&self, exhausted_node: &Arc<BudgetNode>, reason: BudgetRejectionReason) {
542 exhausted_node.record_rejection(reason);
543 if !Arc::ptr_eq(exhausted_node, &self.node) {
544 self.node.record_rejection(reason);
545 }
546 }
547
548 pub(crate) fn capacity_notify(&self) -> &CapacitySignal {
549 &self.capacity_notify
550 }
551
552 pub(crate) fn can_close(&self) -> bool {
556 !self.admission_gates.is_empty()
557 }
558
559 pub fn try_acquire_data(&self, bytes: usize) -> Result<ResourcePermit, BudgetRejection> {
564 self.try_acquire(bytes, BudgetClass::Data)
565 }
566
567 pub fn try_acquire_control(&self, bytes: usize) -> Result<ResourcePermit, BudgetRejection> {
572 self.try_acquire(bytes, BudgetClass::Control)
573 }
574
575 #[must_use]
576 pub fn snapshot(&self) -> BudgetSnapshot {
578 self.node.snapshot()
579 }
580
581 #[must_use]
582 pub fn path(&self) -> &str {
584 &self.node.path
585 }
586
587 #[must_use]
588 pub fn limit(&self) -> BudgetLimit {
590 self.node.limit
591 }
592
593 #[must_use]
595 pub fn monotonic_now(&self) -> Duration {
596 self.node.clock.now()
597 }
598
599 pub fn record_dropped(&self, count: usize) {
601 self.node.record_dropped(count);
602 }
603
604 pub fn record_coalesced(&self, count: usize) {
606 self.node.record_coalesced(count);
607 }
608
609 pub fn record_slow_consumer_closed(&self) {
611 self.node.record_slow_consumer_closed();
612 }
613}
614
615fn children_fit_within(limit: BudgetLimit, children: impl Iterator<Item = BudgetLimit>) -> bool {
621 if limit.capacity.rate.is_some() {
622 return false;
623 }
624 let mut sums = Some([0usize; 4]);
625 for child in children {
626 sums = sums.and_then(|[count, bytes, data_count, data_bytes]| {
627 let data = data_capacity(child);
628 Some([
629 count.checked_add(child.capacity.count)?,
630 bytes.checked_add(child.capacity.bytes)?,
631 data_count.checked_add(data.0)?,
632 data_bytes.checked_add(data.1)?,
633 ])
634 });
635 }
636 let Some([count, bytes, data_count, data_bytes]) = sums else {
637 return false;
638 };
639 let (group_data_count, group_data_bytes) = data_capacity(limit);
640 count <= limit.capacity.count
641 && bytes <= limit.capacity.bytes
642 && data_count <= group_data_count
643 && data_bytes <= group_data_bytes
644}
645
646fn data_capacity(limit: BudgetLimit) -> (usize, usize) {
648 (
649 limit.capacity.count.saturating_sub(limit.control_reserve.count),
650 limit.capacity.bytes.saturating_sub(limit.control_reserve.bytes),
651 )
652}
653
654fn validated_name(name: String) -> Result<String, crate::RuntimeContractViolation> {
655 let name = name.trim();
656 if name.is_empty() {
657 return Err(crate::RuntimeContractViolation::EmptyBudgetName);
658 }
659 if name.contains('/') {
660 return Err(crate::RuntimeContractViolation::InvalidBudgetName);
661 }
662 Ok(name.to_owned())
663}
664
665pub struct ResourcePermit {
672 chain: Arc<[Arc<BudgetNode>]>,
673 bytes: usize,
674 class: BudgetClass,
675}
676
677impl fmt::Debug for ResourcePermit {
678 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
679 formatter
680 .debug_struct("ResourcePermit")
681 .field("path", &self.chain.last().map(|node| &node.path))
682 .field("bytes", &self.bytes)
683 .field("class", &self.class)
684 .finish()
685 }
686}
687
688impl ResourcePermit {
689 pub fn try_resize(&mut self, bytes: usize) -> Result<(), BudgetRejection> {
701 if bytes <= self.bytes {
702 self.shrink_to(bytes);
703 return Ok(());
704 }
705 let chain = &self.chain;
706 let Some(leaf) = chain.last() else {
708 return Ok(());
709 };
710 let mut guards = SmallVec::<[MutexGuard<'_, bool>; 2]>::new();
711 for gate in leaf.admission_gates.iter() {
712 let guard = gate.closed.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
713 if *guard {
714 leaf.record_rejection(BudgetRejectionReason::Closed);
715 return Err(BudgetRejection {
716 path: leaf.path.clone(),
717 exhausted_path: gate.path.clone(),
718 reason: BudgetRejectionReason::Closed,
719 policy: leaf.limit.full_policy,
720 });
721 }
722 guards.push(guard);
723 }
724 let additional = bytes - self.bytes;
725 for (index, node) in chain.iter().enumerate() {
726 if !node.try_reserve_bytes(additional, self.class) {
727 for reserved in &chain[..index] {
728 reserved.release_bytes(additional, self.class);
729 }
730 let reason = BudgetRejectionReason::Capacity(BudgetDimension::Bytes);
731 node.record_rejection(reason);
732 if !Arc::ptr_eq(node, leaf) {
733 leaf.record_rejection(reason);
734 }
735 node.capacity_notify.signal();
736 return Err(BudgetRejection {
737 path: leaf.path.clone(),
738 exhausted_path: node.path.clone(),
739 reason,
740 policy: leaf.limit.full_policy,
741 });
742 }
743 }
744 drop(guards);
745 self.bytes = bytes;
746 Ok(())
747 }
748
749 pub(crate) fn shrink_to(&mut self, bytes: usize) {
750 let released = self.bytes.saturating_sub(bytes);
751 if released == 0 {
752 return;
753 }
754 for node in self.chain.iter() {
755 node.release_bytes(released, self.class);
756 }
757 self.bytes = bytes;
758 self.signal_capacity();
759 }
760
761 #[must_use]
762 pub const fn bytes(&self) -> usize {
764 self.bytes
765 }
766
767 #[must_use]
768 pub const fn class(&self) -> BudgetClass {
770 self.class
771 }
772
773 pub fn promote_to_control(&mut self) {
778 if self.class == BudgetClass::Control {
779 return;
780 }
781 for node in self.chain.iter() {
782 node.release_data_class(self.bytes);
783 if let Some(rate) = &node.rate {
784 BudgetNode::lock_rate(rate).restore_data(node.limit);
785 }
786 }
787 self.class = BudgetClass::Control;
788 self.signal_capacity();
789 }
790
791 pub fn try_rebind(
806 &mut self,
807 target: &ResourceBudget,
808 ) -> Result<PermitBudgetTransferStatus, crate::RuntimeContractViolation> {
809 if !self.belongs_to_tree(target) {
810 return Err(crate::RuntimeContractViolation::PermitTargetInDifferentTree);
811 }
812 let admission = match target.admit() {
813 Ok(admission) => admission,
814 Err(rejection) => return Ok(PermitBudgetTransferStatus::Rejected(rejection)),
815 };
816 Ok(self.try_rebind_admitted(&admission))
817 }
818
819 pub(super) fn belongs_to_tree(&self, target: &ResourceBudget) -> bool {
820 self.chain
821 .first()
822 .zip(target.chain.first())
823 .is_some_and(|(held, node)| Arc::ptr_eq(held, node))
824 }
825
826 pub(super) fn try_rebind_admitted(&mut self, admission: &BudgetAdmission<'_>) -> PermitBudgetTransferStatus {
827 let target = admission.budget;
828 let common_ancestors = self
829 .chain
830 .iter()
831 .zip(target.chain.iter())
832 .take_while(|(held, target_node)| Arc::ptr_eq(held, target_node))
833 .count();
834 debug_assert!(
835 common_ancestors > 0,
836 "caller validates the permit tree before admission"
837 );
838 if common_ancestors == self.chain.len() && common_ancestors == target.chain.len() {
839 return PermitBudgetTransferStatus::Unchanged;
840 }
841
842 let mut target_reservations =
843 PendingReservations::new(&target.chain[common_ancestors..], self.bytes, self.class);
844 if let Err((node, dimension)) = target_reservations.reserve_all() {
845 target.record_node_rejection(node, BudgetRejectionReason::Capacity(dimension));
846 return PermitBudgetTransferStatus::Rejected(BudgetRejection {
847 path: Arc::clone(&target.node.path),
848 exhausted_path: Arc::clone(&node.path),
849 reason: BudgetRejectionReason::Capacity(dimension),
850 policy: target.node.limit.full_policy,
851 });
852 }
853 target_reservations.commit();
854
855 for node in &self.chain[common_ancestors..] {
856 node.release_held(self.bytes, self.class);
857 }
858 self.chain = Arc::clone(&target.chain);
860 self.signal_capacity();
861 PermitBudgetTransferStatus::Rebound
862 }
863
864 fn signal_capacity(&self) {
865 if let Some(root) = self.chain.first() {
866 root.capacity_notify.signal();
867 }
868 }
869}
870
871impl Drop for ResourcePermit {
872 fn drop(&mut self) {
873 for node in self.chain.iter() {
874 node.release_held(self.bytes, self.class);
875 }
876 self.signal_capacity();
877 }
878}
879
880struct BudgetNode {
894 path: Arc<str>,
895 limit: BudgetLimit,
896 clock: Arc<dyn MonotonicClock>,
897 counted: bool,
898 total: PackedUsage,
899 data: PackedUsage,
900 total_limit: PackedLimit,
901 data_limit: PackedLimit,
902 counters: BudgetCounters,
903 rate: Option<Mutex<RateState>>,
904 admission_gates: Arc<[Arc<AdmissionGate>]>,
907 capacity_notify: Arc<CapacitySignal>,
909}
910
911#[derive(Default)]
913struct BudgetCounters {
914 admitted: AtomicU64,
915 rejected: AtomicU64,
916 throttled: AtomicU64,
917 dropped: AtomicU64,
918 coalesced: AtomicU64,
919 closed_slow_consumer: AtomicU64,
920}
921
922const PACKED_BYTE_BITS: u32 = 40;
924const PACKED_BYTE_MASK: u64 = (1 << PACKED_BYTE_BITS) - 1;
925const MAX_PACKED_COUNT: u64 = (1 << (u64::BITS - PACKED_BYTE_BITS)) - 1;
927const MAX_PACKED_BYTES: u64 = PACKED_BYTE_MASK;
929
930#[derive(Clone, Copy)]
935struct PackedLimit {
936 count: u64,
937 bytes: u64,
938}
939
940impl PackedLimit {
941 fn new(count: usize, bytes: usize) -> Self {
942 Self {
943 count: packed_field(count).min(MAX_PACKED_COUNT),
944 bytes: packed_field(bytes).min(MAX_PACKED_BYTES),
945 }
946 }
947}
948
949fn packed_field(value: usize) -> u64 {
950 u64::try_from(value).unwrap_or(u64::MAX)
951}
952
953#[derive(Default)]
960struct PackedUsage(AtomicU64);
961
962impl PackedUsage {
963 fn try_reserve(&self, count: u64, bytes: usize, limit: PackedLimit) -> Result<(), BudgetDimension> {
965 let bytes = packed_field(bytes);
966 let mut current = self.0.load(Ordering::Acquire);
967 loop {
968 let held_count = current >> PACKED_BYTE_BITS;
969 let held_bytes = current & PACKED_BYTE_MASK;
970 let next_count = held_count + count;
971 if next_count > limit.count {
972 return Err(BudgetDimension::Count);
973 }
974 let Some(next_bytes) = held_bytes.checked_add(bytes).filter(|total| *total <= limit.bytes) else {
975 return Err(BudgetDimension::Bytes);
976 };
977 match self.0.compare_exchange_weak(
978 current,
979 (next_count << PACKED_BYTE_BITS) | next_bytes,
980 Ordering::AcqRel,
981 Ordering::Acquire,
982 ) {
983 Ok(_) => return Ok(()),
984 Err(actual) => current = actual,
985 }
986 }
987 }
988
989 fn release(&self, count: u64, bytes: usize) {
991 let bytes = packed_field(bytes);
992 debug_assert!(
993 bytes <= MAX_PACKED_BYTES,
994 "a reservation never holds more than the packed maximum"
995 );
996 let previous = self.0.fetch_sub((count << PACKED_BYTE_BITS) | bytes, Ordering::AcqRel);
997 debug_assert!(
998 previous >> PACKED_BYTE_BITS >= count && previous & PACKED_BYTE_MASK >= bytes,
999 "budget capacity released more than reserved"
1000 );
1001 }
1002
1003 fn load(&self) -> (usize, usize) {
1004 let current = self.0.load(Ordering::Acquire);
1005 (
1006 usize::try_from(current >> PACKED_BYTE_BITS).unwrap_or(usize::MAX),
1007 usize::try_from(current & PACKED_BYTE_MASK).unwrap_or(usize::MAX),
1008 )
1009 }
1010}
1011
1012impl BudgetNode {
1013 fn try_reserve_bytes(&self, bytes: usize, class: BudgetClass) -> bool {
1014 if !self.counted {
1015 return true;
1016 }
1017 if self.total.try_reserve(0, bytes, self.total_limit).is_err() {
1018 return false;
1019 }
1020 if class == BudgetClass::Data && self.data.try_reserve(0, bytes, self.data_limit).is_err() {
1021 self.total.release(0, bytes);
1022 return false;
1023 }
1024 true
1025 }
1026
1027 fn release_bytes(&self, bytes: usize, class: BudgetClass) {
1028 if !self.counted {
1029 return;
1030 }
1031 if class == BudgetClass::Data {
1032 self.data.release(0, bytes);
1033 }
1034 self.total.release(0, bytes);
1035 }
1036
1037 fn new(
1038 path: Arc<str>,
1039 limit: BudgetLimit,
1040 clock: Arc<dyn MonotonicClock>,
1041 admission_gates: Arc<[Arc<AdmissionGate>]>,
1042 capacity_notify: Arc<CapacitySignal>,
1043 counted: bool,
1044 ) -> Self {
1045 let rate = limit
1046 .capacity
1047 .rate
1048 .map(|_| Mutex::new(RateState::new(limit, clock.now())));
1049 let capacity = limit.capacity;
1050 let reserve = limit.control_reserve;
1051 Self {
1052 path,
1053 limit,
1054 clock,
1055 counted,
1056 total: PackedUsage::default(),
1057 data: PackedUsage::default(),
1058 total_limit: PackedLimit::new(capacity.count, capacity.bytes),
1059 data_limit: PackedLimit::new(
1060 capacity.count.saturating_sub(reserve.count),
1061 capacity.bytes.saturating_sub(reserve.bytes),
1062 ),
1063 counters: BudgetCounters::default(),
1064 rate,
1065 admission_gates,
1066 capacity_notify,
1067 }
1068 }
1069
1070 fn lock_rate(rate: &Mutex<RateState>) -> MutexGuard<'_, RateState> {
1071 rate.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
1072 }
1073
1074 fn try_reserve(&self, bytes: usize, class: BudgetClass) -> Result<(), BudgetDimension> {
1077 if !self.counted {
1078 return Ok(());
1079 }
1080 self.total.try_reserve(1, bytes, self.total_limit)?;
1081 if class == BudgetClass::Data {
1082 if let Err(dimension) = self.data.try_reserve(1, bytes, self.data_limit) {
1083 self.total.release(1, bytes);
1084 return Err(dimension);
1085 }
1086 }
1087 if let Some(rate) = &self.rate {
1088 let mut rate = Self::lock_rate(rate);
1089 rate.refill(self.limit, self.clock.now());
1090 if !rate.available(self.limit, class) {
1091 drop(rate);
1092 self.release_capacity(bytes, class);
1093 return Err(BudgetDimension::Rate);
1094 }
1095 rate.consume(self.limit, class);
1096 }
1097
1098 Ok(())
1099 }
1100
1101 fn release_held(&self, bytes: usize, class: BudgetClass) {
1103 self.release_capacity(bytes, class);
1104 }
1105
1106 fn release_capacity(&self, bytes: usize, class: BudgetClass) {
1108 if !self.counted {
1109 return;
1110 }
1111 if class == BudgetClass::Data {
1112 self.data.release(1, bytes);
1113 }
1114 self.total.release(1, bytes);
1115 }
1116
1117 fn release_data_class(&self, bytes: usize) {
1119 if self.counted {
1120 self.data.release(1, bytes);
1121 }
1122 }
1123
1124 fn permanent_exhaustion_dimension(&self, bytes: usize, class: BudgetClass) -> Option<BudgetDimension> {
1125 let limit = match class {
1126 BudgetClass::Data => self.data_limit,
1127 BudgetClass::Control => self.total_limit,
1128 };
1129 if limit.count == 0 {
1130 Some(BudgetDimension::Count)
1131 } else if packed_field(bytes) > limit.bytes {
1132 Some(BudgetDimension::Bytes)
1133 } else {
1134 None
1135 }
1136 }
1137
1138 fn record_rejection(&self, reason: BudgetRejectionReason) {
1139 self.counters.rejected.fetch_add(1, Ordering::Relaxed);
1140 if reason == BudgetRejectionReason::Capacity(BudgetDimension::Rate) {
1141 self.counters.throttled.fetch_add(1, Ordering::Relaxed);
1142 }
1143 }
1144
1145 fn record_dropped(&self, count: usize) {
1146 self.counters.dropped.fetch_add(count as u64, Ordering::Relaxed);
1147 }
1148
1149 fn record_coalesced(&self, count: usize) {
1150 self.counters.coalesced.fetch_add(count as u64, Ordering::Relaxed);
1151 }
1152
1153 fn record_slow_consumer_closed(&self) {
1154 self.counters.closed_slow_consumer.fetch_add(1, Ordering::Relaxed);
1155 }
1156
1157 fn snapshot(&self) -> BudgetSnapshot {
1162 let (current_count, current_bytes) = self.total.load();
1163 let admitted_count = self.counters.admitted.load(Ordering::Acquire);
1164 BudgetSnapshot {
1165 path: Arc::clone(&self.path),
1166 current_count,
1167 current_bytes,
1168 admitted_count,
1169 released_count: admitted_count.saturating_sub(current_count as u64),
1170 rejected_count: self.counters.rejected.load(Ordering::Relaxed),
1171 throttled_count: self.counters.throttled.load(Ordering::Relaxed),
1172 dropped_count: self.counters.dropped.load(Ordering::Relaxed),
1173 coalesced_count: self.counters.coalesced.load(Ordering::Relaxed),
1174 closed_slow_consumer_count: self.counters.closed_slow_consumer.load(Ordering::Relaxed),
1175 }
1176 }
1177}
1178
1179struct PendingReservations<'a> {
1182 nodes: &'a [Arc<BudgetNode>],
1183 reserved: usize,
1184 bytes: usize,
1185 class: BudgetClass,
1186}
1187
1188impl<'a> PendingReservations<'a> {
1189 fn new(nodes: &'a [Arc<BudgetNode>], bytes: usize, class: BudgetClass) -> Self {
1190 Self {
1191 nodes,
1192 reserved: 0,
1193 bytes,
1194 class,
1195 }
1196 }
1197
1198 fn reserve_all(&mut self) -> Result<(), (&'a Arc<BudgetNode>, BudgetDimension)> {
1200 let nodes = self.nodes;
1201 for node in nodes {
1202 node.try_reserve(self.bytes, self.class)
1203 .map_err(|dimension| (node, dimension))?;
1204 self.reserved += 1;
1205 }
1206 Ok(())
1207 }
1208
1209 fn commit(mut self) {
1211 for node in &self.nodes[..self.reserved] {
1212 if node.counted {
1213 node.counters.admitted.fetch_add(1, Ordering::Relaxed);
1214 }
1215 }
1216 self.reserved = 0;
1217 }
1218}
1219
1220impl Drop for PendingReservations<'_> {
1221 fn drop(&mut self) {
1222 for node in &self.nodes[..self.reserved] {
1223 node.release_capacity(self.bytes, self.class);
1224 if let Some(rate) = &node.rate {
1225 BudgetNode::lock_rate(rate).restore(node.limit, self.class);
1227 }
1228 }
1229 }
1230}
1231
1232struct RateState {
1234 total_tokens: Option<TokenBucket>,
1235 data_tokens: Option<TokenBucket>,
1236}
1237
1238impl RateState {
1239 fn new(limit: BudgetLimit, now: Duration) -> Self {
1240 Self {
1241 total_tokens: limit.capacity.rate.map(|rate| TokenBucket::new(rate, now)),
1242 data_tokens: data_rate_limit(limit).map(|rate| TokenBucket::new(rate, now)),
1243 }
1244 }
1245
1246 fn refill(&mut self, limit: BudgetLimit, now: Duration) {
1247 if let (Some(bucket), Some(rate)) = (&mut self.total_tokens, limit.capacity.rate) {
1248 bucket.refill(rate, now);
1249 }
1250 if let (Some(bucket), Some(rate)) = (&mut self.data_tokens, data_rate_limit(limit)) {
1251 bucket.refill(rate, now);
1252 }
1253 }
1254
1255 fn available(&self, limit: BudgetLimit, class: BudgetClass) -> bool {
1256 let total_available = self.total_tokens.as_ref().is_none_or(TokenBucket::has_token);
1257 let data_available = class == BudgetClass::Control
1258 || data_rate_limit(limit).is_none()
1259 || self.data_tokens.as_ref().is_some_and(TokenBucket::has_token);
1260 total_available && data_available
1261 }
1262
1263 fn consume(&mut self, limit: BudgetLimit, class: BudgetClass) {
1264 if let Some(bucket) = &mut self.total_tokens {
1265 bucket.consume();
1266 }
1267 if class == BudgetClass::Data && data_rate_limit(limit).is_some() {
1268 if let Some(bucket) = &mut self.data_tokens {
1269 bucket.consume();
1270 }
1271 }
1272 }
1273
1274 fn restore(&mut self, limit: BudgetLimit, class: BudgetClass) {
1275 if let (Some(bucket), Some(rate)) = (&mut self.total_tokens, limit.capacity.rate) {
1276 bucket.restore(rate);
1277 }
1278 if class == BudgetClass::Data {
1279 self.restore_data(limit);
1280 }
1281 }
1282
1283 fn restore_data(&mut self, limit: BudgetLimit) {
1284 if let (Some(bucket), Some(rate)) = (&mut self.data_tokens, data_rate_limit(limit)) {
1285 bucket.restore(rate);
1286 }
1287 }
1288}
1289
1290fn data_rate_limit(limit: BudgetLimit) -> Option<RateLimit> {
1291 let total = limit.capacity.rate?;
1292 let reserve = limit.control_reserve.rate.unwrap_or(RateLimit::new(0, 0));
1293 Some(RateLimit::new(
1294 total.permits_per_second.saturating_sub(reserve.permits_per_second),
1295 total.burst.saturating_sub(reserve.burst),
1296 ))
1297}
1298
1299struct TokenBucket {
1300 tokens: f64,
1301 last_refill: Duration,
1302}
1303
1304impl TokenBucket {
1305 fn new(rate: RateLimit, now: Duration) -> Self {
1306 Self {
1307 tokens: rate.burst as f64,
1308 last_refill: now,
1309 }
1310 }
1311
1312 fn refill(&mut self, rate: RateLimit, now: Duration) {
1313 let elapsed = now.saturating_sub(self.last_refill).as_secs_f64();
1314 self.tokens = (self.tokens + elapsed * rate.permits_per_second as f64).min(rate.burst as f64);
1315 self.last_refill = now;
1316 }
1317
1318 fn has_token(&self) -> bool {
1319 self.tokens >= 1.0
1320 }
1321
1322 fn consume(&mut self) {
1323 self.tokens = (self.tokens - 1.0).max(0.0);
1324 }
1325
1326 fn restore(&mut self, rate: RateLimit) {
1327 self.tokens = (self.tokens + 1.0).min(rate.burst as f64);
1328 }
1329}