Skip to main content

moqtap_client/draft23/session/
request_id.rs

1use moqtap_codec::varint::VarInt;
2
3/// Role of the endpoint (determines request ID parity).
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum Role {
6    /// Client uses even request IDs: 0, 2, 4, ...
7    Client,
8    /// Server uses odd request IDs: 1, 3, 5, ...
9    Server,
10}
11
12/// Errors from request ID allocation or validation.
13#[derive(Debug, thiserror::Error, PartialEq, Eq)]
14pub enum RequestIdError {
15    /// The request ID exceeds the current MAX_REQUEST_ID.
16    #[error("request ID {0} exceeds max {1}")]
17    ExceedsMax(u64, u64),
18    /// The request ID has the wrong parity for the given role.
19    #[error("request ID {0} has wrong parity for {1:?}")]
20    WrongParity(u64, Role),
21    /// MAX_REQUEST_ID must only increase; it decreased.
22    #[error("max request ID can only increase: was {0}, got {1}")]
23    Decreased(u64, u64),
24    /// No request IDs are available (max is 0 or exhausted).
25    #[error("no request IDs available (blocked)")]
26    Blocked,
27}
28
29/// Allocates and validates request IDs per the MoQT spec.
30///
31/// - Client: even IDs (0, 2, 4, ...)
32/// - Server: odd IDs (1, 3, 5, ...)
33/// - Default MAX_REQUEST_ID: 0 (no requests until increased)
34/// - MAX_REQUEST_ID can only increase
35pub struct RequestIdAllocator {
36    role: Role,
37    next_id: u64,
38    max_id: u64,
39}
40
41impl RequestIdAllocator {
42    /// Create a new allocator for the given role, starting at ID 0 or 1.
43    pub fn new(role: Role) -> Self {
44        let next_id = match role {
45            Role::Client => 0,
46            Role::Server => 1,
47        };
48        // Draft-23 has no MAX_REQUEST_ID;
49        // allocator is never blocked.
50        Self { role, next_id, max_id: u64::MAX }
51    }
52
53    /// Allocate the next request ID.
54    pub fn allocate(&mut self) -> Result<VarInt, RequestIdError> {
55        if self.max_id == 0 || self.next_id > self.max_id {
56            return Err(RequestIdError::Blocked);
57        }
58        let id = VarInt::from_u64(self.next_id).unwrap();
59        self.next_id += 2;
60        Ok(id)
61    }
62
63    /// Update the maximum allowed request ID (can only increase).
64    pub fn update_max(&mut self, new_max: u64) -> Result<(), RequestIdError> {
65        if new_max <= self.max_id {
66            return Err(RequestIdError::Decreased(self.max_id, new_max));
67        }
68        self.max_id = new_max;
69        Ok(())
70    }
71
72    /// Validate a request ID the peer put on the wire.
73    ///
74    /// Draft-23 Section 6.4.2.1: "The client generates even numbered Request IDs,
75    /// starting at 0, and the server generates odd numbered Request IDs,
76    /// starting at 1." The parity checked here is therefore the **peer's**,
77    /// the opposite of this allocator's own — a client validates odd ids.
78    ///
79    /// The same section makes a wrong bit fatal to the session: "If an
80    /// endpoint receives a Request ID where the least significant bit is incorrect for the sender,
81    /// it MUST close the session with INVALID_REQUEST_ID. If an endpoint detects a duplicate
82    /// Request ID, it MUST close the session with INVALID_REQUEST_ID." Only the first half is
83    /// answered here.
84    /// Duplicate detection needs memory of every id the peer has already
85    /// spent, which this allocator does not keep and cannot keep without
86    /// taking `&mut self`; it lives on the endpoint instead.
87    ///
88    /// The parity rule is also what makes one `HashMap` per request kind
89    /// enough for both directions: an id this endpoint allocates and an id the
90    /// peer allocates can never be equal, so a peer's request cannot collide
91    /// with one of ours.
92    ///
93    /// # Errors
94    ///
95    /// - [`RequestIdError::WrongParity`] carrying the id and the **peer's**
96    ///   role, so the message names the endpoint that broke the rule rather
97    ///   than the one that caught it.
98    /// - [`RequestIdError::ExceedsMax`] if the id is past the current
99    ///   MAX_REQUEST_ID. Draft-23 has no MAX_REQUEST_ID, and
100    ///   [`RequestIdAllocator::new`] sets the ceiling to `u64::MAX`,
101    ///   so on this draft the check cannot fire for any id a varint can carry.
102    pub fn validate_peer_id(&self, id: u64) -> Result<(), RequestIdError> {
103        // Peer has opposite parity
104        let expected_even = match self.role {
105            Role::Client => false, // peer is Server, expects odd
106            Role::Server => true,  // peer is Client, expects even
107        };
108        let is_even = id.is_multiple_of(2);
109        if is_even != expected_even {
110            let peer_role = match self.role {
111                Role::Client => Role::Server,
112                Role::Server => Role::Client,
113            };
114            return Err(RequestIdError::WrongParity(id, peer_role));
115        }
116        if id > self.max_id {
117            return Err(RequestIdError::ExceedsMax(id, self.max_id));
118        }
119        Ok(())
120    }
121
122    /// Check if we are blocked (max_id is 0 or next_id > max_id).
123    pub fn is_blocked(&self) -> bool {
124        self.max_id == 0 || self.next_id > self.max_id
125    }
126
127    /// Get the current maximum request ID.
128    pub fn max_id(&self) -> u64 {
129        self.max_id
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136
137    /// A client allocates the even ids and must accept only odd ones from the
138    /// peer; a server is the mirror. The two are checked together against the
139    /// ids each allocator actually hands out, so a parity that is inverted in
140    /// both places at once — which would let a client talk to itself — still
141    /// fails.
142    #[test]
143    fn each_role_accepts_only_the_ids_the_other_role_allocates() {
144        for (role, peer_role) in [(Role::Client, Role::Server), (Role::Server, Role::Client)] {
145            let mut allocator = RequestIdAllocator::new(role);
146            let mut peer = RequestIdAllocator::new(peer_role);
147            for _ in 0..4 {
148                let peer_id = peer.allocate().unwrap().into_inner();
149                assert!(
150                    allocator.validate_peer_id(peer_id).is_ok(),
151                    "a {role:?} refused {peer_id}, which a {peer_role:?} allocates",
152                );
153                let own_id = allocator.allocate().unwrap().into_inner();
154                assert_eq!(
155                    allocator.validate_peer_id(own_id),
156                    Err(RequestIdError::WrongParity(own_id, peer_role)),
157                    "a {role:?} accepted {own_id} from the peer, an id it allocates itself",
158                );
159            }
160        }
161    }
162
163    /// The error names the peer, not the endpoint that caught it. Draft-23
164    /// Section 6.4.2.1 makes this a session close, so the reason phrase a peer
165    /// reads has to say whose bit was wrong.
166    #[test]
167    fn wrong_parity_names_the_peer_that_sent_the_id() {
168        let client = RequestIdAllocator::new(Role::Client);
169        let err = client.validate_peer_id(4).unwrap_err();
170        assert_eq!(err.to_string(), "request ID 4 has wrong parity for Server");
171
172        let server = RequestIdAllocator::new(Role::Server);
173        let err = server.validate_peer_id(7).unwrap_err();
174        assert_eq!(err.to_string(), "request ID 7 has wrong parity for Client");
175    }
176
177    /// Draft-23 has no MAX_REQUEST_ID,
178    /// so the ceiling check in `validate_peer_id` is unreachable on this
179    /// draft: the largest id a MoQT varint can carry is still accepted.
180    #[test]
181    fn no_ceiling_rejects_a_peer_id_on_this_draft() {
182        let client = RequestIdAllocator::new(Role::Client);
183        let largest_odd = moqtap_codec::varint::MAX_MOQT_VARINT | 1;
184        assert_eq!(client.validate_peer_id(largest_odd), Ok(()));
185    }
186}