Skip to main content

qualia_core_db/net/peer/host/
session_table.rs

1//! Bounded session table. Multiple live sessions; close releases the ledger handle.
2
3use crate::net::peer::runtime::{ReservationHandle, ReservationLedger};
4use crate::net::qdnf::errors::QdnfError;
5use crate::net::qdnf::session::congestion::{PathCcTable, INITIAL_WINDOW_BYTES};
6use crate::net::qdnf::session::paths::{PathHandle, PathTable};
7use crate::net::qdnf::session::streams::StreamFrame;
8use crate::net::qdnf::session::{ProtectedAckSession, SessionBinding, StreamState};
9use crate::net::qdnf::types::Generation;
10
11/// Occupied application sessions per peer. A fifth insert is [`QdnfError::Capacity`].
12pub const MAX_SESSIONS: usize = 4;
13
14/// Copyable slot+generation index. The table owns the reservation handle.
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub struct SessionHandle {
17    slot: u8,
18    generation: Generation,
19}
20
21impl SessionHandle {
22    #[inline]
23    /// Generation.
24    pub const fn generation(self) -> Generation {
25        self.generation
26    }
27
28    #[inline]
29    /// Slot.
30    pub const fn slot(self) -> u8 {
31        self.slot
32    }
33}
34
35struct SessionSlot {
36    generation: Generation,
37    binding: Option<SessionBinding>,
38    protection: Option<ProtectedAckSession>,
39    reservation: Option<ReservationHandle>,
40    stream: StreamState,
41}
42
43impl SessionSlot {
44    const fn empty() -> Self {
45        Self {
46            generation: Generation::ZERO,
47            binding: None,
48            protection: None,
49            reservation: None,
50            stream: StreamState::new(),
51        }
52    }
53
54    fn occupied(&self) -> bool {
55        self.protection.is_some() && self.reservation.is_some()
56    }
57}
58
59pub struct SessionTable {
60    slots: [SessionSlot; MAX_SESSIONS],
61    pub(crate) paths: PathTable,
62    pub(crate) path_cc: PathCcTable,
63    pub(crate) primary_path: Option<PathHandle>,
64}
65
66impl SessionTable {
67    /// Creates a default `SessionTable`.
68    pub const fn new() -> Self {
69        Self {
70            slots: [
71                SessionSlot::empty(),
72                SessionSlot::empty(),
73                SessionSlot::empty(),
74                SessionSlot::empty(),
75            ],
76            paths: PathTable::new(),
77            path_cc: PathCcTable::new(INITIAL_WINDOW_BYTES),
78            primary_path: None,
79        }
80    }
81
82    /// Live sessions.
83    pub fn live_count(&self) -> usize {
84        let mut n = 0usize;
85        let mut i = 0usize;
86        while i < MAX_SESSIONS {
87            if self.slots[i].occupied() {
88                n = n.saturating_add(1);
89            }
90            i = i.saturating_add(1);
91        }
92        n
93    }
94
95    #[inline]
96    /// `true` when full.
97    pub fn is_full(&self) -> bool {
98        self.live_count() >= MAX_SESSIONS
99    }
100
101    /// `SessionTable::first_live`.
102    pub fn first_live(&self) -> Option<SessionHandle> {
103        let mut i = 0usize;
104        while i < MAX_SESSIONS {
105            if self.slots[i].occupied() {
106                return Some(SessionHandle {
107                    slot: i as u8,
108                    generation: self.slots[i].generation,
109                });
110            }
111            i = i.saturating_add(1);
112        }
113        None
114    }
115
116    /// First free slot; error when full.
117    pub(crate) fn free_index(&self) -> Result<usize, QdnfError> {
118        let mut i = 0usize;
119        while i < MAX_SESSIONS {
120            if !self.slots[i].occupied() {
121                return Ok(i);
122            }
123            i = i.saturating_add(1);
124        }
125        Err(QdnfError::Capacity)
126    }
127
128    fn slot_mut(&mut self, h: SessionHandle) -> Result<&mut SessionSlot, QdnfError> {
129        let i = h.slot as usize;
130        if i >= MAX_SESSIONS {
131            return Err(QdnfError::Range);
132        }
133        let slot = &mut self.slots[i];
134        if !slot.occupied() {
135            return Err(QdnfError::Closed);
136        }
137        if slot.generation != h.generation {
138            return Err(QdnfError::StaleGeneration);
139        }
140        Ok(slot)
141    }
142
143    fn slot(&self, h: SessionHandle) -> Result<&SessionSlot, QdnfError> {
144        let i = h.slot as usize;
145        if i >= MAX_SESSIONS {
146            return Err(QdnfError::Range);
147        }
148        let slot = &self.slots[i];
149        if !slot.occupied() {
150            return Err(QdnfError::Closed);
151        }
152        if slot.generation != h.generation {
153            return Err(QdnfError::StaleGeneration);
154        }
155        Ok(slot)
156    }
157
158    /// Occupies one vacancy. Caller must [`Self::is_full`] before reserving so a
159    /// rejected insert cannot drop an unreleased handle.
160    pub fn insert(
161        &mut self,
162        binding: SessionBinding,
163        protection: ProtectedAckSession,
164        reservation: ReservationHandle,
165    ) -> Result<SessionHandle, QdnfError> {
166        let i = self.free_index()?;
167        let generation = self.slots[i].generation.next()?;
168        self.slots[i] = SessionSlot {
169            generation,
170            binding: Some(binding),
171            protection: Some(protection),
172            reservation: Some(reservation),
173            stream: StreamState::new(),
174        };
175        Ok(SessionHandle {
176            slot: i as u8,
177            generation,
178        })
179    }
180
181    /// Mutable session for `h`; error on stale handle.
182    pub fn get_mut(&mut self, h: SessionHandle) -> Result<&mut ProtectedAckSession, QdnfError> {
183        self.slot_mut(h)?
184            .protection
185            .as_mut()
186            .ok_or(QdnfError::Unauthorized)
187    }
188
189    /// Session binding for `h`.
190    pub fn binding(&self, h: SessionHandle) -> Result<SessionBinding, QdnfError> {
191        self.slot(h)?.binding.ok_or(QdnfError::Unauthorized)
192    }
193
194    /// Advance the application send offset only after the bearer accepted the frame.
195    pub fn commit_send_offset(
196        &mut self,
197        h: SessionHandle,
198        payload_len: u16,
199    ) -> Result<u64, QdnfError> {
200        let slot = self.slot_mut(h)?;
201        let offset = slot.stream.next_offset;
202        slot.stream.accept(StreamFrame {
203            stream_id: 0,
204            offset,
205            fin: false,
206            declared_final: None,
207            len: payload_len,
208        })?;
209        Ok(slot.stream.next_offset)
210    }
211
212    /// Current send offset for `h`.
213    pub fn send_offset(&self, h: SessionHandle) -> Result<u64, QdnfError> {
214        Ok(self.slot(h)?.stream.next_offset)
215    }
216
217    /// Handle-based release. Does not accept caller-supplied byte amounts.
218    pub fn close(
219        &mut self,
220        h: SessionHandle,
221        ledger: &mut ReservationLedger,
222    ) -> Result<(), QdnfError> {
223        let i = h.slot as usize;
224        if i >= MAX_SESSIONS {
225            return Err(QdnfError::Range);
226        }
227        if !self.slots[i].occupied() {
228            return Err(QdnfError::Closed);
229        }
230        if self.slots[i].generation != h.generation {
231            return Err(QdnfError::StaleGeneration);
232        }
233        let reservation = self.slots[i].reservation.take().ok_or(QdnfError::Closed)?;
234        ledger.release(reservation)?;
235        let keep = self.slots[i].generation;
236        self.slots[i] = SessionSlot::empty();
237        self.slots[i].generation = keep;
238        Ok(())
239    }
240}
241
242impl Default for SessionTable {
243    fn default() -> Self {
244        Self::new()
245    }
246}
247
248#[cfg(test)]
249mod tests {
250    use super::*;
251    use crate::net::peer::runtime::ResourceBudget;
252    use crate::net::qdnf::authority::PolicyOutcome;
253    use crate::net::qdnf::session::SessionState;
254    use crate::net::qdnf::types::{OperationId, StrongDigest};
255
256    fn ledger() -> ReservationLedger {
257        let cap = ResourceBudget {
258            bytes: 1024,
259            work: 16,
260            io: 16,
261        };
262        ReservationLedger::new(cap, cap, cap, cap, cap)
263    }
264
265    fn charge() -> ResourceBudget {
266        ResourceBudget {
267            bytes: 256,
268            work: 1,
269            io: 1,
270        }
271    }
272
273    fn binding() -> SessionBinding {
274        SessionBinding::test_fixture(
275            OperationId([1u8; 16]),
276            StrongDigest([2u8; 48]),
277            StrongDigest([3u8; 48]),
278            StrongDigest([4u8; 48]),
279            PolicyOutcome::Allow,
280            SessionState::Active,
281        )
282    }
283
284    fn protection(tag: u8) -> ProtectedAckSession {
285        let mut send = [tag; 32];
286        let mut recv = [tag.wrapping_add(1); 32];
287        send[0] = tag.max(1);
288        recv[0] = tag.wrapping_add(40).max(2);
289        ProtectedAckSession::from_keys(send, recv, Generation(1)).unwrap()
290    }
291
292    #[test]
293    fn two_sessions_live_close_one_keeps_the_other() {
294        let mut table = SessionTable::new();
295        let mut ledger = ledger();
296        let h1 = table
297            .insert(
298                binding(),
299                protection(1),
300                ledger.reserve(charge(), true).unwrap(),
301            )
302            .unwrap();
303        let h2 = table
304            .insert(
305                binding(),
306                protection(2),
307                ledger.reserve(charge(), true).unwrap(),
308            )
309            .unwrap();
310        assert_eq!(table.live_count(), 2);
311        assert!(table.get_mut(h1).is_ok());
312        assert!(table.get_mut(h2).is_ok());
313        let h3 = table
314            .insert(
315                binding(),
316                protection(3),
317                ledger.reserve(charge(), true).unwrap(),
318            )
319            .unwrap();
320        let h4 = table
321            .insert(
322                binding(),
323                protection(4),
324                ledger.reserve(charge(), true).unwrap(),
325            )
326            .unwrap();
327        assert_eq!(table.live_count(), MAX_SESSIONS);
328        assert!(table.is_full());
329        assert_eq!(table.free_index(), Err(QdnfError::Capacity));
330        table.close(h1, &mut ledger).unwrap();
331        assert_eq!(table.live_count(), 3);
332        assert_eq!(table.get_mut(h1).err(), Some(QdnfError::Closed));
333        assert!(table.get_mut(h2).is_ok());
334        assert!(table.get_mut(h3).is_ok());
335        assert!(table.get_mut(h4).is_ok());
336    }
337
338    #[test]
339    fn close_releases_ledger_budget() {
340        let mut table = SessionTable::new();
341        let mut ledger = ledger();
342        let before = ledger.host_remaining_bytes();
343        let h = table
344            .insert(
345                binding(),
346                protection(1),
347                ledger.reserve(charge(), true).unwrap(),
348            )
349            .unwrap();
350        assert!(ledger.host_remaining_bytes() < before);
351        table.close(h, &mut ledger).unwrap();
352        assert_eq!(ledger.host_remaining_bytes(), before);
353    }
354}