1use std::collections::BTreeMap;
13
14use crate::error::{CoreError, CoreResult};
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18pub enum LedgerType {
19 Root,
21 Domain,
23 Queue,
25 Connection,
27}
28
29impl LedgerType {
30 pub fn depth(&self) -> u8 {
32 match self {
33 LedgerType::Root => 0,
34 LedgerType::Domain => 1,
35 LedgerType::Queue => 2,
36 LedgerType::Connection => 3,
37 }
38 }
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
43pub enum ResourceType {
44 Memory,
46 Frames,
48 Connections,
50}
51
52impl ResourceType {
53 pub fn name(&self) -> &'static str {
55 match self {
56 ResourceType::Memory => "memory",
57 ResourceType::Frames => "frames",
58 ResourceType::Connections => "connections",
59 }
60 }
61}
62
63#[derive(Debug, Clone, Default)]
65pub struct LedgerQuota {
66 pub memory_bytes: u64,
68 pub frame_count: u64,
70 pub connection_count: u64,
72}
73
74impl LedgerQuota {
75 #[inline]
77 pub const fn zero() -> Self {
78 Self {
79 memory_bytes: 0,
80 frame_count: 0,
81 connection_count: 0,
82 }
83 }
84
85 #[inline]
87 pub const fn unlimited() -> Self {
88 Self {
89 memory_bytes: u64::MAX,
90 frame_count: u64::MAX,
91 connection_count: u64::MAX,
92 }
93 }
94
95 #[inline]
97 pub fn can_allocate(&self, child: &LedgerQuota) -> CoreResult<()> {
98 if child.memory_bytes > self.memory_bytes {
99 return Err(CoreError::quota_exceeded(
100 "memory",
101 self.memory_bytes,
102 child.memory_bytes,
103 ));
104 }
105 if child.frame_count > self.frame_count {
106 return Err(CoreError::quota_exceeded(
107 "frames",
108 self.frame_count,
109 child.frame_count,
110 ));
111 }
112 if child.connection_count > self.connection_count {
113 return Err(CoreError::quota_exceeded(
114 "connections",
115 self.connection_count,
116 child.connection_count,
117 ));
118 }
119 Ok(())
120 }
121
122 #[inline]
124 pub fn consume(&mut self, resource: ResourceType, amount: u64) -> CoreResult<()> {
125 let field = match resource {
126 ResourceType::Memory => &mut self.memory_bytes,
127 ResourceType::Frames => &mut self.frame_count,
128 ResourceType::Connections => &mut self.connection_count,
129 };
130 *field = field
131 .checked_sub(amount)
132 .ok_or_else(|| CoreError::arithmetic_overflow("sub", *field, amount))?;
133 Ok(())
134 }
135
136 #[inline]
138 pub fn restore(&mut self, resource: ResourceType, amount: u64) -> CoreResult<()> {
139 let field = match resource {
140 ResourceType::Memory => &mut self.memory_bytes,
141 ResourceType::Frames => &mut self.frame_count,
142 ResourceType::Connections => &mut self.connection_count,
143 };
144 *field = field
145 .checked_add(amount)
146 .ok_or_else(|| CoreError::arithmetic_overflow("add", *field, amount))?;
147 Ok(())
148 }
149
150 #[inline]
152 pub fn get(&self, resource: ResourceType) -> u64 {
153 match resource {
154 ResourceType::Memory => self.memory_bytes,
155 ResourceType::Frames => self.frame_count,
156 ResourceType::Connections => self.connection_count,
157 }
158 }
159
160 pub fn remaining(&self, used: &LedgerQuota) -> LedgerQuota {
162 LedgerQuota {
163 memory_bytes: self.memory_bytes.saturating_sub(used.memory_bytes),
164 frame_count: self.frame_count.saturating_sub(used.frame_count),
165 connection_count: self.connection_count.saturating_sub(used.connection_count),
166 }
167 }
168}
169
170#[derive(Debug)]
178pub struct ResourceLedger {
179 name: String,
181 ledger_type: LedgerType,
183 total: LedgerQuota,
185 used: LedgerQuota,
187 used_direct: LedgerQuota,
193 allocated_to_children: LedgerQuota,
195 children: BTreeMap<String, ResourceLedger>,
197}
198
199impl ResourceLedger {
200 pub fn new(name: impl Into<String>, ledger_type: LedgerType, total: LedgerQuota) -> Self {
202 Self {
203 name: name.into(),
204 ledger_type,
205 total,
206 used: LedgerQuota::zero(),
207 used_direct: LedgerQuota::zero(),
208 allocated_to_children: LedgerQuota::zero(),
209 children: BTreeMap::new(),
210 }
211 }
212
213 pub fn root(total: LedgerQuota) -> Self {
215 Self::new("root", LedgerType::Root, total)
216 }
217
218 #[inline]
220 pub fn name(&self) -> &str {
221 &self.name
222 }
223
224 #[inline]
226 pub fn ledger_type(&self) -> LedgerType {
227 self.ledger_type
228 }
229
230 #[inline]
232 pub fn depth(&self) -> u8 {
233 self.ledger_type.depth()
234 }
235
236 #[inline]
238 pub fn total(&self) -> &LedgerQuota {
239 &self.total
240 }
241
242 #[inline]
244 pub fn used(&self) -> &LedgerQuota {
245 &self.used
246 }
247
248 #[inline]
250 pub fn allocated_to_children(&self) -> &LedgerQuota {
251 &self.allocated_to_children
252 }
253
254 #[inline]
256 pub fn child_count(&self) -> usize {
257 self.children.len()
258 }
259
260 pub fn child_names(&self) -> impl Iterator<Item = &str> {
262 self.children.keys().map(|s| s.as_str())
263 }
264
265 pub fn get_child(&self, name: &str) -> Option<&ResourceLedger> {
267 self.children.get(name)
268 }
269
270 pub fn get_child_mut(&mut self, name: &str) -> Option<&mut ResourceLedger> {
272 self.children.get_mut(name)
273 }
274
275 pub fn create_child(
288 &mut self,
289 name: impl Into<String>,
290 ledger_type: LedgerType,
291 quota: LedgerQuota,
292 ) -> CoreResult<&mut ResourceLedger> {
293 let name: String = name.into();
294
295 if quota.memory_bytes == 0
297 && quota.frame_count == 0
298 && quota.connection_count == 0
299 {
300 return Err(CoreError::invalid_config(
301 "LedgerQuota",
302 "all quota fields are zero; a child ledger with zero total quota can never allocate any resource",
303 ));
304 }
305
306 if self.children.contains_key(&name) {
307 return Err(CoreError::resource_already_exists(
308 0,
309 "ledger",
310 ));
311 }
312
313 for resource in [ResourceType::Memory, ResourceType::Frames, ResourceType::Connections] {
316 let committed = self
317 .allocated_to_children
318 .get(resource)
319 .checked_add(quota.get(resource))
320 .ok_or_else(|| {
321 CoreError::arithmetic_overflow(
322 "add",
323 self.allocated_to_children.get(resource),
324 quota.get(resource),
325 )
326 })?;
327 let available = self
329 .total
330 .get(resource)
331 .checked_sub(self.used.get(resource))
332 .ok_or_else(|| {
333 CoreError::arithmetic_overflow(
334 "sub",
335 self.total.get(resource),
336 self.used.get(resource),
337 )
338 })?;
339 if committed > available {
340 return Err(CoreError::quota_exceeded(
341 resource.name(),
342 available,
343 committed,
344 ));
345 }
346 }
347
348 self.allocated_to_children.memory_bytes = self
351 .allocated_to_children
352 .memory_bytes
353 .checked_add(quota.memory_bytes)
354 .ok_or_else(|| {
355 CoreError::arithmetic_overflow(
356 "add",
357 self.allocated_to_children.memory_bytes,
358 quota.memory_bytes,
359 )
360 })?;
361 self.allocated_to_children.frame_count = self
362 .allocated_to_children
363 .frame_count
364 .checked_add(quota.frame_count)
365 .ok_or_else(|| {
366 CoreError::arithmetic_overflow(
367 "add",
368 self.allocated_to_children.frame_count,
369 quota.frame_count,
370 )
371 })?;
372 self.allocated_to_children.connection_count = self
373 .allocated_to_children
374 .connection_count
375 .checked_add(quota.connection_count)
376 .ok_or_else(|| {
377 CoreError::arithmetic_overflow(
378 "add",
379 self.allocated_to_children.connection_count,
380 quota.connection_count,
381 )
382 })?;
383
384 let child = ResourceLedger::new(name.clone(), ledger_type, quota);
385 self.children.insert(name.clone(), child);
386
387 self.children.get_mut(&name).ok_or_else(|| CoreError::internal("child ledger not found after insertion"))
388 }
389
390 pub fn remove_child(&mut self, name: &str) -> CoreResult<()> {
403 let (new_used, new_allocated) = {
405 let child = self
406 .children
407 .get(name)
408 .ok_or_else(|| CoreError::resource_not_found(0, "ledger"))?;
409
410 let new_used = LedgerQuota {
413 memory_bytes: self.used.memory_bytes.checked_sub(child.used.memory_bytes).ok_or_else(
414 || {
415 CoreError::arithmetic_overflow(
416 "sub",
417 self.used.memory_bytes,
418 child.used.memory_bytes,
419 )
420 },
421 )?,
422 frame_count: self
423 .used
424 .frame_count
425 .checked_sub(child.used.frame_count)
426 .ok_or_else(|| {
427 CoreError::arithmetic_overflow(
428 "sub",
429 self.used.frame_count,
430 child.used.frame_count,
431 )
432 })?,
433 connection_count: self
434 .used
435 .connection_count
436 .checked_sub(child.used.connection_count)
437 .ok_or_else(|| {
438 CoreError::arithmetic_overflow(
439 "sub",
440 self.used.connection_count,
441 child.used.connection_count,
442 )
443 })?,
444 };
445 let new_allocated = LedgerQuota {
447 memory_bytes: self
448 .allocated_to_children
449 .memory_bytes
450 .checked_sub(child.total.memory_bytes)
451 .ok_or_else(|| {
452 CoreError::arithmetic_overflow(
453 "sub",
454 self.allocated_to_children.memory_bytes,
455 child.total.memory_bytes,
456 )
457 })?,
458 frame_count: self
459 .allocated_to_children
460 .frame_count
461 .checked_sub(child.total.frame_count)
462 .ok_or_else(|| {
463 CoreError::arithmetic_overflow(
464 "sub",
465 self.allocated_to_children.frame_count,
466 child.total.frame_count,
467 )
468 })?,
469 connection_count: self
470 .allocated_to_children
471 .connection_count
472 .checked_sub(child.total.connection_count)
473 .ok_or_else(|| {
474 CoreError::arithmetic_overflow(
475 "sub",
476 self.allocated_to_children.connection_count,
477 child.total.connection_count,
478 )
479 })?,
480 };
481 (new_used, new_allocated)
482 };
483
484 self.children.remove(name);
486 self.used = new_used;
487 self.allocated_to_children = new_allocated;
488 Ok(())
489 }
490
491 pub fn allocate(&mut self, resource: ResourceType, amount: u64) -> CoreResult<()> {
504 let direct = self.used_direct.get(resource);
505 let total = self.total.get(resource);
506 let new_direct = direct
507 .checked_add(amount)
508 .ok_or_else(|| CoreError::arithmetic_overflow("add", direct, amount))?;
509
510 let committed = self.allocated_to_children.get(resource);
512 let total_need = new_direct
513 .checked_add(committed)
514 .ok_or_else(|| CoreError::arithmetic_overflow("add", new_direct, committed))?;
515 if total_need > total {
516 return Err(CoreError::quota_exceeded(resource.name(), total, total_need));
517 }
518
519 self.used_direct.restore(resource, amount)?;
521 self.used.restore(resource, amount)?;
522 Ok(())
523 }
524
525 fn allocate_rollup(&mut self, resource: ResourceType, amount: u64) -> CoreResult<()> {
531 let current = self.used.get(resource);
532 let total = self.total.get(resource);
533 let new_used = current
534 .checked_add(amount)
535 .ok_or_else(|| CoreError::arithmetic_overflow("add", current, amount))?;
536 if new_used > total {
537 return Err(CoreError::quota_exceeded(resource.name(), total, new_used));
538 }
539 self.used.restore(resource, amount)?;
540 Ok(())
541 }
542
543 pub fn release(&mut self, resource: ResourceType, amount: u64) -> CoreResult<()> {
548 self.used_direct.consume(resource, amount)?;
549 self.used.consume(resource, amount)?;
550 Ok(())
551 }
552
553 fn release_rollup(&mut self, resource: ResourceType, amount: u64) -> CoreResult<()> {
558 self.used.consume(resource, amount)?;
559 Ok(())
560 }
561
562 pub fn allocate_in_child(
580 &mut self,
581 child_path: &[&str],
582 resource: ResourceType,
583 amount: u64,
584 ) -> CoreResult<()> {
585 match child_path.split_first() {
586 None => self.allocate(resource, amount),
587 Some((head, rest)) => {
588 if !self.children.contains_key(*head) {
590 return Err(CoreError::resource_not_found(0, "ledger"));
591 }
592 self.allocate_rollup(resource, amount)?;
596 let child = self
597 .children
598 .get_mut(*head)
599 .ok_or_else(|| CoreError::internal("child ledger not found after existence check"))?;
600 match child.allocate_in_child(rest, resource, amount) {
601 Ok(()) => Ok(()),
602 Err(e) => {
603 self.release_rollup(resource, amount)?;
608 Err(e)
609 }
610 }
611 }
612 }
613 }
614
615 pub fn release_in_child(
628 &mut self,
629 child_path: &[&str],
630 resource: ResourceType,
631 amount: u64,
632 ) -> CoreResult<()> {
633 match child_path.split_first() {
634 None => self.release(resource, amount),
635 Some((head, rest)) => {
636 if !self.children.contains_key(*head) {
638 return Err(CoreError::resource_not_found(0, "ledger"));
639 }
640 self.release_rollup(resource, amount)?;
643 let child = self
644 .children
645 .get_mut(*head)
646 .ok_or_else(|| CoreError::internal("child ledger not found after existence check"))?;
647 match child.release_in_child(rest, resource, amount) {
648 Ok(()) => Ok(()),
649 Err(e) => {
650 self.used.restore(resource, amount)?;
653 Err(e)
654 }
655 }
656 }
657 }
658 }
659
660 #[inline]
665 pub fn can_allocate(&self, resource: ResourceType, amount: u64) -> bool {
666 let direct = self.used_direct.get(resource);
667 let total = self.total.get(resource);
668 let committed = self.allocated_to_children.get(resource);
669 match direct
670 .checked_add(amount)
671 .and_then(|v| v.checked_add(committed))
672 {
673 Some(need) => need <= total,
674 None => false,
676 }
677 }
678
679 pub fn remaining(&self) -> LedgerQuota {
681 self.total.remaining(&self.used)
682 }
683
684 pub fn max_depth(&self) -> u8 {
686 let mut max = self.depth();
687 for child in self.children.values() {
688 max = max.max(child.max_depth());
689 }
690 max
691 }
692
693 pub fn node_count(&self) -> u64 {
695 self.children
699 .values()
700 .map(ResourceLedger::node_count)
701 .fold(1u64, u64::saturating_add)
702 }
703}
704
705#[cfg(test)]
706mod tests {
707 use super::*;
708
709 fn make_quota(mem: u64, frames: u64, conns: u64) -> LedgerQuota {
710 LedgerQuota {
711 memory_bytes: mem,
712 frame_count: frames,
713 connection_count: conns,
714 }
715 }
716
717 #[test]
718 fn test_root_ledger_create() {
719 let root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));
720 assert_eq!(root.name(), "root");
721 assert_eq!(root.ledger_type(), LedgerType::Root);
722 assert_eq!(root.depth(), 0);
723 assert_eq!(root.total().memory_bytes, 1 << 30);
724 assert_eq!(root.used().memory_bytes, 0);
725 assert_eq!(root.child_count(), 0);
726 assert_eq!(root.node_count(), 1);
727 }
728
729 #[test]
730 fn test_create_domain_child() {
731 let mut root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));
732
733 root.create_child("domain_0", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000))
734 .unwrap();
735
736 assert_eq!(root.child_count(), 1);
737 assert!(root.get_child("domain_0").is_some());
738
739 let domain = root.get_child("domain_0").unwrap();
740 assert_eq!(domain.ledger_type(), LedgerType::Domain);
741 assert_eq!(domain.depth(), 1);
742 assert_eq!(domain.total().frame_count, 10_000);
743 assert_eq!(root.node_count(), 2);
744 }
745
746 #[test]
747 fn test_create_child_quota_exceeded() {
748 let mut root = ResourceLedger::root(make_quota(1024, 100, 10));
749
750 let result = root.create_child("big", LedgerType::Domain, make_quota(2048, 0, 0));
752 assert!(result.is_err());
753
754 assert_eq!(root.child_count(), 0);
756 assert_eq!(root.total().memory_bytes, 1024);
757 }
758
759 #[test]
760 fn test_duplicate_child_name() {
761 let mut root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));
762
763 root.create_child("domain_0", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000))
764 .unwrap();
765
766 let result = root.create_child("domain_0", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000));
767 assert!(result.is_err());
768 }
769
770 #[test]
771 fn test_allocate_and_release() {
772 let mut ledger = ResourceLedger::new("test", LedgerType::Queue, make_quota(4096, 100, 10));
773
774 ledger.allocate(ResourceType::Memory, 1024).unwrap();
776 assert_eq!(ledger.used().memory_bytes, 1024);
777
778 ledger.release(ResourceType::Memory, 512).unwrap();
780 assert_eq!(ledger.used().memory_bytes, 512);
781
782 let remaining = ledger.remaining();
784 assert_eq!(remaining.memory_bytes, 4096 - 512);
785 }
786
787 #[test]
788 fn test_allocate_quota_exceeded() {
789 let mut ledger = ResourceLedger::new("small", LedgerType::Queue, make_quota(1024, 0, 0));
790
791 ledger.allocate(ResourceType::Memory, 512).unwrap();
792
793 let result = ledger.allocate(ResourceType::Memory, 1024);
794 assert!(result.is_err());
795 }
796
797 #[test]
798 fn test_allocate_overflow() {
799 let mut ledger = ResourceLedger::new("max", LedgerType::Queue, make_quota(u64::MAX, 0, 0));
800
801 ledger.allocate(ResourceType::Memory, u64::MAX).unwrap();
802
803 let result = ledger.allocate(ResourceType::Memory, 1);
804 assert!(result.is_err());
805 }
806
807 #[test]
808 fn test_frames_and_connections() {
809 let mut ledger = ResourceLedger::new("test", LedgerType::Queue, make_quota(0, 1000, 50));
810
811 ledger.allocate(ResourceType::Frames, 500).unwrap();
812 assert_eq!(ledger.used().frame_count, 500);
813
814 ledger.allocate(ResourceType::Connections, 10).unwrap();
815 assert_eq!(ledger.used().connection_count, 10);
816
817 ledger.release(ResourceType::Frames, 200).unwrap();
818 assert_eq!(ledger.used().frame_count, 300);
819 }
820
821 #[test]
822 fn test_can_allocate() {
823 let ledger = ResourceLedger::new("test", LedgerType::Queue, make_quota(1 << 30, 0, 0));
824
825 assert!(ledger.can_allocate(ResourceType::Memory, 1024));
826 assert!(ledger.can_allocate(ResourceType::Memory, 1 << 30));
827 assert!(!ledger.can_allocate(ResourceType::Memory, (1 << 30) + 1));
828 }
829
830 #[test]
831 fn test_nested_hierarchy() {
832 let mut root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));
833
834 root.create_child("domain_0", LedgerType::Domain, make_quota(1 << 24, 50_000, 5_000))
836 .unwrap();
837
838 root.get_child_mut("domain_0").unwrap()
840 .create_child("queue_0", LedgerType::Queue, make_quota(1 << 20, 10_000, 1_000))
841 .unwrap();
842
843 root.get_child_mut("domain_0").unwrap()
845 .get_child_mut("queue_0").unwrap()
846 .create_child("conn_0", LedgerType::Connection, make_quota(1 << 16, 100, 10))
847 .unwrap();
848
849 let conn = root.get_child("domain_0").unwrap()
851 .get_child("queue_0").unwrap()
852 .get_child("conn_0").unwrap();
853 assert_eq!(conn.depth(), 3);
854 assert_eq!(conn.ledger_type(), LedgerType::Connection);
855 assert_eq!(root.max_depth(), 3);
856 assert_eq!(root.node_count(), 4);
857
858 root.get_child_mut("domain_0").unwrap()
860 .get_child_mut("queue_0").unwrap()
861 .get_child_mut("conn_0").unwrap()
862 .allocate(ResourceType::Memory, 1024)
863 .unwrap();
864
865 assert_eq!(
866 root.get_child("domain_0").unwrap()
867 .get_child("queue_0").unwrap()
868 .get_child("conn_0").unwrap()
869 .used()
870 .memory_bytes,
871 1024
872 );
873 }
874
875 #[test]
876 fn test_remove_child_reclaims_quota() {
877 let mut root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));
878
879 root.create_child("domain_0", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000))
880 .unwrap();
881
882 root.get_child_mut("domain_0").unwrap()
884 .create_child("queue_0", LedgerType::Queue, make_quota(1 << 16, 1000, 100))
885 .unwrap();
886
887 root.get_child_mut("domain_0").unwrap()
888 .get_child_mut("queue_0").unwrap()
889 .allocate(ResourceType::Memory, 4096)
890 .unwrap();
891
892 let queue_used = root.get_child("domain_0").unwrap()
894 .get_child("queue_0").unwrap()
895 .used().memory_bytes;
896 assert_eq!(queue_used, 4096);
897
898 root.remove_child("domain_0").unwrap();
901
902 assert_eq!(root.child_count(), 0);
903 assert_eq!(root.allocated_to_children().memory_bytes, 0);
905 }
906
907 #[test]
908 fn test_remove_nonexistent_child() {
909 let mut root = ResourceLedger::root(make_quota(1 << 30, 0, 0));
910 let result = root.remove_child("nonexistent");
911 assert!(result.is_err());
912 }
913
914 #[test]
915 fn test_list_child_names() {
916 let mut root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));
917
918 root.create_child("domain_0", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000))
919 .unwrap();
920 root.create_child("domain_1", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000))
921 .unwrap();
922
923 let names: Vec<&str> = root.child_names().collect();
924 assert_eq!(names.len(), 2);
925 assert!(names.contains(&"domain_0"));
926 assert!(names.contains(&"domain_1"));
927 }
928
929 #[test]
930 fn test_allocations_accounted_in_parent() {
931 let mut root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));
932
933 root.create_child("domain_0", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000))
934 .unwrap();
935
936 root.get_child_mut("domain_0").unwrap()
938 .allocate(ResourceType::Memory, 8192)
939 .unwrap();
940
941 assert_eq!(root.get_child("domain_0").unwrap().used().memory_bytes, 8192);
943
944 let domain = root.get_child("domain_0").unwrap();
946 assert!(domain.can_allocate(ResourceType::Memory, (1 << 20) - 8192));
947 assert!(!domain.can_allocate(ResourceType::Memory, (1 << 20) - 8191));
948 }
949
950 #[test]
953 fn test_ledger_quota_zero() {
954 let q = LedgerQuota::zero();
955 assert_eq!(q.memory_bytes, 0);
956 assert_eq!(q.frame_count, 0);
957 assert_eq!(q.connection_count, 0);
958 }
959
960 #[test]
961 fn test_ledger_quota_unlimited() {
962 let q = LedgerQuota::unlimited();
963 assert_eq!(q.memory_bytes, u64::MAX);
964 assert_eq!(q.frame_count, u64::MAX);
965 assert_eq!(q.connection_count, u64::MAX);
966 }
967
968 #[test]
969 fn test_ledger_quota_can_allocate_memory() {
970 let parent = make_quota(1024, 0, 0);
971 let child_ok = make_quota(512, 0, 0);
972 let child_exceed = make_quota(2048, 0, 0);
973
974 assert!(parent.can_allocate(&child_ok).is_ok());
975 assert!(parent.can_allocate(&child_exceed).is_err());
976 }
977
978 #[test]
979 fn test_ledger_quota_can_allocate_frames() {
980 let parent = make_quota(0, 100, 0);
981 let child_ok = make_quota(0, 50, 0);
982 let child_exceed = make_quota(0, 200, 0);
983
984 assert!(parent.can_allocate(&child_ok).is_ok());
985 assert!(parent.can_allocate(&child_exceed).is_err());
986 }
987
988 #[test]
989 fn test_ledger_quota_can_allocate_connections() {
990 let parent = make_quota(0, 0, 10);
991 let child_ok = make_quota(0, 0, 5);
992 let child_exceed = make_quota(0, 0, 20);
993
994 assert!(parent.can_allocate(&child_ok).is_ok());
995 assert!(parent.can_allocate(&child_exceed).is_err());
996 }
997
998 #[test]
999 fn test_ledger_quota_can_allocate_exact() {
1000 let parent = make_quota(100, 200, 300);
1001 let child_exact = make_quota(100, 200, 300);
1002 assert!(parent.can_allocate(&child_exact).is_ok());
1003 }
1004
1005 #[test]
1006 fn test_ledger_quota_consume_and_restore() {
1007 let mut q = make_quota(1000, 100, 10);
1008
1009 q.consume(ResourceType::Memory, 500).unwrap();
1010 assert_eq!(q.memory_bytes, 500);
1011
1012 q.restore(ResourceType::Memory, 300).unwrap();
1013 assert_eq!(q.memory_bytes, 800);
1014 }
1015
1016 #[test]
1017 fn test_ledger_quota_consume_underflow() {
1018 let mut q = make_quota(100, 0, 0);
1019 let result = q.consume(ResourceType::Memory, 200);
1020 assert!(result.is_err());
1021 }
1022
1023 #[test]
1024 fn test_ledger_quota_restore_overflow() {
1025 let mut q = make_quota(u64::MAX, 0, 0);
1026 let result = q.restore(ResourceType::Memory, 1);
1027 assert!(result.is_err());
1028 }
1029
1030 #[test]
1031 fn test_ledger_quota_get() {
1032 let q = make_quota(10, 20, 30);
1033 assert_eq!(q.get(ResourceType::Memory), 10);
1034 assert_eq!(q.get(ResourceType::Frames), 20);
1035 assert_eq!(q.get(ResourceType::Connections), 30);
1036 }
1037
1038 #[test]
1039 fn test_ledger_quota_remaining() {
1040 let total = make_quota(1000, 100, 50);
1041 let used = make_quota(400, 30, 10);
1042 let remaining = total.remaining(&used);
1043 assert_eq!(remaining.memory_bytes, 600);
1044 assert_eq!(remaining.frame_count, 70);
1045 assert_eq!(remaining.connection_count, 40);
1046 }
1047
1048 #[test]
1049 fn test_ledger_quota_remaining_saturating() {
1050 let total = make_quota(100, 0, 0);
1051 let used = make_quota(200, 0, 0);
1052 let remaining = total.remaining(&used);
1053 assert_eq!(remaining.memory_bytes, 0);
1054 }
1055
1056 #[test]
1059 fn test_ledger_type_depth() {
1060 assert_eq!(LedgerType::Root.depth(), 0);
1061 assert_eq!(LedgerType::Domain.depth(), 1);
1062 assert_eq!(LedgerType::Queue.depth(), 2);
1063 assert_eq!(LedgerType::Connection.depth(), 3);
1064 }
1065
1066 #[test]
1067 fn test_ledger_type_equality() {
1068 assert_eq!(LedgerType::Root, LedgerType::Root);
1069 assert_ne!(LedgerType::Root, LedgerType::Domain);
1070 }
1071
1072 #[test]
1073 fn test_ledger_type_debug() {
1074 assert_eq!(format!("{:?}", LedgerType::Root), "Root");
1075 assert_eq!(format!("{:?}", LedgerType::Connection), "Connection");
1076 }
1077
1078 #[test]
1081 fn test_resource_type_name() {
1082 assert_eq!(ResourceType::Memory.name(), "memory");
1083 assert_eq!(ResourceType::Frames.name(), "frames");
1084 assert_eq!(ResourceType::Connections.name(), "connections");
1085 }
1086
1087 #[test]
1088 fn test_resource_type_equality() {
1089 assert_eq!(ResourceType::Memory, ResourceType::Memory);
1090 assert_ne!(ResourceType::Memory, ResourceType::Frames);
1091 }
1092
1093 #[test]
1094 fn test_resource_type_debug() {
1095 assert_eq!(format!("{:?}", ResourceType::Memory), "Memory");
1096 assert_eq!(format!("{:?}", ResourceType::Frames), "Frames");
1097 }
1098
1099 #[test]
1102 fn test_multiple_children_quota_sum() {
1103 let mut root = ResourceLedger::root(make_quota(10000, 1000, 100));
1104
1105 root.create_child("d0", LedgerType::Domain, make_quota(3000, 300, 30)).unwrap();
1106 root.create_child("d1", LedgerType::Domain, make_quota(2000, 200, 20)).unwrap();
1107 root.create_child("d2", LedgerType::Domain, make_quota(5000, 500, 50)).unwrap();
1108
1109 let allocated = root.allocated_to_children();
1110 assert_eq!(allocated.memory_bytes, 10000);
1111 assert_eq!(allocated.frame_count, 1000);
1112 assert_eq!(allocated.connection_count, 100);
1113 }
1114
1115 #[test]
1116 fn test_nested_three_level_quota_conservation() {
1117 let mut root = ResourceLedger::root(make_quota(10000, 1000, 100));
1118
1119 root.create_child("d0", LedgerType::Domain, make_quota(5000, 500, 50)).unwrap();
1120
1121 root.get_child_mut("d0").unwrap()
1122 .create_child("q0", LedgerType::Queue, make_quota(2000, 200, 20)).unwrap();
1123 root.get_child_mut("d0").unwrap()
1124 .create_child("q1", LedgerType::Queue, make_quota(3000, 300, 30)).unwrap();
1125
1126 let domain_allocated = root.get_child("d0").unwrap().allocated_to_children();
1127 assert_eq!(domain_allocated.memory_bytes, 5000);
1128 assert_eq!(domain_allocated.frame_count, 500);
1129 assert_eq!(domain_allocated.connection_count, 50);
1130
1131 let root_allocated = root.allocated_to_children();
1132 assert_eq!(root_allocated.memory_bytes, 5000);
1133 }
1134
1135 #[test]
1136 fn test_child_quota_exceeds_parent_total() {
1137 let mut root = ResourceLedger::root(make_quota(1000, 100, 10));
1138
1139 let result = root.create_child("big", LedgerType::Domain, make_quota(2000, 200, 20));
1140 assert!(result.is_err());
1141
1142 assert_eq!(root.child_count(), 0);
1143 assert_eq!(root.allocated_to_children().memory_bytes, 0);
1144 }
1145
1146 #[test]
1147 fn test_child_quota_exceeds_parent_used_remaining() {
1148 let mut root = ResourceLedger::root(make_quota(1000, 100, 10));
1149
1150 root.allocate(ResourceType::Memory, 600).unwrap();
1151 root.allocate(ResourceType::Frames, 60).unwrap();
1152 root.allocate(ResourceType::Connections, 6).unwrap();
1153
1154 let result = root.create_child("d0", LedgerType::Domain, make_quota(500, 50, 5));
1155 assert!(result.is_err());
1156
1157 assert_eq!(root.child_count(), 0);
1158 }
1159
1160 #[test]
1163 fn test_release_underflow_memory() {
1164 let mut ledger = ResourceLedger::new("test", LedgerType::Queue, make_quota(1000, 0, 0));
1165 ledger.allocate(ResourceType::Memory, 500).unwrap();
1166 ledger.release(ResourceType::Memory, 300).unwrap();
1167 assert_eq!(ledger.used().memory_bytes, 200);
1168 }
1169
1170 #[test]
1171 fn test_release_underflow_frames() {
1172 let mut ledger = ResourceLedger::new("test", LedgerType::Queue, make_quota(0, 100, 0));
1173 ledger.allocate(ResourceType::Frames, 50).unwrap();
1174 let result = ledger.release(ResourceType::Frames, 100);
1175 assert!(result.is_err());
1176 }
1177
1178 #[test]
1179 fn test_release_underflow_connections() {
1180 let mut ledger = ResourceLedger::new("test", LedgerType::Queue, make_quota(0, 0, 10));
1181 let result = ledger.release(ResourceType::Connections, 1);
1182 assert!(result.is_err());
1183 }
1184
1185 #[test]
1188 fn test_allocated_to_children_after_remove() {
1189 let mut root = ResourceLedger::root(make_quota(10000, 1000, 100));
1190
1191 root.create_child("d0", LedgerType::Domain, make_quota(3000, 300, 30)).unwrap();
1192 root.create_child("d1", LedgerType::Domain, make_quota(2000, 200, 20)).unwrap();
1193
1194 assert_eq!(root.allocated_to_children().memory_bytes, 5000);
1195 assert_eq!(root.allocated_to_children().frame_count, 500);
1196 assert_eq!(root.allocated_to_children().connection_count, 50);
1197
1198 root.remove_child("d0").unwrap();
1199
1200 assert_eq!(root.allocated_to_children().memory_bytes, 2000);
1201 assert_eq!(root.allocated_to_children().frame_count, 200);
1202 assert_eq!(root.allocated_to_children().connection_count, 20);
1203 }
1204
1205 #[test]
1206 fn test_allocated_to_children_zero_initially() {
1207 let root = ResourceLedger::root(make_quota(1000, 100, 10));
1208 assert_eq!(root.allocated_to_children().memory_bytes, 0);
1209 assert_eq!(root.allocated_to_children().frame_count, 0);
1210 assert_eq!(root.allocated_to_children().connection_count, 0);
1211 }
1212
1213 #[test]
1216 fn test_ledger_quota_default() {
1217 let q = LedgerQuota::default();
1218 assert_eq!(q.memory_bytes, 0);
1219 assert_eq!(q.frame_count, 0);
1220 assert_eq!(q.connection_count, 0);
1221 }
1222
1223 #[test]
1226 fn test_ledger_remaining() {
1227 let mut ledger = ResourceLedger::new("test", LedgerType::Queue, make_quota(1000, 100, 10));
1228 ledger.allocate(ResourceType::Memory, 400).unwrap();
1229 ledger.allocate(ResourceType::Frames, 30).unwrap();
1230 ledger.allocate(ResourceType::Connections, 5).unwrap();
1231
1232 let remaining = ledger.remaining();
1233 assert_eq!(remaining.memory_bytes, 600);
1234 assert_eq!(remaining.frame_count, 70);
1235 assert_eq!(remaining.connection_count, 5);
1236 }
1237
1238 #[test]
1241 fn test_four_level_hierarchy_allocated_to_children() {
1242 let mut root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));
1243
1244 root.create_child("d0", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000)).unwrap();
1245
1246 root.get_child_mut("d0").unwrap()
1247 .create_child("q0", LedgerType::Queue, make_quota(1 << 15, 1_000, 100)).unwrap();
1248
1249 root.get_child_mut("d0").unwrap().get_child_mut("q0").unwrap()
1250 .create_child("c0", LedgerType::Connection, make_quota(1 << 10, 100, 10)).unwrap();
1251
1252 assert_eq!(root.max_depth(), 3);
1253 assert_eq!(root.node_count(), 4);
1254
1255 let conn = root.get_child("d0").unwrap().get_child("q0").unwrap().get_child("c0").unwrap();
1256 assert_eq!(conn.ledger_type(), LedgerType::Connection);
1257 assert_eq!(conn.depth(), 3);
1258 }
1259
1260 #[test]
1263 fn test_create_child_oversubscription_rejected() {
1264 let mut root = ResourceLedger::root(make_quota(1000, 100, 10));
1265
1266 root.create_child("c1", LedgerType::Domain, make_quota(600, 60, 6)).unwrap();
1268 let result = root.create_child("c2", LedgerType::Domain, make_quota(600, 0, 0));
1270 assert!(result.is_err());
1271 assert_eq!(root.child_count(), 1);
1272
1273 root.create_child("c2", LedgerType::Domain, make_quota(400, 40, 4)).unwrap();
1275 assert_eq!(root.child_count(), 2);
1276 assert_eq!(root.allocated_to_children().memory_bytes, 1000);
1277
1278 assert!(root.create_child("c3", LedgerType::Domain, make_quota(1, 0, 0)).is_err());
1280 }
1281
1282 #[test]
1283 fn test_create_child_accounts_parent_used() {
1284 let mut root = ResourceLedger::root(make_quota(1000, 0, 0));
1285
1286 root.allocate(ResourceType::Memory, 400).unwrap();
1288 root.create_child("c1", LedgerType::Domain, make_quota(600, 0, 0)).unwrap();
1289 assert!(root.create_child("c2", LedgerType::Domain, make_quota(1, 0, 0)).is_err());
1290 }
1291
1292 #[test]
1295 fn test_allocate_in_child_rolls_up_to_ancestors() {
1296 let mut root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));
1297 root.create_child("d0", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000)).unwrap();
1298 root.get_child_mut("d0").unwrap()
1299 .create_child("q0", LedgerType::Queue, make_quota(1 << 15, 1_000, 100)).unwrap();
1300
1301 root.allocate_in_child(&["d0", "q0"], ResourceType::Memory, 1024).unwrap();
1303
1304 assert_eq!(root.used().memory_bytes, 1024);
1305 assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 1024);
1306 assert_eq!(
1307 root.get_child("d0").unwrap().get_child("q0").unwrap().used().memory_bytes,
1308 1024
1309 );
1310
1311 root.release_in_child(&["d0", "q0"], ResourceType::Memory, 1024).unwrap();
1313 assert_eq!(root.used().memory_bytes, 0);
1314 assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 0);
1315 assert_eq!(
1316 root.get_child("d0").unwrap().get_child("q0").unwrap().used().memory_bytes,
1317 0
1318 );
1319 }
1320
1321 #[test]
1322 fn test_allocate_in_child_ancestor_quota_enforced() {
1323 let mut root = ResourceLedger::root(make_quota(1000, 0, 0));
1324 root.create_child("d0", LedgerType::Domain, make_quota(500, 0, 0)).unwrap();
1325
1326 assert!(root.allocate(ResourceType::Memory, 600).is_err());
1329 root.allocate(ResourceType::Memory, 500).unwrap();
1331
1332 root.allocate_in_child(&["d0"], ResourceType::Memory, 500).unwrap();
1334 assert_eq!(root.used().memory_bytes, 1000);
1335 assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 500);
1336
1337 let result = root.allocate_in_child(&["d0"], ResourceType::Memory, 100);
1339 assert!(result.is_err());
1340 assert_eq!(root.used().memory_bytes, 1000);
1341 assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 500);
1342 }
1343
1344 #[test]
1345 fn test_allocate_in_child_rollback_on_descendant_failure() {
1346 let mut root = ResourceLedger::root(make_quota(1000, 0, 0));
1347 root.create_child("d0", LedgerType::Domain, make_quota(500, 0, 0)).unwrap();
1348
1349 let result = root.allocate_in_child(&["d0"], ResourceType::Memory, 600);
1351 assert!(result.is_err());
1352 assert_eq!(root.used().memory_bytes, 0);
1353 assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 0);
1354 }
1355
1356 #[test]
1359 fn test_allocate_not_double_counted_with_child_usage() {
1360 let mut root = ResourceLedger::root(make_quota(1000, 0, 0));
1361 root.create_child("d0", LedgerType::Domain, make_quota(500, 0, 0)).unwrap();
1362
1363 root.allocate_in_child(&["d0"], ResourceType::Memory, 200).unwrap();
1365 assert_eq!(root.used().memory_bytes, 200);
1366 assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 200);
1367
1368 root.allocate(ResourceType::Memory, 400).unwrap();
1372
1373 assert_eq!(root.used().memory_bytes, 600);
1374 assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 200);
1375 assert_eq!(root.remaining().memory_bytes, 400);
1377 }
1378
1379 #[test]
1380 fn test_allocate_in_child_rollback_does_not_touch_used_direct() {
1381 let mut root = ResourceLedger::root(make_quota(1000, 0, 0));
1382 root.create_child("d0", LedgerType::Domain, make_quota(500, 0, 0)).unwrap();
1383
1384 root.allocate(ResourceType::Memory, 300).unwrap();
1387 let result = root.allocate_in_child(&["d0"], ResourceType::Memory, 600);
1388 assert!(result.is_err());
1389 assert_eq!(root.used().memory_bytes, 300);
1391 }
1392
1393 #[test]
1394 fn test_allocate_in_child_unknown_path() {
1395 let mut root = ResourceLedger::root(make_quota(1000, 0, 0));
1396 root.create_child("d0", LedgerType::Domain, make_quota(500, 0, 0)).unwrap();
1397
1398 assert!(root.allocate_in_child(&["nope"], ResourceType::Memory, 100).is_err());
1400 assert!(root.allocate_in_child(&["d0", "nope"], ResourceType::Memory, 100).is_err());
1401 assert_eq!(root.used().memory_bytes, 0);
1402 assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 0);
1403 }
1404
1405 #[test]
1406 fn test_release_in_child_restores_on_descendant_failure() {
1407 let mut root = ResourceLedger::root(make_quota(1000, 0, 0));
1408 root.create_child("d0", LedgerType::Domain, make_quota(500, 0, 0)).unwrap();
1409
1410 root.allocate_in_child(&["d0"], ResourceType::Memory, 200).unwrap();
1411
1412 let result = root.release_in_child(&["d0"], ResourceType::Memory, 300);
1414 assert!(result.is_err());
1415 assert_eq!(root.used().memory_bytes, 200);
1416 assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 200);
1417
1418 root.release_in_child(&["d0"], ResourceType::Memory, 200).unwrap();
1420 assert_eq!(root.used().memory_bytes, 0);
1421 }
1422
1423 #[test]
1424 fn test_remove_child_reclaims_rolled_up_usage() {
1425 let mut root = ResourceLedger::root(make_quota(1000, 100, 10));
1426 root.create_child("d0", LedgerType::Domain, make_quota(500, 50, 5)).unwrap();
1427
1428 root.allocate_in_child(&["d0"], ResourceType::Memory, 200).unwrap();
1430 assert_eq!(root.used().memory_bytes, 200);
1431
1432 root.remove_child("d0").unwrap();
1434 assert_eq!(root.used().memory_bytes, 0);
1435 assert_eq!(root.allocated_to_children().memory_bytes, 0);
1436
1437 root.create_child("d1", LedgerType::Domain, make_quota(1000, 100, 10)).unwrap();
1439 }
1440}