Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proto-layer endpoint/connection communication #1726

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
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
122 changes: 66 additions & 56 deletions quinn-proto/src/connection/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::{
convert::TryFrom,
fmt, io, mem,
net::{IpAddr, SocketAddr},
sync::Arc,
sync::{mpsc, Arc},
time::{Duration, Instant},
};

Expand All @@ -24,14 +24,11 @@ use crate::{
frame::{Close, Datagram, FrameStruct},
packet::{Header, LongType, Packet, PartialDecode, SpaceId},
range_set::ArrayRangeSet,
shared::{
ConnectionEvent, ConnectionEventInner, ConnectionId, EcnCodepoint, EndpointEvent,
EndpointEventInner,
},
shared::{ConnectionEvent, ConnectionId, EcnCodepoint, EndpointEvent},
token::ResetToken,
transport_parameters::TransportParameters,
Dir, EndpointConfig, Frame, Side, StreamId, Transmit, TransportError, TransportErrorCode,
VarInt, MAX_STREAM_COUNT, MIN_INITIAL_SIZE, TIMER_GRANULARITY,
ConnectionHandle, Dir, EndpointConfig, Frame, Side, StreamId, Transmit, TransportError,
TransportErrorCode, VarInt, MAX_STREAM_COUNT, MIN_INITIAL_SIZE, TIMER_GRANULARITY,
};

