Skip to main content

qualia_core_db/net/peer/connectivity/
planner.rs

1//! Scheduler: race permitted paths. Relay is eligible immediately.
2
3use super::candidates::{gather_permitted, AddrFamily, CandidateKind, CandidateTables};
4use super::policy::PathPolicy;
5use super::state::{ConnError, ConnSlot, ConnState};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum Scheduled {
9    None,
10    CheckRelay,
11    CheckDirectV6,
12    CheckDirectV4,
13    Defer,
14    Close,
15}
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub struct Schedule {
19    pub now_ms: u64,
20    pub first_v6_ms: Option<u64>,
21    pub relay_started: bool,
22    pub v6_started: bool,
23    pub v4_started: bool,
24    pub selected: Scheduled,
25}
26
27impl Schedule {
28    /// Creates a default `Schedule`.
29    pub const fn new() -> Self {
30        Self {
31            now_ms: 0,
32            first_v6_ms: None,
33            relay_started: false,
34            v6_started: false,
35            v4_started: false,
36            selected: Scheduled::None,
37        }
38    }
39
40    /// `true` when IPv4 is eligible under `policy`.
41    pub fn ipv4_eligible(&self, policy: PathPolicy) -> bool {
42        match self.first_v6_ms {
43            None => true,
44            Some(t) => self.now_ms.saturating_sub(t) >= u64::from(policy.ipv4_prompt_ms),
45        }
46    }
47
48    /// `true` when the setup window expired.
49    pub fn setup_expired(&self, policy: PathPolicy) -> bool {
50        self.now_ms >= u64::from(policy.setup_deadline_ms)
51    }
52}
53
54/// Advance the slot and return the next permitted action. Concurrent relay + direct.
55pub fn tick(
56    slot: &mut ConnSlot,
57    schedule: &mut Schedule,
58    policy: PathPolicy,
59    now_ms: u64,
60    tables: &CandidateTables,
61) -> Result<Scheduled, ConnError> {
62    schedule.now_ms = now_ms;
63    if slot.state == ConnState::Closed {
64        return Ok(Scheduled::Close);
65    }
66    if slot.state == ConnState::Admitted {
67        if !policy.allows_relay() && !policy.allows_direct_probes() {
68            slot.transition(slot.generation, ConnState::Deferred)?;
69            schedule.selected = Scheduled::Defer;
70            return Ok(Scheduled::Defer);
71        }
72        slot.transition(slot.generation, ConnState::Establishing)?;
73    }
74    if schedule.setup_expired(policy) && slot.state == ConnState::Establishing {
75        slot.transition(slot.generation, ConnState::Deferred)?;
76        schedule.selected = Scheduled::Defer;
77        return Ok(Scheduled::Defer);
78    }
79    if policy.allows_relay() && policy.relay_immediate && !schedule.relay_started {
80        schedule.relay_started = true;
81        schedule.selected = Scheduled::CheckRelay;
82        return Ok(Scheduled::CheckRelay);
83    }
84    let has_v6_host = has_kind(tables, CandidateKind::Host, AddrFamily::V6);
85    let has_v4_host = has_kind(tables, CandidateKind::Host, AddrFamily::V4);
86    if policy.allows_direct_probes() && has_v6_host && !schedule.v6_started {
87        schedule.v6_started = true;
88        if schedule.first_v6_ms.is_none() {
89            schedule.first_v6_ms = Some(now_ms);
90        }
91        schedule.selected = Scheduled::CheckDirectV6;
92        return Ok(Scheduled::CheckDirectV6);
93    }
94    if policy.allows_direct_probes()
95        && has_v4_host
96        && !schedule.v4_started
97        && schedule.ipv4_eligible(policy)
98    {
99        schedule.v4_started = true;
100        schedule.selected = Scheduled::CheckDirectV4;
101        return Ok(Scheduled::CheckDirectV4);
102    }
103    Ok(schedule.selected)
104}
105
106fn has_kind(tables: &CandidateTables, kind: CandidateKind, family: AddrFamily) -> bool {
107    let mut i = 0;
108    while i < tables.local_len {
109        if let Some(c) = tables.local[i] {
110            if c.kind == kind && c.family == family {
111                return true;
112            }
113        }
114        i += 1;
115    }
116    false
117}
118
119/// Ordinary dual-stack gather + first ticks prove relay is not delayed by IPv6.
120pub fn ordinary_first_actions() -> [Scheduled; 3] {
121    let policy = PathPolicy::ORDINARY;
122    let tables = gather_permitted(policy, true, true);
123    let mut slot = ConnSlot::new(1);
124    let mut sch = Schedule::new();
125    let a0 = tick(&mut slot, &mut sch, policy, 0, &tables).unwrap();
126    let a1 = tick(&mut slot, &mut sch, policy, 0, &tables).unwrap();
127    let a2 = tick(&mut slot, &mut sch, policy, 250, &tables).unwrap();
128    [a0, a1, a2]
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134
135    #[test]
136    fn relay_then_v6_then_v4() {
137        assert_eq!(
138            ordinary_first_actions(),
139            [
140                Scheduled::CheckRelay,
141                Scheduled::CheckDirectV6,
142                Scheduled::CheckDirectV4
143            ]
144        );
145    }
146
147    #[test]
148    fn blackholed_v6_does_not_block_v4() {
149        let policy = PathPolicy::ORDINARY;
150        let tables = gather_permitted(policy, true, true);
151        let mut slot = ConnSlot::new(1);
152        let mut sch = Schedule::new();
153        assert_eq!(
154            tick(&mut slot, &mut sch, policy, 0, &tables).unwrap(),
155            Scheduled::CheckRelay
156        );
157        assert_eq!(
158            tick(&mut slot, &mut sch, policy, 0, &tables).unwrap(),
159            Scheduled::CheckDirectV6
160        );
161        assert!(
162            !sch.ipv4_eligible(policy),
163            "IPv4 waits the prompt, not a family-wide timeout"
164        );
165        assert_eq!(
166            tick(&mut slot, &mut sch, policy, 250, &tables).unwrap(),
167            Scheduled::CheckDirectV4
168        );
169    }
170
171    #[test]
172    fn isolated_defers() {
173        let policy = PathPolicy::ISOLATED;
174        let tables = gather_permitted(policy, true, true);
175        let mut slot = ConnSlot::new(1);
176        let mut sch = Schedule::new();
177        assert_eq!(
178            tick(&mut slot, &mut sch, policy, 0, &tables).unwrap(),
179            Scheduled::Defer
180        );
181        assert_eq!(slot.state, ConnState::Deferred);
182    }
183}