1use crate::net::qdnf::errors::QdnfError;
7use crate::net::qdnf::session::credit::CreditTable;
8use crate::net::qdnf::session::paths::{PathHandle, MAX_RACE_CANDIDATES};
9use crate::net::qdnf::session::rtt::RttEstimator;
10
11pub const CC_SEGMENT_BYTES: u64 = 1200;
13pub const INITIAL_WINDOW_BYTES: u64 = 14_720;
14pub const MIN_WINDOW_BYTES: u64 = 2 * CC_SEGMENT_BYTES;
15const FLIGHT_SLOTS: usize = 16;
16
17#[repr(C)]
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19struct FlightSlot {
20 pn: u64,
21 bytes: u64,
22 retired: bool,
23}
24
25#[derive(Clone, Copy, Debug)]
26pub struct Congestion {
27 pub bytes_in_flight: u64,
28 pub window_bytes: u64,
29 pub ssthresh: u64,
30 flight: [Option<FlightSlot>; FLIGHT_SLOTS],
31}
32
33impl Congestion {
34 pub const fn new() -> Self {
36 Self::with_window(INITIAL_WINDOW_BYTES)
37 }
38
39 pub const fn with_window(window_bytes: u64) -> Self {
41 Self {
42 bytes_in_flight: 0,
43 window_bytes,
44 ssthresh: u64::MAX,
45 flight: [None; FLIGHT_SLOTS],
46 }
47 }
48}
49
50impl Default for Congestion {
51 fn default() -> Self {
53 Self::new()
54 }
55}
56
57#[repr(C)]
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59pub struct EcnState {
60 pub ect: bool,
61 pub ce_count: u32,
62 pub validated: bool,
63}
64
65impl EcnState {
66 pub const fn new() -> Self {
68 Self {
69 ect: false,
70 ce_count: 0,
71 validated: false,
72 }
73 }
74}
75
76#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78pub struct PmtuState {
79 mtu: Option<u16>,
80}
81
82impl PmtuState {
83 pub const fn unknown() -> Self {
85 Self { mtu: None }
86 }
87
88 pub fn current(self) -> Result<u16, QdnfError> {
90 self.mtu.ok_or(QdnfError::Incomplete)
91 }
92
93 pub fn discover(&mut self, mtu: u16) -> Result<u16, QdnfError> {
95 if mtu == 0 {
96 return Err(QdnfError::Range);
97 }
98 self.mtu = Some(mtu);
99 Ok(mtu)
100 }
101
102 pub fn shrink(&mut self, mtu: u16) -> Result<u16, QdnfError> {
104 let cur = self.current()?;
105 if mtu == 0 || mtu > cur {
106 return Err(QdnfError::Range);
107 }
108 self.mtu = Some(mtu);
109 Ok(mtu)
110 }
111
112 pub fn admit_bytes(&self, len: usize) -> Result<(), QdnfError> {
114 let mtu = self.current()?;
115 if len > mtu as usize {
116 Err(QdnfError::Capacity)
117 } else {
118 Ok(())
119 }
120 }
121}
122
123#[derive(Clone, Copy, Debug)]
124struct PathLocalCc {
125 handle: PathHandle,
126 cc: Congestion,
127 rtt: RttEstimator,
128}
129
130#[derive(Clone, Copy, Debug)]
132pub struct PathCcTable {
133 pub shared: Congestion,
134 pub independent_bottleneck: bool,
135 locals: [Option<PathLocalCc>; MAX_RACE_CANDIDATES],
136}
137
138impl PathCcTable {
139 pub const fn new(window_bytes: u64) -> Self {
141 Self {
142 shared: Congestion::with_window(window_bytes),
143 independent_bottleneck: false,
144 locals: [None; MAX_RACE_CANDIDATES],
145 }
146 }
147
148 pub fn attach(&mut self, handle: PathHandle) -> Result<(), QdnfError> {
151 let i = slot_index(handle)?;
152 if let Some(existing) = self.locals[i] {
153 if existing.handle.generation() != handle.generation() {
154 return Err(QdnfError::StaleGeneration);
155 }
156 return Ok(());
157 }
158 self.locals[i] = Some(PathLocalCc {
159 handle,
160 cc: Congestion::with_window(self.shared.window_bytes),
161 rtt: RttEstimator::new(),
162 });
163 Ok(())
164 }
165
166 pub fn path_rtt(&self, handle: PathHandle) -> Result<RttEstimator, QdnfError> {
168 Ok(self.local(handle)?.rtt)
169 }
170
171 pub fn check_send(&self, handle: PathHandle, bytes: u64) -> Result<(), QdnfError> {
173 if self.independent_bottleneck {
174 can_send(&self.local(handle)?.cc, bytes)
175 } else {
176 let _ = self.local(handle)?;
177 can_send(&self.shared, bytes)
178 }
179 }
180
181 pub fn send(&mut self, handle: PathHandle, pn: u64, bytes: u64) -> Result<(), QdnfError> {
184 self.check_send(handle, bytes)?;
185 let independent = self.independent_bottleneck;
186 if independent {
187 return on_send(&mut self.local_mut(handle)?.cc, pn, bytes);
188 }
189 let _ = self.local(handle)?;
190 on_send(&mut self.shared, pn, bytes)
191 }
192
193 pub fn total_in_flight(&self) -> u64 {
195 if self.independent_bottleneck {
196 let mut n = 0u64;
197 let mut i = 0usize;
198 while i < MAX_RACE_CANDIDATES {
199 if let Some(local) = self.locals[i] {
200 n = n.saturating_add(local.cc.bytes_in_flight);
201 }
202 i += 1;
203 }
204 n
205 } else {
206 self.shared.bytes_in_flight
207 }
208 }
209
210 fn local(&self, handle: PathHandle) -> Result<&PathLocalCc, QdnfError> {
212 let i = slot_index(handle)?;
213 let local = self.locals[i].as_ref().ok_or(QdnfError::Closed)?;
214 if local.handle.generation() != handle.generation() {
215 return Err(QdnfError::StaleGeneration);
216 }
217 Ok(local)
218 }
219
220 fn local_mut(&mut self, handle: PathHandle) -> Result<&mut PathLocalCc, QdnfError> {
222 let i = slot_index(handle)?;
223 let local = self.locals[i].as_mut().ok_or(QdnfError::Closed)?;
224 if local.handle.generation() != handle.generation() {
225 return Err(QdnfError::StaleGeneration);
226 }
227 Ok(local)
228 }
229}
230
231fn slot_index(handle: PathHandle) -> Result<usize, QdnfError> {
233 let i = handle.slot() as usize;
234 if i >= MAX_RACE_CANDIDATES {
235 Err(QdnfError::Range)
236 } else {
237 Ok(i)
238 }
239}
240
241pub fn can_send(cc: &Congestion, payload: u64) -> Result<(), QdnfError> {
244 if payload == 0 {
245 return Err(QdnfError::Range);
246 }
247 let next = cc.bytes_in_flight.saturating_add(payload);
248 if next > cc.window_bytes {
249 Err(QdnfError::BudgetExhausted)
250 } else {
251 Ok(())
252 }
253}
254
255pub fn on_send(cc: &mut Congestion, pn: u64, bytes: u64) -> Result<(), QdnfError> {
257 can_send(cc, bytes)?;
258 insert_flight(cc, pn, bytes)?;
259 cc.bytes_in_flight = cc.bytes_in_flight.saturating_add(bytes);
260 Ok(())
261}
262
263pub fn on_acked(cc: &mut Congestion, bytes: u64) {
265 cc.bytes_in_flight = cc.bytes_in_flight.saturating_sub(bytes);
266 grow_window(cc, bytes);
267}
268
269pub fn on_lost(cc: &mut Congestion, bytes: u64) {
271 cc.bytes_in_flight = cc.bytes_in_flight.saturating_sub(bytes);
272 collapse_window(cc);
273}
274
275pub fn on_acked_pn(cc: &mut Congestion, pn: u64) -> Result<(), QdnfError> {
278 match take_live(cc, pn)? {
279 None => Ok(()),
280 Some(bytes) => {
281 on_acked(cc, bytes);
282 Ok(())
283 }
284 }
285}
286
287pub fn on_lost_pn(cc: &mut Congestion, pn: u64) -> Result<(), QdnfError> {
290 match take_live(cc, pn)? {
291 None => Ok(()),
292 Some(bytes) => {
293 on_lost(cc, bytes);
294 Ok(())
295 }
296 }
297}
298
299pub fn on_ecn(ecn: &mut EcnState, ce: bool) {
301 if ce && ecn.validated {
302 ecn.ce_count = ecn.ce_count.saturating_add(1);
303 }
304}
305
306pub fn apply_ecn(cc: &mut Congestion, ecn: &EcnState, ce: bool) {
309 if ce && ecn.validated {
310 collapse_window(cc);
311 }
312}
313
314pub fn admit_send(
316 cc: &Congestion,
317 credit: &CreditTable,
318 dir: u8,
319 payload: u64,
320) -> Result<(), QdnfError> {
321 can_send(cc, payload)?;
322 credit.admit_application(dir, payload)?;
323 Ok(())
324}
325
326pub fn application_credit_is_congestion() -> bool {
329 false
330}
331
332pub fn path_cc_is_connection_authority() -> bool {
335 false
336}
337
338fn grow_window(cc: &mut Congestion, acked: u64) {
340 if acked == 0 {
341 return;
342 }
343 if cc.window_bytes < cc.ssthresh {
344 cc.window_bytes = cc.window_bytes.saturating_add(acked);
345 return;
346 }
347 let denom = cc.window_bytes.max(1);
348 let inc = CC_SEGMENT_BYTES.saturating_mul(acked) / denom;
349 cc.window_bytes = cc.window_bytes.saturating_add(inc.max(1));
350}
351
352fn collapse_window(cc: &mut Congestion) {
354 let half = (cc.window_bytes / 2).max(MIN_WINDOW_BYTES);
355 cc.ssthresh = half;
356 cc.window_bytes = half;
357}
358
359fn insert_flight(cc: &mut Congestion, pn: u64, bytes: u64) -> Result<(), QdnfError> {
362 let mut free = None;
363 let mut i = 0usize;
364 while i < FLIGHT_SLOTS {
365 match cc.flight[i] {
366 Some(slot) if slot.pn == pn && !slot.retired => return Err(QdnfError::Replay),
367 Some(slot) if slot.pn == pn && slot.retired => {
368 cc.flight[i] = Some(FlightSlot {
369 pn,
370 bytes,
371 retired: false,
372 });
373 return Ok(());
374 }
375 None if free.is_none() => free = Some(i),
376 _ => {}
377 }
378 i += 1;
379 }
380 let idx = free.ok_or(QdnfError::Capacity)?;
381 cc.flight[idx] = Some(FlightSlot {
382 pn,
383 bytes,
384 retired: false,
385 });
386 Ok(())
387}
388
389fn take_live(cc: &mut Congestion, pn: u64) -> Result<Option<u64>, QdnfError> {
392 let mut i = 0usize;
393 while i < FLIGHT_SLOTS {
394 if let Some(slot) = cc.flight[i] {
395 if slot.pn == pn {
396 if slot.retired {
397 return Ok(None);
398 }
399 cc.flight[i] = Some(FlightSlot {
400 pn,
401 bytes: slot.bytes,
402 retired: true,
403 });
404 return Ok(Some(slot.bytes));
405 }
406 }
407 i += 1;
408 }
409 Err(QdnfError::Malformed)
410}
411
412#[cfg(test)]
413mod tests {
414 use super::*;
415 use crate::net::qdnf::session::credit::DIR_CLIENT;
416 use crate::net::qdnf::session::paths::{mutate_path, PathState, PathTable};
417 use crate::net::qdnf::types::Generation;
418
419 #[test]
420 fn transport_a_send_ack_conserves_bytes() {
421 let mut cc = Congestion::with_window(10_000);
422 on_send(&mut cc, 1, 400).unwrap();
423 on_send(&mut cc, 2, 600).unwrap();
424 assert_eq!(cc.bytes_in_flight, 1000);
425 on_acked_pn(&mut cc, 1).unwrap();
426 on_acked_pn(&mut cc, 2).unwrap();
427 assert_eq!(cc.bytes_in_flight, 0);
428 }
429
430 #[test]
431 fn transport_a_loss_does_not_double_count_later_ack() {
432 let mut cc = Congestion::with_window(10_000);
433 on_send(&mut cc, 7, 250).unwrap();
434 assert_eq!(cc.bytes_in_flight, 250);
435 on_lost_pn(&mut cc, 7).unwrap();
436 assert_eq!(cc.bytes_in_flight, 0);
437 on_acked_pn(&mut cc, 7).unwrap();
438 assert_eq!(cc.bytes_in_flight, 0);
439 }
440
441 #[test]
442 fn window_exhausted_is_budget_even_with_stream_credit() {
443 let credit = CreditTable::new(10_000);
444 let mut cc = Congestion::with_window(100);
445 on_send(&mut cc, 1, 100).unwrap();
446 assert!(credit.admit_application(DIR_CLIENT, 1).is_ok());
447 assert_eq!(can_send(&cc, 1), Err(QdnfError::BudgetExhausted));
448 assert_eq!(
449 admit_send(&cc, &credit, DIR_CLIENT, 1),
450 Err(QdnfError::BudgetExhausted)
451 );
452 assert!(!application_credit_is_congestion());
453 }
454
455 #[test]
456 fn stream_credit_exhausted_is_capacity_even_with_cc_window() {
457 let credit = CreditTable::new(0);
458 let cc = Congestion::with_window(10_000);
459 assert!(can_send(&cc, 64).is_ok());
460 assert_eq!(
461 credit.admit_application(DIR_CLIENT, 1),
462 Err(QdnfError::Capacity)
463 );
464 assert_eq!(
465 admit_send(&cc, &credit, DIR_CLIENT, 1),
466 Err(QdnfError::Capacity)
467 );
468 }
469
470 #[test]
471 fn unvalidated_ce_does_not_collapse_window() {
472 let mut cc = Congestion::with_window(8_000);
473 let mut ecn = EcnState {
474 ect: true,
475 ce_count: 0,
476 validated: false,
477 };
478 let before = cc.window_bytes;
479 on_ecn(&mut ecn, true);
480 apply_ecn(&mut cc, &ecn, true);
481 assert_eq!(ecn.ce_count, 0);
482 assert_eq!(cc.window_bytes, before);
483 ecn.validated = true;
484 on_ecn(&mut ecn, true);
485 apply_ecn(&mut cc, &ecn, true);
486 assert_eq!(ecn.ce_count, 1);
487 assert!(cc.window_bytes < before);
488 }
489
490 #[test]
491 fn shared_bottleneck_two_paths_one_window() {
492 let mut paths = PathTable::new();
493 let a = paths.start_race(1).unwrap();
494 let b = paths.start_race(1).unwrap();
495 paths.mark_active(a).unwrap();
496 paths.mark_active(b).unwrap();
497 let ha = paths.handle_of(a).unwrap();
498 let hb = paths.handle_of(b).unwrap();
499 let mut tbl = PathCcTable::new(500);
500 assert!(!tbl.independent_bottleneck);
501 tbl.attach(ha).unwrap();
502 tbl.attach(hb).unwrap();
503 tbl.send(ha, 1, 500).unwrap();
504 assert_eq!(tbl.send(hb, 2, 1), Err(QdnfError::BudgetExhausted));
505 assert!(tbl.total_in_flight() <= 500);
506 assert!(!path_cc_is_connection_authority());
507 }
508
509 #[test]
510 fn pmtu_shrink_rejects_oversize() {
511 let mut pmtu = PmtuState::unknown();
512 assert_eq!(pmtu.admit_bytes(1), Err(QdnfError::Incomplete));
513 assert_eq!(pmtu.shrink(1280), Err(QdnfError::Incomplete));
514 pmtu.discover(1500).unwrap();
515 pmtu.admit_bytes(1500).unwrap();
516 pmtu.shrink(1400).unwrap();
517 assert_eq!(pmtu.admit_bytes(1401), Err(QdnfError::Capacity));
518 pmtu.admit_bytes(1400).unwrap();
519 }
520
521 #[test]
522 fn forged_ack_unknown_pn_malformed() {
523 let mut cc = Congestion::with_window(10_000);
524 on_send(&mut cc, 1, 100).unwrap();
525 assert_eq!(on_acked_pn(&mut cc, 99), Err(QdnfError::Malformed));
526 assert_eq!(cc.bytes_in_flight, 100);
527 }
528
529 #[test]
530 fn packet_or_stream_exhaustion_is_capacity() {
531 let mut cc = Congestion::with_window(1_000_000);
532 let mut pn = 1u64;
533 while pn <= 16 {
534 on_send(&mut cc, pn, 10).unwrap();
535 pn += 1;
536 }
537 assert_eq!(on_send(&mut cc, 17, 10), Err(QdnfError::Capacity));
538 let credit = CreditTable::new(0);
539 assert_eq!(
540 admit_send(&cc, &credit, DIR_CLIENT, 1),
541 Err(QdnfError::Capacity)
542 );
543 }
544
545 #[test]
546 fn stale_path_handle_rejected_by_cc_table() {
547 let mut paths = PathTable::new();
548 let id = paths.start_race(3).unwrap();
549 paths
550 .attest_reachability(paths.handle_of(id).unwrap())
551 .unwrap();
552 let stale = paths.handle_of(id).unwrap();
553 let fresh = mutate_path(&mut paths, stale, PathState::Racing).unwrap();
554 assert_ne!(stale.generation(), fresh.generation());
555 let mut tbl = PathCcTable::new(1200);
556 tbl.attach(fresh).unwrap();
557 assert_eq!(tbl.send(stale, 1, 10), Err(QdnfError::StaleGeneration));
558 assert_eq!(stale.generation(), Generation(3));
559 }
560
561 #[test]
562 fn unknown_pmtu_fails_closed() {
563 let mut p = PmtuState::unknown();
564 assert_eq!(p.current(), Err(QdnfError::Incomplete));
565 assert_eq!(p.discover(0), Err(QdnfError::Range));
566 assert_eq!(p.discover(1500).unwrap(), 1500);
567 assert_eq!(p.current(), Ok(1500));
568 }
569}