qualia_core_db/sensing/local_custody/quota/
recovery.rs1use super::{CustodyQuota, QuotaError};
5use core::sync::atomic::{AtomicUsize, Ordering};
6use std::path::Path;
7static NEXT_OWNER: AtomicUsize = AtomicUsize::new(1);
8pub(super) fn next_recovery_owner() -> Result<usize, QuotaError> {
9 NEXT_OWNER
10 .try_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_add(1))
11 .map_err(|_| QuotaError::Overflow)
12}
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub(crate) struct RecoveryScopeKey {
15 owner: usize,
16 serial: u64,
17}
18#[derive(Debug)]
19pub struct RecoveryRootScope<'root> {
20 root: &'root Path,
21 snapshot: [u8; 32],
22 key: RecoveryScopeKey,
23}
24impl<'root> RecoveryRootScope<'root> {
25 pub const fn snapshot_id(&self) -> [u8; 32] {
26 self.snapshot
27 }
28 pub(crate) const fn root(&self) -> &'root Path {
29 self.root
30 }
31 pub(crate) const fn key(&self) -> RecoveryScopeKey {
32 self.key
33 }
34}
35impl<'root, const N: usize> CustodyQuota<'root, N> {
36 pub fn recovery_root_scope(&mut self) -> Result<RecoveryRootScope<'root>, QuotaError> {
39 let serial = self
40 .recovery_scope_serial
41 .checked_add(1)
42 .ok_or(QuotaError::Overflow)?;
43 self.recovery_scope_serial = serial;
44 Ok(RecoveryRootScope {
45 root: self.root,
46 snapshot: self.usage.id,
47 key: RecoveryScopeKey {
48 owner: self.recovery_owner,
49 serial,
50 },
51 })
52 }
53}
54
55#[cfg(test)]
56mod tests {
57 use super::*;
58 use crate::sensing::local_custody::quota::{
59 QuotaLimits, QuotaSnapshot, QuotaSnapshotAuthority,
60 };
61 struct Snapshot;
62 impl QuotaSnapshotAuthority for Snapshot {
63 fn admit_usage(&self, _: &Path, _: QuotaLimits, s: QuotaSnapshot) -> bool {
64 s.id == [1; 32]
65 }
66 }
67 #[test]
68 fn scopes_are_distinct_noncopy_provenance_without_usage_or_mutable_borrow() {
69 let root = tempfile::tempdir().unwrap();
70 let mut quota = CustodyQuota::<4>::from_authenticated_usage(
71 root.path(),
72 QuotaLimits {
73 encoded_bytes: 100,
74 entries: 4,
75 },
76 QuotaSnapshot {
77 id: [1; 32],
78 encoded_bytes: 10,
79 entries: 1,
80 },
81 &Snapshot,
82 )
83 .unwrap();
84 let first = quota.recovery_root_scope().unwrap();
85 let second = quota.recovery_root_scope().unwrap();
86 assert_ne!(first.key(), second.key());
87 assert_eq!(first.snapshot_id(), [1; 32]);
88 assert_eq!(quota.charged_usage(), (10, 1));
89 let token = quota.admit_staging([2; 32], 20).unwrap();
90 drop(token);
91 assert_eq!(quota.charged_usage(), (30, 2));
92 assert_eq!(first.root(), root.path());
93 let before = second.key();
94 quota.recovery_scope_serial = u64::MAX;
95 assert!(matches!(
96 quota.recovery_root_scope(),
97 Err(QuotaError::Overflow)
98 ));
99 assert_eq!(second.key(), before);
100 assert_eq!(quota.charged_usage(), (30, 2));
101 }
102}