noq_proto/connection/
ack_frequency.rs

1use crate::Duration;
2use crate::frame::AckFrequency;
3use crate::transport_parameters::TransportParameters;
4use crate::{AckFrequencyConfig, TIMER_GRANULARITY, TransportError, VarInt};
5
6use super::PathId;
7
8/// State associated to ACK frequency
9pub(super) struct AckFrequencyState {
10    //
11    // Sending ACK_FREQUENCY frames
12    /// The path ID, packet number and value of the in-flight ACK_FREQUENCY frame
13    in_flight_ack_frequency_frame: Option<(PathId, u64, Duration)>,
14    next_outgoing_sequence_number: VarInt,
15    pub(super) peer_max_ack_delay: Duration,
16
17    //
18    // Receiving ACK_FREQUENCY frames
19    /// The sequence number of the most recently received ACK_FREQUENCY frame
20    last_ack_frequency_frame: Option<u64>,
21    pub(super) max_ack_delay: Duration,
22}
23
24impl AckFrequencyState {
25    pub(super) fn new(default_max_ack_delay: Duration) -> Self {
26        Self {
27            in_flight_ack_frequency_frame: None,
28            next_outgoing_sequence_number: VarInt(0),
29            peer_max_ack_delay: default_max_ack_delay,
30
31            last_ack_frequency_frame: None,
32            max_ack_delay: default_max_ack_delay,
33        }
34    }
35
36    /// Returns the `max_ack_delay` that should be requested of the peer when sending an
37    /// ACK_FREQUENCY frame
38    pub(super) fn candidate_max_ack_delay(
39        &self,
40        rtt: Duration,
41        config: &AckFrequencyConfig,
42        peer_params: &TransportParameters,
43    ) -> Duration {
44        // Use the peer's max_ack_delay if no custom max_ack_delay was provided in the config
45        let min_ack_delay =
46            Duration::from_micros(peer_params.min_ack_delay.map_or(0, |x| x.into()));
47        config
48            .max_ack_delay
49            .unwrap_or(self.peer_max_ack_delay)
50            .clamp(min_ack_delay, rtt.max(MIN_AUTOMATIC_ACK_DELAY))
51    }
52
53    /// Returns the `max_ack_delay` for the purposes of calculating the PTO
54    ///
55    /// This `max_ack_delay` is defined as the maximum of the peer's current `max_ack_delay` and all
56    /// in-flight `max_ack_delay`s (i.e. proposed values that haven't been acknowledged yet, but
57    /// might be already in use by the peer).
58    pub(super) fn max_ack_delay_for_pto(&self) -> Duration {
59        // Note: we have at most one in-flight ACK_FREQUENCY frame
60        if let Some((_, _, max_ack_delay)) = self.in_flight_ack_frequency_frame {
61            self.peer_max_ack_delay.max(max_ack_delay)
62        } else {
63            self.peer_max_ack_delay
64        }
65    }
66
67    /// Returns the next sequence number for an ACK_FREQUENCY frame
68    pub(super) fn next_sequence_number(&mut self) -> VarInt {
69        assert!(self.next_outgoing_sequence_number <= VarInt::MAX);
70
71        let seq = self.next_outgoing_sequence_number;
72        self.next_outgoing_sequence_number.0 += 1;
73        seq
74    }
75
76    /// Returns true if we should send an ACK_FREQUENCY frame
77    pub(super) fn should_send_ack_frequency(
78        &self,
79        rtt: Duration,
80        config: &AckFrequencyConfig,
81        peer_params: &TransportParameters,
82    ) -> bool {
83        if self.next_outgoing_sequence_number.0 == 0 {
84            // Always send at startup
85            return true;
86        }
87        let current = self
88            .in_flight_ack_frequency_frame
89            .map_or(self.peer_max_ack_delay, |(_, _, pending)| pending);
90        let desired = self.candidate_max_ack_delay(rtt, config, peer_params);
91        let error = (desired.as_secs_f32() / current.as_secs_f32()) - 1.0;
92        error.abs() > MAX_RTT_ERROR
93    }
94
95    /// Notifies the [`AckFrequencyState`] that a packet containing an ACK_FREQUENCY frame was sent
96    pub(super) fn ack_frequency_sent(
97        &mut self,
98        path_id: PathId,
99        pn: u64,
100        requested_max_ack_delay: Duration,
101    ) {
102        self.in_flight_ack_frequency_frame = Some((path_id, pn, requested_max_ack_delay));
103    }
104
105    /// Notifies the [`AckFrequencyState`] that a packet has been ACKed
106    pub(super) fn on_acked(&mut self, path_id: PathId, pn: u64) {
107        match self.in_flight_ack_frequency_frame {
108            Some((path, number, requested_max_ack_delay)) if path == path_id && number == pn => {
109                self.in_flight_ack_frequency_frame = None;
110                self.peer_max_ack_delay = requested_max_ack_delay;
111            }
112            _ => {}
113        }
114    }
115
116    /// Notifies the [`AckFrequencyState`] that an ACK_FREQUENCY frame was received
117    ///
118    /// Updates the endpoint's params according to the payload of the ACK_FREQUENCY frame, or
119    /// returns an error in case the requested `max_ack_delay` is invalid.
120    ///
121    /// Returns `true` if the frame was processed and `false` if it was ignored because of being
122    /// stale.
123    pub(super) fn ack_frequency_received(
124        &mut self,
125        frame: &AckFrequency,
126    ) -> Result<bool, TransportError> {
127        if self
128            .last_ack_frequency_frame
129            .is_some_and(|highest_sequence_nr| frame.sequence.into_inner() <= highest_sequence_nr)
130        {
131            return Ok(false);
132        }
133
134        self.last_ack_frequency_frame = Some(frame.sequence.into_inner());
135
136        // Update max_ack_delay
137        let max_ack_delay = Duration::from_micros(frame.request_max_ack_delay.into_inner());
138        if max_ack_delay < TIMER_GRANULARITY {
139            return Err(TransportError::PROTOCOL_VIOLATION(
140                "Requested Max Ack Delay in ACK_FREQUENCY frame is less than min_ack_delay",
141            ));
142        }
143        self.max_ack_delay = max_ack_delay;
144
145        Ok(true)
146    }
147}
148
149/// Maximum proportion difference between the most recently requested max ACK delay and the
150/// currently desired one before a new request is sent, when the peer supports the ACK frequency
151/// extension and an explicit max ACK delay is not configured.
152const MAX_RTT_ERROR: f32 = 0.2;
153
154/// Minimum value to request the peer set max ACK delay to when the peer supports the ACK frequency
155/// extension and an explicit max ACK delay is not configured.
156// Keep in sync with `AckFrequencyConfig::max_ack_delay` documentation
157const MIN_AUTOMATIC_ACK_DELAY: Duration = Duration::from_millis(25);