moq_transport_iroh/group.rs
1//! moq-net's send groups, mapped onto QUIC stream urgency.
2
3use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
4
5use iroh::endpoint;
6use moq_net::transport::poll;
7use tracing::trace;
8
9/// The tiers inside one group. Streams past the last share it.
10const TIERS: i32 = 16;
11
12/// The bound a group priority is clamped to, either way.
13///
14/// moq-net packs a subscriber and a publisher `i8` into
15/// `subscriber * 256 + publisher`, well inside it.
16const GROUP_PRIORITY_LIMIT: i64 = 1 << 20;
17
18/// Where ungrouped streams start, above the highest grouped urgency.
19///
20/// Grouped urgencies stay within `GROUP_PRIORITY_LIMIT * TIERS`, 2^24 either way.
21const UNGROUPED_BASE: i32 = 1 << 29;
22
23/// The bound an ungrouped priority is clamped to, either way, which keeps every
24/// ungrouped urgency above the grouped ones and inside `i32`.
25const UNGROUPED_LIMIT: i64 = (1 << 28) - 1;
26
27/// Returns the urgency of a stream outside every group at `priority`.
28pub(crate) fn ungrouped(priority: i64) -> i32 {
29 // Within 2^28 - 1 of 2^29 either way, so inside (2^28, 2^30).
30 UNGROUPED_BASE + priority.clamp(-UNGROUPED_LIMIT, UNGROUPED_LIMIT) as i32
31}
32
33/// Returns the urgency of a stream at `tier` of a group at `priority`.
34fn grouped(priority: i64, tier: usize) -> i32 {
35 let priority = priority.clamp(-GROUP_PRIORITY_LIMIT, GROUP_PRIORITY_LIMIT) as i32;
36 let tier = i32::try_from(tier).unwrap_or(i32::MAX).min(TIERS - 1);
37 priority * TIERS + (TIERS - 1 - tier)
38}
39
40/// A QUIC send stream that a group and its owner both reach.
41///
42/// The owner writes through it and the group sets its urgency, which happens
43/// whenever another stream of the group joins, leaves or moves.
44pub(crate) type SharedStream = Arc<Mutex<endpoint::SendStream>>;
45
46/// Locks `stream`, recovering it from a panic in another holder.
47///
48/// Every holder leaves the stream valid, so a poisoned lock is safe to use.
49pub(crate) fn lock(stream: &SharedStream) -> MutexGuard<'_, endpoint::SendStream> {
50 stream.lock().unwrap_or_else(PoisonError::into_inner)
51}
52
53/// A send group, from [`send_group`](poll::Session::send_group) on a
54/// [`Transport`](crate::Transport).
55///
56/// moq-net opens one send group per subscription and ranks its streams in two
57/// levels: a higher-priority group preempts every lower one, groups of equal
58/// priority share the bytes, and inside a group streams go in their own order,
59/// the newest group of a track first. Streams outside every group, the control
60/// streams, go before all of them. kuic schedules exactly that, with
61/// deficit round robin between groups.
62///
63/// iroh's QUIC stack has one level instead: an `i32` urgency per stream,
64/// higher first. Streams of one urgency are sent round robin while the
65/// connection's send fairness is on, which is noq's default, so they share the
66/// bytes. The two levels are packed into the urgency:
67///
68/// ```text
69/// ungrouped: 2^29 + priority above every group
70/// grouped: group priority * 16 + (15 - tier)
71/// ```
72///
73/// A stream's tier is its dense rank inside its group: the streams with the
74/// highest order in the group are tier 0, the next distinct order tier 1, up
75/// to tier 15, which the rest share. So the streams heading equal-priority
76/// groups share one urgency and split the bytes, a group's older streams wait
77/// for its head, and a higher-priority group outranks every tier of a lower
78/// one. A stream joining, leaving or moving reranks its group.
79///
80/// A new urgency does not reach data the stream already has queued right away.
81/// noq 1.4's `set_priority` only stores the value: a stream with queued data
82/// keeps its place in noq's send queue, at the urgency it was queued with,
83/// until its next turn. So a lowered urgency applies after one more turn at
84/// the old one. A raised one, from
85/// [`set_priority`](poll::SendGroup::set_priority) on the group, from a stream
86/// moving up its group's order or from the stream behind a departing head,
87/// applies only once that turn comes at the old urgency. While anything above
88/// the old urgency has data queued, as it does on a link held at its cap, that
89/// may never happen. A stream that joins is queued at its urgency from its
90/// first write, so a new subscription is not affected.
91///
92/// It departs from kuic in one more way: fairness is per stream and per
93/// turn, not per group and per byte, and only between streams of one tier. Two
94/// streams of one group that tie at its head take two turns to another group's
95/// one, and a turn is up to one packet whatever the stream has queued. When the
96/// head of a group has nothing queued, the next stream of that group waits
97/// behind the heads of the other groups rather than taking the idle head's
98/// turn. For live media that holds back a group's backlog first, as the
99/// newest-first order asks anyway.
100///
101/// The sharing rests on the connection's send fairness: with
102/// `send_fairness(false)` in iroh's transport config, streams of one urgency go
103/// in the order they were written to, and the older of two equal-priority
104/// groups goes first again. RFC 9218's per-stream incremental flag, which
105/// [n0-computer/noq#859](https://github.com/n0-computer/noq/pull/859) adds,
106/// would let each stream ask for round robin whatever that setting.
107///
108/// Clones share the group. It lives as long as a handle or a member stream
109/// does.
110#[derive(Clone)]
111pub struct SendGroup {
112 state: Arc<Mutex<GroupState>>,
113}
114
115impl std::fmt::Debug for SendGroup {
116 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117 let state = self.lock();
118 f.debug_struct("SendGroup")
119 .field("priority", &state.priority)
120 .field("members", &state.members.len())
121 .finish()
122 }
123}
124
125#[derive(Debug)]
126struct GroupState {
127 priority: i64,
128 /// The id the next member gets.
129 next: u64,
130 members: Vec<Member>,
131}
132
133#[derive(Debug)]
134struct Member {
135 id: u64,
136 /// The stream's order inside the group: higher goes first.
137 order: i64,
138 stream: SharedStream,
139 /// The urgency last set on the stream, so a rerank touches only the
140 /// streams whose urgency moved.
141 urgency: Option<i32>,
142}
143
144/// A stream's place in a group, which it leaves on drop.
145#[derive(Debug)]
146pub(crate) struct Membership {
147 group: SendGroup,
148 id: u64,
149}
150
151impl SendGroup {
152 pub(crate) fn new(priority: i64) -> Self {
153 Self {
154 state: Arc::new(Mutex::new(GroupState {
155 priority,
156 next: 0,
157 members: Vec::new(),
158 })),
159 }
160 }
161
162 fn lock(&self) -> MutexGuard<'_, GroupState> {
163 self.state.lock().unwrap_or_else(PoisonError::into_inner)
164 }
165
166 /// Adds `stream` to the group at `order` and reranks the group.
167 pub(crate) fn join(&self, stream: SharedStream, order: i64) -> Membership {
168 let mut state = self.lock();
169 let id = state.next;
170 state.next += 1;
171 state.members.push(Member {
172 id,
173 order,
174 stream,
175 urgency: None,
176 });
177 state.rerank();
178 Membership {
179 group: self.clone(),
180 id,
181 }
182 }
183
184 /// Returns whether `self` and `other` are the same group.
185 pub(crate) fn same(&self, other: &Self) -> bool {
186 Arc::ptr_eq(&self.state, &other.state)
187 }
188}
189
190impl poll::SendGroup for SendGroup {
191 fn set_priority(&mut self, priority: i64) {
192 let mut state = self.lock();
193 if state.priority != priority {
194 state.priority = priority;
195 state.rerank();
196 }
197 }
198}
199
200impl Membership {
201 /// Returns the group the stream is in.
202 pub(crate) fn group(&self) -> &SendGroup {
203 &self.group
204 }
205
206 /// Moves the stream to `order` inside its group.
207 pub(crate) fn set_order(&self, order: i64) {
208 let mut state = self.group.lock();
209 let Some(member) = state.members.iter_mut().find(|m| m.id == self.id) else {
210 return;
211 };
212 if member.order != order {
213 member.order = order;
214 state.rerank();
215 }
216 }
217}
218
219impl Drop for Membership {
220 /// Leaves the group, promoting the streams behind this one.
221 ///
222 /// Whatever the stream still has queued keeps the urgency it had.
223 fn drop(&mut self) {
224 let mut state = self.group.lock();
225 state.members.retain(|m| m.id != self.id);
226 state.rerank();
227 }
228}
229
230impl GroupState {
231 /// Sets every member's urgency from its tier and the group's priority.
232 ///
233 /// noq applies a new urgency to queued data only at the stream's next
234 /// turn, which for a raised urgency may be late; see [`SendGroup`].
235 fn rerank(&mut self) {
236 let mut orders: Vec<i64> = self.members.iter().map(|m| m.order).collect();
237 // Highest order first, ties sharing a tier.
238 orders.sort_unstable_by(|a, b| b.cmp(a));
239 orders.dedup();
240 let mut moved = 0usize;
241 for member in &mut self.members {
242 let tier = orders
243 .binary_search_by(|order| member.order.cmp(order))
244 .unwrap_or_else(|tier| tier);
245 let urgency = grouped(self.priority, tier);
246 if member.urgency != Some(urgency) {
247 // Fails only once the stream is closed, when the urgency no
248 // longer matters.
249 lock(&member.stream).set_priority(urgency).ok();
250 member.urgency = Some(urgency);
251 moved += 1;
252 }
253 }
254 trace!(
255 priority = self.priority,
256 members = self.members.len(),
257 tiers = orders.len(),
258 moved,
259 "reranked send group"
260 );
261 }
262}
263
264#[cfg(test)]
265mod tests {
266 use super::*;
267
268 #[test]
269 fn ungrouped_outranks_every_group() {
270 let lowest = ungrouped(i64::MIN);
271 assert!(lowest > grouped(i64::MAX, 0));
272 assert!(lowest > 0);
273 assert!(ungrouped(1) > ungrouped(0));
274 assert_eq!(ungrouped(i64::MAX), UNGROUPED_BASE + UNGROUPED_LIMIT as i32);
275 }
276
277 #[test]
278 fn a_higher_group_outranks_every_tier_of_a_lower_one() {
279 assert!(grouped(1, TIERS as usize) > grouped(0, 0));
280 assert!(grouped(-1, 0) < grouped(0, usize::MAX));
281 // moq-net's packing: a subscriber priority step dominates the publisher's.
282 let packed = |subscriber: i64, publisher: i64| subscriber * 256 + publisher;
283 assert!(grouped(packed(1, -128), 99) > grouped(packed(0, 127), 0));
284 }
285
286 #[test]
287 fn tiers_order_within_a_group_and_saturate() {
288 assert!(grouped(3, 0) > grouped(3, 1));
289 assert_eq!(grouped(3, TIERS as usize - 1), grouped(3, 1000));
290 assert_eq!(grouped(i64::MIN, 0), grouped(-GROUP_PRIORITY_LIMIT, 0));
291 }
292}