mod ack_frequency;
Expand Down Expand Up @@ -131,6 +128,7 @@ pub struct Connection {
server_config: Option<Arc<ServerConfig>>,
config: Arc<TransportConfig>,
rng: StdRng,
connection_events: mpsc::Receiver<ConnectionEvent>,
crypto: Box<dyn crypto::Session>,
/// The CID we initially chose, for use during the handshake
handshake_cid: ConnectionId,
Expand Down Expand Up @@ -162,7 +160,7 @@ pub struct Connection {
/// Total number of outgoing packets that have been deemed lost
lost_packets: u64,
events: VecDeque<Event>,
endpoint_events: VecDeque<EndpointEventInner>,
endpoint_events: EndpointEvents,
/// Whether the spin bit is in use for this connection
spin_enabled: bool,
/// Outgoing spin bit state
Expand Down Expand Up @@ -253,6 +251,8 @@ impl Connection {
version: u32,
allow_mtud: bool,
rng_seed: [u8; 32],
endpoint_events: EndpointEvents,
connection_events: mpsc::Receiver<ConnectionEvent>,
) -> Self {
let side = if server_config.is_some() {
Side::Server
Expand All @@ -273,6 +273,7 @@ impl Connection {
let mut this = Self {
endpoint_config,
server_config,
connection_events,
crypto,
handshake_cid: loc_cid,
rem_handshake_cid: rem_cid,
Expand Down Expand Up @@ -314,7 +315,7 @@ impl Connection {
retry_src_cid: None,
lost_packets: 0,
events: VecDeque::new(),
endpoint_events: VecDeque::new(),
endpoint_events,
spin_enabled: config.allow_spin && rng.gen_ratio(7, 8),
spin: false,
spaces: [initial_space, PacketSpace::new(now), PacketSpace::new(now)],
Expand Down Expand Up @@ -407,10 +408,10 @@ impl Connection {
None
}

/// Return endpoint-facing events
/// Whether [`Endpoint::handle_events`] must be called in the immediate future
#[must_use]
pub fn poll_endpoint_events(&mut self) -> Option<EndpointEvent> {
self.endpoint_events.pop_front().map(EndpointEvent)
pub fn poll_endpoint_events(&mut self) -> bool {
mem::take(&mut self.endpoint_events.dirty)
}

/// Provide control over streams
Expand Down Expand Up @@ -951,14 +952,20 @@ impl Connection {
SendableFrames::empty()
}

/// Process `ConnectionEvent`s generated by the associated `Endpoint`
/// Process events from the associated [`Endpoint`](crate::Endpoint)
///
/// Will execute protocol logic upon receipt of a connection event, in turn preparing signals
/// (including application `Event`s, `EndpointEvent`s and outgoing datagrams) that should be
/// extracted through the relevant methods.
pub fn handle_event(&mut self, event: ConnectionEvent) {
use self::ConnectionEventInner::*;
match event.0 {
/// (including application `Event`s, endpoint events, and outgoing datagrams) that should be
/// checked through the relevant methods.
pub fn handle_events(&mut self, now: Instant) {
while let Ok(event) = self.connection_events.try_recv() {
self.handle_event(event, now);
}
}

fn handle_event(&mut self, event: ConnectionEvent, now: Instant) {
use self::ConnectionEvent::*;
match event {
Datagram {
now,
remote,
Expand Down Expand Up @@ -1001,7 +1008,7 @@ impl Connection {
self.set_loss_detection_timer(now);
}
}
NewIdentifiers(ids, now) => {
NewIdentifiers(ids) => {
self.local_cid_state.new_cids(&ids, now);
ids.into_iter().rev().for_each(|frame| {
self.spaces[SpaceId::Data].pending.new_cids.push(frame);
Expand Down Expand Up @@ -1037,7 +1044,7 @@ impl Connection {
match timer {
Timer::Close => {
self.state = State::Drained;
self.endpoint_events.push_back(EndpointEventInner::Drained);
self.endpoint_events.push(EndpointEvent::Drained);
}
Timer::Idle => {
self.kill(ConnectionError::TimedOut);
Expand Down Expand Up @@ -1071,7 +1078,7 @@ impl Connection {
self.local_cid_state.retire_prior_to()
);
self.endpoint_events
.push_back(EndpointEventInner::NeedIdentifiers(now, num_new_cid));
.push(EndpointEvent::NeedIdentifiers(num_new_cid));
}
}
Timer::MaxAckDelay => {
Expand Down Expand Up @@ -2168,7 +2175,7 @@ impl Connection {
}
}
if !was_drained && self.state.is_drained() {
self.endpoint_events.push_back(EndpointEventInner::Drained);
self.endpoint_events.push(EndpointEvent::Drained);
// Close timer may have been started previously, e.g. if we sent a close and got a
// stateless reset in response
self.timers.stop(Timer::Close);
Expand Down Expand Up @@ -2351,10 +2358,10 @@ impl Connection {
}
if let Some(token) = params.stateless_reset_token {
self.endpoint_events
.push_back(EndpointEventInner::ResetToken(self.path.remote, token));
.push(EndpointEvent::ResetToken(self.path.remote, token));
}
self.handle_peer_params(params)?;
self.issue_first_cids(now);
self.issue_first_cids();
} else {
// Server-only
self.spaces[SpaceId::Data].pending.handshake_done = true;
Expand Down Expand Up @@ -2401,7 +2408,7 @@ impl Connection {
reason: "transport parameters missing".into(),
})?;
self.handle_peer_params(params)?;
self.issue_first_cids(now);
self.issue_first_cids();
self.init_0rtt();
}
Ok(())
Expand Down Expand Up @@ -2661,11 +2668,7 @@ impl Connection {
.local_cid_state
.on_cid_retirement(sequence, self.peer_params.issue_cids_limit())?;
self.endpoint_events
.push_back(EndpointEventInner::RetireConnectionId(
now,
sequence,
allow_more_cids,
));
.push(EndpointEvent::RetireConnectionId(sequence, allow_more_cids));
}
Frame::NewConnectionId(frame) => {
trace!(
Expand Down Expand Up @@ -2881,23 +2884,19 @@ impl Connection {

fn set_reset_token(&mut self, reset_token: ResetToken) {
self.endpoint_events
.push_back(EndpointEventInner::ResetToken(
self.path.remote,
reset_token,
));
.push(EndpointEvent::ResetToken(self.path.remote, reset_token));
self.peer_params.stateless_reset_token = Some(reset_token);
}

/// Issue an initial set of connection IDs to the peer upon connection
fn issue_first_cids(&mut self, now: Instant) {
fn issue_first_cids(&mut self) {
if self.local_cid_state.cid_len() == 0 {
return;
}

// Subtract 1 to account for the CID we supplied while handshaking
let n = self.peer_params.issue_cids_limit() - 1;
self.endpoint_events
.push_back(EndpointEventInner::NeedIdentifiers(now, n));
self.endpoint_events.push(EndpointEvent::NeedIdentifiers(n));
}

fn populate_packet(
Expand Down Expand Up @@ -3284,22 +3283,9 @@ impl Connection {

/// Decodes a packet, returning its decrypted payload, so it can be inspected in tests
#[cfg(test)]
pub(crate) fn decode_packet(&self, event: &ConnectionEvent) -> Option<Vec<u8>> {
let (first_decode, remaining) = match &event.0 {
ConnectionEventInner::Datagram {
first_decode,
remaining,
..
} => (first_decode, remaining),
_ => return None,
};

if remaining.is_some() {
panic!("Packets should never be coalesced in tests");
}

pub(crate) fn decode_packet(&self, packet: PartialDecode) -> Option<Vec<u8>> {
let decrypted_header = packet_crypto::unprotect_header(
first_decode.clone(),
packet.clone(),
&self.spaces,
self.zero_rtt_crypto.as_ref(),
self.peer_params.stateless_reset_token,
Expand Down Expand Up @@ -3372,10 +3358,9 @@ impl Connection {
/// Instruct the peer to replace previously issued CIDs by sending a NEW_CONNECTION_ID frame
/// with updated `retire_prior_to` field set to `v`
#[cfg(test)]
pub(crate) fn rotate_local_cid(&mut self, v: u64, now: Instant) {
pub(crate) fn rotate_local_cid(&mut self, v: u64) {
let n = self.local_cid_state.assign_retire_seq(v);
self.endpoint_events
.push_back(EndpointEventInner::NeedIdentifiers(now, n));
self.endpoint_events.push(EndpointEvent::NeedIdentifiers(n));
}

/// Check the current active remote CID sequence
Expand Down Expand Up @@ -3416,7 +3401,7 @@ impl Connection {
self.close_common();
self.error = Some(reason);
self.state = State::Drained;
self.endpoint_events.push_back(EndpointEventInner::Drained);
self.endpoint_events.push(EndpointEvent::Drained);
}

/// Storage size required for the largest packet known to be supported by the current path
Expand Down Expand Up @@ -3651,3 +3636,28 @@ impl SentFrames {
&& self.retransmits.is_empty(streams)
}
}

pub(crate) struct EndpointEvents {
ch: ConnectionHandle,
sender: mpsc::Sender<(ConnectionHandle, EndpointEvent)>,
dirty: bool,
}

impl EndpointEvents {
pub(crate) fn new(
ch: ConnectionHandle,
sender: mpsc::Sender<(ConnectionHandle, EndpointEvent)>,
) -> Self {
Self {
ch,
sender,
dirty: false,
}
}

fn push(&mut self, event: EndpointEvent) {
// If the endpoint has gone away, assume the caller is winding down regardless.
_ = self.sender.send((self.ch, event));
self.dirty = true;
}
}
Loading
Loading