Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
177 changes: 172 additions & 5 deletions neqo-http3/src/features/extended_connect/connect_udp_session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ use crate::{
/// The only context ID RFC 9298 defines: the payload is a UDP packet.
const CONTEXT_ID: u64 = 0;

/// Datagram bytes one control stream read may queue as events (RFC 9298 Section 5).
const MAX_DATAGRAM_BYTES_PER_READ: usize = 256 * 1024;

/// Per-event bookkeeping charge, as `PER_DATAGRAM_OVERHEAD` in neqo-transport's datagram queue.
const PER_DATAGRAM_OVERHEAD: usize = 64;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This duplicates the private constant in neqo-transport/src/datagram_queue.rs:62, and the doc comment says it mirrors it, but nothing ties them together; if transport changes its value this silently diverges. Maybe export the transport one (or a cost helper) instead? However, see below -- using PER_DATAGRAM_OVERHEAD from transport probably isn't what we want, so perhaps just use a different constant (and name)


#[derive(Debug)]
pub struct Session {
frame_reader: FrameReader,
Expand Down Expand Up @@ -61,6 +67,7 @@ impl Protocol for Session {
control_stream_recv: &mut Box<dyn RecvStream>,
now: Instant,
) -> Res<Option<State>> {
let mut budget = MAX_DATAGRAM_BYTES_PER_READ;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This bounds the events queued per read_control_stream call, but not the events outstanding. The budget starts fresh on every call (from both Session::receive and header_unblocked), and consuming the stream data reopens flow control, so a peer can send another window of tiny capsules every RTT. If the application doesn't poll events between process calls, or polls more slowly than the peer sends, each read adds up to another ~4096 Datagram events and the queue still grows without bound.

Would it work to track outstanding queued bytes per session, released as events are polled, like transport's max_buffered_datagrams? That bounds memory regardless of how reads are batched.

loop {
let (capsule, fin) = self
.frame_reader
Expand All @@ -75,7 +82,14 @@ impl Protocol for Session {
match capsule {
Some(Capsule::Datagram { payload }) => match self.dgram_context_id(payload) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Datagrams over the budget are still fully decoded before being dropped: Capsule::decode does Bytes::from(payload.to_vec()) (frames/capsule.rs:59), and the context ID is parsed, then the allocation is freed. The loop also keeps reading after the budget is exhausted. So under a flood each read still does work proportional to the whole flow-control window, and the CPU side of the amplification is unchanged. Could we stop reading once the budget is exhausted, or check the length before allocating?

Ok(slice) => {
events.new_datagram(self.session_id, slice, self.connect_type());
let cost = slice.len().saturating_add(PER_DATAGRAM_OVERHEAD);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will also drop legitimate traffic. With an multi-MB stream receive window, a single lost packet blocks the stream; when the retransmission fills the gap, everything buffered behind it becomes readable in one read, and anything past the first 256 KB is discarded even though the peer sent it within flow control and we've already ACKed it. A tunneled flow would see a burst loss after every recovery event. That's the same scenario the hold_first tests construct, just with benign traffic.

A cap on outstanding (unpolled) events, per the comment above, avoids this, since a well-behaved application drains between reads.

Also, this undercounts actual memory per event. Each queued event is an Http3ClientEvent/Http3ServerEvent in a VecDeque slot plus a Bytes header, and the backing allocation is the full capsule payload including the context-ID prefix (not just slice.len()). For an empty datagram I suspect that's well over 64 bytes, so the real bound per read is a multiple of the documented 256 KB. The 64 was chosen for transport's queue entries, not HTTP/3 events.

if let Some(rest) = budget.checked_sub(cost) {
budget = rest;
events.new_datagram(self.session_id, slice, self.connect_type());
} else {
// RFC 9221 Section 5.3 lets the receiver drop datagrams.
debug!("[{self}]: dropped datagram over the per-read budget");

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two concerns: there's no counter, stat or event for these drops, so the application can't tell that it's losing datagrams (which makes the case in the previous comment hard to diagnose), and under the flood this is guarding against it logs once per dropped capsule, which can be hundreds of thousands of lines per read with debug logging on. Could we count the drops and log once per read (and ideally surface the count in stats)?

}
}
Err(e) => {
debug!("[{self}]: received capsule with invalid context identifier: {e}");
Expand Down Expand Up @@ -171,11 +185,164 @@ impl Protocol for Session {
#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
use neqo_common::Bytes;
use neqo_transport::StreamId;
use std::iter;

use neqo_common::{Bytes, Datagram, event::Provider as _};
use neqo_transport::{ConnectionParameters, DatagramQueueOutcome, StreamId};
use test_fixture::now;

use super::{MAX_DATAGRAM_BYTES_PER_READ, PER_DATAGRAM_OVERHEAD, Session};
use crate::{
ConnectUdpEvent, Http3Client, Http3ClientEvent, Http3Parameters, Http3Server,
Http3ServerEvent, Res, SessionAcceptAction,
connect_udp::{ClientSession as _, ServerEvent, ServerSession},
features::extended_connect::{session::Protocol as _, tests::webtransport::connect},
};

trait Peer {
/// Processes `dgrams` in one batch and returns everything sent in response.
fn exchange(&mut self, dgrams: Vec<Datagram>) -> Vec<Datagram>;
fn datagram_events(&mut self) -> usize;
}

impl Peer for Http3Client {
fn exchange(&mut self, dgrams: Vec<Datagram>) -> Vec<Datagram> {
self.process_multiple_input(dgrams, now());
iter::from_fn(|| self.process_output(now()).dgram()).collect()
}

fn datagram_events(&mut self) -> usize {
self.events()
.filter(|e| {
matches!(
e,
Http3ClientEvent::ConnectUdp(ConnectUdpEvent::Datagram { .. })
)
})
.count()
}
}

impl Peer for Http3Server {
fn exchange(&mut self, dgrams: Vec<Datagram>) -> Vec<Datagram> {
let first = self.process(dgrams, now()).dgram();
first
.into_iter()
.chain(iter::from_fn(|| {
self.process(None::<Datagram>, now()).dgram()
}))
.collect()
}

fn datagram_events(&mut self) -> usize {
self.events()
.filter(|e| {
matches!(
e,
Http3ServerEvent::ConnectUdp(ServerEvent::Datagram { .. })
)
})
.count()
}
}

/// Runs both peers until `sender` is idle. With `hold_first`, the first datagram of every
/// flight is held back, so the receiver cannot read past the stream data it carries.
fn exchange_all(
sender: &mut impl Peer,
receiver: &mut impl Peer,
to_sender: Vec<Datagram>,
hold_first: bool,
) -> Vec<Datagram> {
let mut held = Vec::new();
let mut flight = sender.exchange(to_sender);
while !flight.is_empty() {
if hold_first {
held.push(flight.remove(0));
}
flight = sender.exchange(receiver.exchange(flight));
}
Comment on lines +260 to +264

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hold_first withholds the first datagram of every flight, not just the one carrying the first stream data, so later ACK-only or MAX_STREAM_DATA packets are held as well and delivered together with the gap-filler. The exact assertions (== budgeted, == budgeted - 1) depend on the capsules landing so that everything becomes readable in exactly one read. A change in packetization or pacing could break them for reasons unrelated to the budget logic. Holding only the first packet of the first flight would make the tests less sensitive to that.

held
}

/// Establishes a session that carries datagrams in capsules.
fn capsule_session() -> (Http3Client, Http3Server, ServerSession) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is largely the same as establish_capsule_session in neqo-http3/tests/connect_udp.rs:770. It also requires making tests::webtransport and its connect() public so connect-udp unit tests can reach into the WebTransport test module. Could the two setups share one helper, or the flood tests live alongside the existing integration tests in tests/connect_udp.rs?

let params = Http3Parameters::default()
.connect(true)
.connection_parameters(ConnectionParameters::default().datagram_size(0));
let (mut client, mut server) = connect(params.clone(), params);
let session_id = client
.connect_udp_create_session(now(), ("https", "something.com", "/"), &[])
.unwrap();
exchange_all(&mut client, &mut server, Vec::new(), false);
let session = server
.events()
.find_map(|e| match e {
Http3ServerEvent::ConnectUdp(ServerEvent::NewSession { session, .. }) => {
Some(session)
}
_ => None,
})
.unwrap();
assert_eq!(session.stream_id(), session_id);
session
.response(&SessionAcceptAction::Accept, now())
.unwrap();
exchange_all(&mut server, &mut client, Vec::new(), false);
(client, server, session)
}

use super::Session;
use crate::features::extended_connect::session::Protocol as _;
/// Makes more empty datagram capsules than the per-read budget readable at once, then
/// checks that the session still delivers a later datagram.
fn flood<S: Peer>(
sender: &mut S,
receiver: &mut impl Peer,
send: impl Fn(&mut S) -> Res<DatagramQueueOutcome>,
) {
let budgeted = MAX_DATAGRAM_BYTES_PER_READ / PER_DATAGRAM_OVERHEAD;
for _ in 0..=budgeted {
assert_eq!(send(sender), Ok(DatagramQueueOutcome::Ok));
}
let held = exchange_all(sender, receiver, Vec::new(), true);
assert_eq!(receiver.datagram_events(), 0);
let acks = receiver.exchange(held);
assert_eq!(receiver.datagram_events(), budgeted);
assert_eq!(send(sender), Ok(DatagramQueueOutcome::Ok));
exchange_all(sender, receiver, acks, false);
assert_eq!(receiver.datagram_events(), 1);
}

#[test]
fn proxy_capsule_flood_is_bounded_per_read() {
let (mut client, mut server, session) = capsule_session();
flood(&mut server, &mut client, |_| {
session.send_datagram(&[], None, now())
});
}

#[test]
fn client_capsule_flood_is_bounded_per_read() {
let (mut client, mut server, session) = capsule_session();
let session_id = session.stream_id();
flood(&mut client, &mut server, |client| {
client.connect_udp_send_datagram(session_id, &[], None, now())
});
}

#[test]
fn datagram_one_byte_over_remaining_budget_is_dropped() {
let (mut client, mut server, session) = capsule_session();
let send = |payload: &[u8]| session.send_datagram(payload, None, now());
let budgeted = MAX_DATAGRAM_BYTES_PER_READ / PER_DATAGRAM_OVERHEAD;
for _ in 1..budgeted {
assert_eq!(send(&[]), Ok(DatagramQueueOutcome::Ok));
}
// Costs one byte more than the remaining `PER_DATAGRAM_OVERHEAD`.
assert_eq!(send(&[0]), Ok(DatagramQueueOutcome::Ok));
let held = exchange_all(&mut server, &mut client, Vec::new(), true);
_ = client.exchange(held);
assert_eq!(client.datagram_events(), budgeted - 1);
}

#[test]
fn varint_0_context_id() {
Expand Down
2 changes: 1 addition & 1 deletion neqo-http3/src/features/extended_connect/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

mod webtransport;
pub(super) mod webtransport;
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ fn connect_with(client: &mut Http3Client, server: &mut Http3Server) {
drop(client.process(out.dgram(), now()));
}

fn connect(
pub fn connect(
client_params: Http3Parameters,
server_params: Http3Parameters,
) -> (Http3Client, Http3Server) {
Expand Down
Loading