qualia_core_db/net/peer/connectivity/
state.rs1#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum ConnState {
6 Admitted,
7 Establishing,
8 CarrierReady,
9 SessionReady,
10 Upgrading,
11 Degraded,
12 Deferred,
13 Closed,
14}
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum ConnError {
18 IllegalTransition,
19 StaleGeneration,
20 PolicyDenied,
21 Capacity,
22 Expired,
23}
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub struct ConnSlot {
28 pub attempt: u32,
29 pub generation: u32,
30 pub state: ConnState,
31}
32
33impl ConnSlot {
34 pub const fn new(attempt: u32) -> Self {
36 Self {
37 attempt,
38 generation: 1,
39 state: ConnState::Admitted,
40 }
41 }
42
43 pub fn restart(&mut self) {
45 self.generation = self.generation.wrapping_add(1);
46 if self.generation == 0 {
47 self.generation = 1;
48 }
49 self.state = ConnState::Admitted;
50 }
51
52 fn allow(from: ConnState, to: ConnState) -> bool {
53 use ConnState::*;
54 matches!(
55 (from, to),
56 (Admitted, Establishing)
57 | (Admitted, Deferred)
58 | (Admitted, Closed)
59 | (Establishing, CarrierReady)
60 | (Establishing, Deferred)
61 | (Establishing, Closed)
62 | (CarrierReady, SessionReady)
63 | (CarrierReady, Degraded)
64 | (CarrierReady, Closed)
65 | (SessionReady, Upgrading)
66 | (SessionReady, Degraded)
67 | (SessionReady, Closed)
68 | (Upgrading, SessionReady)
69 | (Upgrading, Degraded)
70 | (Upgrading, Closed)
71 | (Degraded, Establishing)
72 | (Degraded, Deferred)
73 | (Degraded, Closed)
74 | (Deferred, Establishing)
75 | (Deferred, Closed)
76 )
77 }
78
79 pub fn transition(&mut self, gen: u32, to: ConnState) -> Result<(), ConnError> {
81 if gen != self.generation {
82 return Err(ConnError::StaleGeneration);
83 }
84 if self.state == to {
85 return Ok(());
86 }
87 if !Self::allow(self.state, to) {
88 return Err(ConnError::IllegalTransition);
89 }
90 self.state = to;
91 Ok(())
92 }
93}
94
95#[cfg(test)]
96mod tests {
97 use super::*;
98
99 #[test]
100 fn stale_generation_rejected() {
101 let mut s = ConnSlot::new(1);
102 s.transition(1, ConnState::Establishing).unwrap();
103 s.restart();
104 assert_eq!(
105 s.transition(1, ConnState::CarrierReady),
106 Err(ConnError::StaleGeneration)
107 );
108 s.transition(s.generation, ConnState::Establishing).unwrap();
109 }
110
111 #[test]
112 fn session_ready_skips_establishing() {
113 let mut s = ConnSlot::new(1);
114 assert_eq!(
115 s.transition(1, ConnState::SessionReady),
116 Err(ConnError::IllegalTransition)
117 );
118 }
119}