qualia_core_db/net/peer/fabric/
lease.rs1use super::intent::PeerId;
4
5pub const MAX_LEASES: usize = 8;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub struct RelayLease {
9 pub lease_id: u64,
10 pub operator: u64,
11 pub participants: [PeerId; 2],
12 pub max_bytes: u64,
13 pub remaining_bytes: u64,
14 pub expiry_ms: u64,
15 pub generation: u32,
16 pub cancelled: bool,
17 pub export_observations: bool,
19}
20
21impl RelayLease {
22 pub const fn grant(
24 lease_id: u64,
25 operator: u64,
26 a: PeerId,
27 b: PeerId,
28 max_bytes: u64,
29 expiry_ms: u64,
30 generation: u32,
31 export_observations: bool,
32 ) -> Self {
33 Self {
34 lease_id,
35 operator,
36 participants: [a, b],
37 max_bytes,
38 remaining_bytes: max_bytes,
39 expiry_ms,
40 generation,
41 cancelled: false,
42 export_observations,
43 }
44 }
45
46 pub const fn live(&self, now_ms: u64) -> bool {
48 !self.cancelled && now_ms < self.expiry_ms && self.remaining_bytes > 0
49 }
50
51 pub fn admits(&self, from: &PeerId, to: &PeerId) -> bool {
53 (from == &self.participants[0] && to == &self.participants[1])
54 || (from == &self.participants[1] && to == &self.participants[0])
55 }
56
57 pub fn charge(&mut self, n: u64, now_ms: u64) -> Result<(), ()> {
59 if !self.live(now_ms) || n > self.remaining_bytes {
60 return Err(());
61 }
62 self.remaining_bytes -= n;
63 Ok(())
64 }
65
66 pub fn cancel(&mut self) {
68 self.cancelled = true;
69 self.remaining_bytes = 0;
70 }
71}
72
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub struct CustodyLease {
76 pub lease_id: u64,
77 pub operator: u64,
78 pub expiry_unix: u32,
79 pub max_objects: u16,
80 pub held: u16,
81 pub cancelled: bool,
82}
83
84impl CustodyLease {
85 pub const fn grant(lease_id: u64, operator: u64, expiry_unix: u32, max_objects: u16) -> Self {
87 Self {
88 lease_id,
89 operator,
90 expiry_unix,
91 max_objects,
92 held: 0,
93 cancelled: false,
94 }
95 }
96
97 pub const fn live(&self, now_unix: u32) -> bool {
99 !self.cancelled && now_unix < self.expiry_unix && self.held < self.max_objects
100 }
101}
102
103#[cfg(test)]
104mod tests {
105 use super::*;
106
107 #[test]
108 fn charge_stops_at_cap_and_expiry() {
109 let mut l = RelayLease::grant(1, 9, [1u8; 32], [2u8; 32], 10, 100, 1, false);
110 assert!(l.charge(8, 10).is_ok());
111 assert!(l.charge(3, 10).is_err());
112 assert_eq!(l.remaining_bytes, 2);
113 l.remaining_bytes = 10;
114 assert!(l.charge(1, 100).is_err());
115 l.expiry_ms = 200;
116 l.cancel();
117 assert!(l.charge(1, 10).is_err());
118 }
119
120 #[test]
121 fn custody_is_not_a_relay_budget() {
122 let c = CustodyLease::grant(2, 9, 50, 4);
123 assert!(c.live(10));
124 assert_ne!(
125 core::mem::size_of::<CustodyLease>(),
126 0,
127 "distinct type from RelayLease"
128 );
129 }
130}