Skip to main content

qualia_core_db/net/peer/runtime/
leases.rs

1//! Exclusive buffer leases with double-release and stale-generation rejection.
2
3use crate::net::qdnf::errors::QdnfError;
4use crate::net::qdnf::types::Generation;
5
6use super::handles::{BufferLease, LeaseHandle};
7
8pub const LEASE_SLOTS: usize = 32;
9mod incarnation;
10mod inspect;
11
12#[derive(Clone, Copy)]
13struct Slot {
14    generation: Generation,
15    occupied: bool,
16    exclusive: bool,
17    capacity: u32,
18}
19
20pub struct LeaseTable {
21    incarnation: super::incarnation::CanonicalIncarnation,
22    slots: [Slot; LEASE_SLOTS],
23}
24
25impl LeaseTable {
26    /// Creates a default `LeaseTable`.
27    pub const fn new() -> Self {
28        Self {
29            incarnation: super::incarnation::CanonicalIncarnation::UNASSIGNED,
30            slots: [Slot {
31                generation: Generation::ZERO,
32                occupied: false,
33                exclusive: false,
34                capacity: 0,
35            }; LEASE_SLOTS],
36        }
37    }
38
39    /// Acquires the resource.
40    pub fn acquire(&mut self, capacity: u32, exclusive: bool) -> Result<BufferLease, QdnfError> {
41        let mut exhausted = false;
42        for i in 0..LEASE_SLOTS {
43            if self.slots[i].occupied {
44                continue;
45            }
46            match self.try_acquire_slot(i, capacity, exclusive) {
47                Ok(lease) => return Ok(lease),
48                Err(QdnfError::StaleGeneration) => {
49                    exhausted = true;
50                    continue;
51                }
52                Err(e) => return Err(e),
53            }
54        }
55        if exhausted {
56            Err(QdnfError::StaleGeneration)
57        } else {
58            Err(QdnfError::Capacity)
59        }
60    }
61
62    /// Acquire a specific free slot. Generation `u64::MAX` fails closed; it never wraps.
63    pub fn try_acquire_slot(
64        &mut self,
65        slot: usize,
66        capacity: u32,
67        exclusive: bool,
68    ) -> Result<BufferLease, QdnfError> {
69        if slot >= LEASE_SLOTS {
70            return Err(QdnfError::Range);
71        }
72        let cell = &mut self.slots[slot];
73        if cell.occupied {
74            return Err(QdnfError::Conflict);
75        }
76        let generation = cell.generation.next()?;
77        *cell = Slot {
78            generation,
79            occupied: true,
80            exclusive,
81            capacity,
82        };
83        Ok(BufferLease {
84            handle: LeaseHandle {
85                slot: slot as u16,
86                generation,
87            },
88            capacity,
89            initialized: 0,
90            exclusive,
91        })
92    }
93
94    /// Releases the resource.
95    pub fn release(&mut self, handle: LeaseHandle) -> Result<(), QdnfError> {
96        let idx = handle.slot as usize;
97        if idx >= LEASE_SLOTS {
98            return Err(QdnfError::Range);
99        }
100        let slot = &mut self.slots[idx];
101        if slot.generation != handle.generation {
102            return Err(QdnfError::StaleGeneration);
103        }
104        if !slot.occupied {
105            return Err(QdnfError::DoubleRelease);
106        }
107        let _ = (slot.exclusive, slot.capacity);
108        slot.occupied = false;
109        slot.capacity = 0;
110        slot.exclusive = false;
111        Ok(())
112    }
113
114    /// `occupied` count.
115    pub fn occupied_count(&self) -> usize {
116        let mut n = 0;
117        for slot in &self.slots {
118            if slot.occupied {
119                n += 1;
120            }
121        }
122        n
123    }
124
125    #[cfg(test)]
126    /// `LeaseTable::debug_set_generation`.
127    pub(crate) fn debug_set_generation(&mut self, slot: usize, generation: Generation) {
128        debug_assert!(slot < LEASE_SLOTS);
129        debug_assert!(!self.slots[slot].occupied);
130        self.slots[slot].generation = generation;
131    }
132}
133
134impl Default for LeaseTable {
135    fn default() -> Self {
136        Self::new()
137    }
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143
144    #[test]
145    fn double_release_fails() {
146        let mut table = LeaseTable::new();
147        let lease = table.acquire(64, true).unwrap();
148        table.release(lease.handle).unwrap();
149        assert_eq!(table.release(lease.handle), Err(QdnfError::DoubleRelease));
150    }
151
152    #[test]
153    fn thirty_third_acquire_is_capacity() {
154        let mut table = LeaseTable::new();
155        for _ in 0..LEASE_SLOTS {
156            table.acquire(8, true).unwrap();
157        }
158        assert_eq!(table.occupied_count(), LEASE_SLOTS);
159        assert_eq!(table.acquire(8, true), Err(QdnfError::Capacity));
160    }
161}