use std::sync::atomic::Ordering;
use std::sync::{Arc, Weak};
use std::time::Duration;
use tokio::sync::{Semaphore, mpsc, watch};
use weida_core::{Error, ErrorCode, Limits, LossCause, PeerIdentity};
use weida_protocol::header::{GuaranteeSet, MAX_CURSOR_RECORD_LEN};
use weida_protocol::{
Agreed, CAPABILITY_DATAGRAM, CAPABILITY_PATH_REPORT, CreditHeader, CursorHeader, DataHeader,
ErrorHeader, FlowHeader, FrameKind, HeaderError, Hello, MAX_PREAMBLE_LEN, Preamble, ReportHead,
SubscriptionHeader, codes, decode_cursor_record, encode_frame, negotiate, parse_preamble,
};
use crate::dedup::DedupWindow;
use crate::identity::PeerChain;
use crate::listener::{Namespace, Route};
use crate::ordering::{GapDetector, Reassembler, Sequencer};
use crate::pubsub::SubRegistry;
use crate::runtime::{Exec, Shared};
use crate::stream::{Consumer, ConsumerId, CreditGrant, Incoming};
use crate::transfer::{IncomingMeta, IncomingRequest, IncomingTransfer};
use crate::transport::{Link, RecvHalf, SendHalf};
const CTL_QUEUE: usize = 1024;
pub(crate) enum Ctl {
SendUnsubscribe { path: Arc<str>, filter: String },
ReplyError { send: SendHalf, code: ErrorCode },
}
pub(crate) struct ConnCtx {
pub conn: Link,
pub ctl: mpsc::Sender<Ctl>,
pub limits: Limits,
pub namespace: Arc<Namespace>,
pub subs: Option<Arc<SubRegistry>>,
pub peer: Option<PeerIdentity>,
pub peer_chain: Option<PeerChain>,
pub exec: Exec,
pub guarantees: GuaranteeSet,
pub sequencer: Sequencer,
pub gaps: GapDetector,
pub reorder: Reassembler<Held>,
pub dedup: DedupWindow,
pub parked: crate::drain::ConnDrain,
pub reports: crate::cursor::ReportTable,
pub shared: Arc<Shared>,
pub flows: crate::flow::FlowTable,
pub established: std::time::Instant,
pub segments_out: crate::segment::SegmentNumbers,
pub segments_in: crate::segment::Newest,
pub remote: crate::report::RemoteSlot,
pub header_slots: Semaphore,
agreed: watch::Receiver<Option<Agreed>>,
}
pub(crate) type ConnHandle = Arc<ConnCtx>;
impl ConnCtx {
pub(crate) fn spawn(
conn: Link,
limits: Limits,
namespace: Arc<Namespace>,
subs: Option<Arc<SubRegistry>>,
exec: Exec,
guarantees: GuaranteeSet,
shared: Arc<Shared>,
) -> ConnHandle {
let (ctl_tx, ctl_rx) = mpsc::channel(CTL_QUEUE);
let (agreed_tx, agreed_rx) = watch::channel(None);
let agreed_tx = Arc::new(agreed_tx);
let streams_are_local = conn.streams_are_local();
let ctx = Arc::new(ConnCtx {
peer: conn.peer(),
peer_chain: conn.peer_chain(),
conn,
ctl: ctl_tx,
limits,
namespace,
subs,
exec: exec.clone(),
guarantees,
sequencer: Sequencer::new(guarantees.ordering, limits.max_sequence_scopes),
gaps: GapDetector::new(guarantees.ordering, limits.max_sequence_scopes),
reorder: Reassembler::new(
guarantees.ordering,
limits.max_reorder_hold,
limits.max_sequence_scopes,
),
dedup: DedupWindow::new(
guarantees.deduplication,
guarantees.dedup_window_ms,
limits.max_dedup_entries,
),
parked: crate::drain::ConnDrain::new(&limits, streams_are_local),
reports: crate::cursor::ReportTable::new(),
shared,
flows: crate::flow::FlowTable::new(&limits),
agreed: agreed_rx,
established: std::time::Instant::now(),
segments_out: crate::segment::SegmentNumbers::new(limits.max_sequence_scopes),
segments_in: crate::segment::Newest::new(limits.max_sequence_scopes),
remote: crate::report::RemoteSlot::default(),
header_slots: Semaphore::new(limits.header_slots()),
});
ctx.shared.drain.register(&ctx);
exec.spawn(driver(Arc::downgrade(&ctx), ctl_rx, exec.clone()));
exec.spawn(hello_deadline(Arc::clone(&ctx), Arc::clone(&agreed_tx)));
exec.spawn(accept_uni_loop(Arc::clone(&ctx), agreed_tx));
exec.spawn(accept_bi_loop(Arc::clone(&ctx)));
exec.spawn(send_hello(Arc::clone(&ctx), limits, guarantees));
if limits.datagram_receive_bytes > 0 && ctx.conn.is_quic() {
exec.spawn(crate::flow::datagram_reader(Arc::clone(&ctx)));
}
ctx
}
pub(crate) async fn negotiated(&self) -> Result<Agreed, Error> {
let mut rx = self.agreed.clone();
loop {
if let Some(agreed) = *rx.borrow_and_update() {
return Ok(agreed);
}
tokio::select! {
changed = rx.changed() => {
if changed.is_err() {
return Err(self
.conn
.close_reason()
.unwrap_or(Error::ConnectionLost(LossCause::LocallyClosed)));
}
}
reason = self.conn.closed() => return Err(reason),
}
}
}
pub(crate) fn agreed_now(&self) -> Option<Agreed> {
*self.agreed.borrow()
}
pub(crate) fn notify(&self, ctl: Ctl) {
if self.ctl.try_send(ctl).is_err() {
tracing::debug!("connection control queue full or closed; notification dropped");
}
}
pub(crate) async fn open_uni(&self) -> Result<SendHalf, Error> {
self.free_local_slots();
self.conn.open_uni().await
}
pub(crate) async fn open_bi(&self) -> Result<(SendHalf, RecvHalf), Error> {
self.free_local_slots();
self.conn.open_bi().await
}
fn free_local_slots(&self) {
if !self.conn.local_slots_exhausted() {
return;
}
let freed = self.parked.reap();
if freed > 0 {
tracing::debug!(
freed,
"reaped settled receipts to make room for another stream"
);
}
}
}
pub(crate) fn check_header_len(ctx: &ConnCtx, len: usize) -> Result<(), Error> {
match ctx.agreed_now() {
Some(agreed) => agreed
.check_header_len(len)
.map_err(|_| Error::LimitExceeded),
None => Ok(()),
}
}
pub(crate) fn conn_error(e: quinn::ConnectionError) -> Error {
match e {
quinn::ConnectionError::ApplicationClosed(frame) => match frame.error_code.into_inner() {
codes::NEGOTIATION_FAILED => {
Error::Negotiation("peer closed the connection: negotiation failed".into())
}
codes::PROTOCOL_VIOLATION => {
Error::Protocol("peer closed the connection: protocol violation".into())
}
codes::LIMIT_EXCEEDED => Error::LimitExceeded,
codes::RESTARTING => Error::ConnectionLost(LossCause::PeerRestarting),
_ => Error::ConnectionLost(LossCause::PeerClosed),
},
quinn::ConnectionError::LocallyClosed => Error::ConnectionLost(LossCause::LocallyClosed),
quinn::ConnectionError::TimedOut => Error::ConnectionLost(LossCause::IdleTimeout),
quinn::ConnectionError::Reset => Error::ConnectionLost(LossCause::Reset),
quinn::ConnectionError::TransportError(t) if is_tls_alert(t.code) => {
Error::Tls(t.to_string())
}
quinn::ConnectionError::ConnectionClosed(c) if is_tls_alert(c.error_code) => {
Error::Tls(format!("peer aborted the handshake: {c}"))
}
other => Error::Transport(other.to_string()),
}
}
fn is_tls_alert(code: quinn::TransportErrorCode) -> bool {
(0x100..0x200).contains(&u64::from(code))
}
pub(crate) fn write_error(e: quinn::WriteError) -> Error {
match e {
quinn::WriteError::Stopped(code) => codes::stop_reason(code.into_inner()).into(),
quinn::WriteError::ConnectionLost(e) => conn_error(e),
quinn::WriteError::ClosedStream => Error::Transport("stream already closed".into()),
quinn::WriteError::ZeroRttRejected => {
Error::Transport("0-RTT data rejected by the peer".into())
}
}
}
pub(crate) fn read_error(e: quinn::ReadError) -> Error {
match e {
quinn::ReadError::Reset(code) => match code.into_inner() {
codes::CANCELED => Error::Canceled,
codes::REJECTED => Error::Rejected,
codes::UNKNOWN_ENDPOINT => Error::UnknownEndpoint,
codes::UNSUPPORTED => Error::Unsupported,
other => Error::Transport(format!("peer reset the stream with code {other}")),
},
quinn::ReadError::ConnectionLost(e) => conn_error(e),
quinn::ReadError::ClosedStream => Error::Transport("stream already closed".into()),
quinn::ReadError::IllegalOrderedRead => {
Error::Transport("ordered read after unordered read".into())
}
quinn::ReadError::ZeroRttRejected => {
Error::Transport("0-RTT data rejected by the peer".into())
}
}
}
async fn driver(ctx: Weak<ConnCtx>, mut rx: mpsc::Receiver<Ctl>, exec: Exec) {
while let Some(ctl) = rx.recv().await {
let Some(ctx) = ctx.upgrade() else { break };
handle_ctl(ctx, ctl, &exec);
}
}
fn handle_ctl(ctx: ConnHandle, ctl: Ctl, exec: &Exec) {
match ctl {
Ctl::SendUnsubscribe { path, filter } => {
let header = SubscriptionHeader::new(&*path, filter).encode();
exec.spawn(async move {
if let Err(e) = write_control(&ctx.conn, FrameKind::Unsubscribe, &header).await {
tracing::debug!(error = %e, "failed to send an UNSUBSCRIBE frame");
}
});
}
Ctl::ReplyError { mut send, code } => {
exec.spawn(async move {
if let Err(e) = write_error_frame(&mut send, code).await {
tracing::debug!(error = %e, "failed to report a reply failure");
}
});
}
}
}
pub(crate) async fn write_error_frame(send: &mut SendHalf, code: ErrorCode) -> Result<(), Error> {
let frame = encode_frame(FrameKind::Error, &ErrorHeader::new(code).encode());
send.write_all(&frame).await?;
send.finish()
}
pub(crate) async fn write_control(
conn: &Link,
kind: FrameKind,
header: &[u8],
) -> Result<(), Error> {
let mut stream = if kind == FrameKind::Hello {
conn.open_control().await?
} else {
conn.open_uni().await?
};
stream.write_all(&encode_frame(kind, header)).await?;
stream.finish()?;
Ok(())
}
fn hello_for(limits: Limits, guarantees: GuaranteeSet, quic: bool) -> Hello {
let declaration = (!guarantees.is_core()).then_some(guarantees);
let mut capabilities = Vec::new();
if limits.datagram_receive_bytes > 0 {
capabilities.push(CAPABILITY_DATAGRAM);
}
if limits.path_report && quic {
capabilities.push(CAPABILITY_PATH_REPORT);
}
Hello {
guarantees_offered: declaration,
guarantees_required: declaration,
capabilities,
..Hello::v0(
limits.max_header_bytes,
u64::from(limits.max_concurrent_uni_streams),
)
}
}
async fn send_hello(ctx: ConnHandle, limits: Limits, guarantees: GuaranteeSet) {
let hello = hello_for(limits, guarantees, ctx.conn.is_quic());
if let Err(e) = write_control(&ctx.conn, FrameKind::Hello, &hello.encode()).await {
tracing::debug!(error = %e, "failed to send HELLO");
}
}
async fn hello_deadline(ctx: ConnHandle, agreed_tx: Arc<watch::Sender<Option<Agreed>>>) {
tokio::select! {
() = ctx.exec.sleep(Duration::from_millis(ctx.limits.hello_timeout_ms)) => {}
_ = ctx.conn.closed() => return,
}
if agreed_tx.borrow().is_none() {
tracing::debug!("peer HELLO did not arrive in time");
ctx.conn.close(codes::NEGOTIATION_FAILED, "hello timeout");
}
}
async fn accept_uni_loop(ctx: ConnHandle, agreed_tx: Arc<watch::Sender<Option<Agreed>>>) {
loop {
match ctx.conn.accept_uni().await {
Ok(stream) => {
if ctx.shared.drain.is_draining() {
refuse_uni(stream);
continue;
}
let ctx = Arc::clone(&ctx);
let agreed_tx = Arc::clone(&agreed_tx);
ctx.exec.clone().spawn(async move {
if let Err(e) = handle_stream(&ctx, &agreed_tx, stream).await {
tracing::debug!(error = %e, "inbound stream failed");
}
});
}
Err(e) => {
tracing::debug!(error = %e, "connection closed; uni accept loop ending");
break;
}
}
}
}
async fn accept_bi_loop(ctx: ConnHandle) {
loop {
match ctx.conn.accept_bi().await {
Ok((mut send, recv)) => {
if ctx.shared.drain.is_draining() {
refuse_uni(recv);
send.reset(codes::SHUTDOWN);
continue;
}
let ctx = Arc::clone(&ctx);
let by_path = ctx.conn.dispatch_by_path();
ctx.exec.clone().spawn(async move {
let outcome = if by_path {
handle_local(&ctx, send, recv).await
} else {
handle_bi(&ctx, send, recv).await
};
if let Err(e) = outcome {
tracing::debug!(error = %e, "inbound exchange failed");
}
});
}
Err(e) => {
tracing::debug!(error = %e, "connection closed; bidi accept loop ending");
break;
}
}
}
}
async fn handle_local(ctx: &ConnHandle, send: SendHalf, mut recv: RecvHalf) -> Result<(), Error> {
let preamble = match read_preamble_within(ctx, &mut recv).await {
Ok(preamble) => preamble,
Err(Error::Protocol(reason)) => return violation(ctx, &reason),
Err(e) => return refuse_head(recv, send, e),
};
if preamble.kind != FrameKind::Hello {
ctx.negotiated().await?;
}
let head = match read_head_within(ctx, &mut recv, &preamble).await {
Ok(Ok(head)) => head,
Ok(Err(e)) => return violation(ctx, &e.to_string()),
Err(e) => return refuse_head(recv, send, e),
};
match head {
Head::Hello(_) => violation(ctx, "HELLO is legal only on the control connection"),
Head::Error => violation(ctx, "ERROR is legal only in answer to a request"),
Head::Subscribe(header) => handle_subscription(ctx, header, true).await,
Head::Unsubscribe(header) => handle_subscription(ctx, header, false).await,
Head::Credit(header) => handle_credit(ctx, header).await,
Head::Cursor(header) => {
drop(send);
handle_cursor(ctx, recv, header).await
}
Head::Flow(header) => {
drop(send);
crate::flow::handle_flow(ctx, recv, header).await
}
Head::Report => violation(ctx, "REPORT is legal only on QUIC"),
Head::Data(decoded) => {
let Some(path) = decoded.endpoint.as_deref() else {
return violation(ctx, "DATA on a local connection must name an endpoint");
};
match ctx.namespace.lookup(path) {
Some(Route::Request(queue)) => {
let request = request_for(ctx, decoded, recv, send);
if let Err(gone) = queue.send(request).await {
tracing::debug!(
path = ?gone.0.meta().endpoint,
"endpoint went away while dispatching"
);
}
Ok(())
}
Some(Route::Raw(queue)) => {
let request = request_for(ctx, decoded, recv, send);
if let Err(gone) = queue.send(Incoming::Exchange(request)).await
&& let Incoming::Exchange(request) = gone.0
{
tracing::debug!(
path = ?request.meta().endpoint,
"acceptor went away while dispatching"
);
}
Ok(())
}
_ => {
drop(send);
dispatch_data(ctx, recv, decoded).await
}
}
}
}
}
fn refuse_uni(mut stream: RecvHalf) {
stream.stop(codes::SHUTDOWN);
}
fn refuse_cursor(mut stream: RecvHalf) -> Result<(), Error> {
stream.stop(codes::CANCELED);
Ok(())
}
async fn handle_cursor(
ctx: &ConnHandle,
mut stream: RecvHalf,
head: CursorHeader,
) -> Result<(), Error> {
let Some(tx) = ctx.reports.claim(head.report_id) else {
return refuse_cursor(stream);
};
let mut buf = [0u8; 64];
let mut pending: Vec<u8> = Vec::with_capacity(64 + MAX_CURSOR_RECORD_LEN);
loop {
match stream.read(&mut buf).await {
Ok(Some(0)) => continue,
Ok(Some(n)) => {
pending.extend_from_slice(&buf[..n]);
let mut at = 0;
while let Some((level, offset, used)) = match decode_cursor_record(&pending[at..]) {
Ok(record) => record,
Err(e) => return violation(ctx, &e.to_string()),
} {
at += used;
tx.send_if_modified(|shared| shared.advance(level, offset));
}
pending.drain(..at);
}
Ok(None) => {
if !pending.is_empty() {
return violation(ctx, "a cursor stream ended inside a record");
}
break;
}
Err(e) => {
tracing::debug!(error = %e, report_id = head.report_id, "cursor stream ended");
break;
}
}
}
ctx.reports.release(head.report_id);
drop(tx);
Ok(())
}
const INLINE_HEADER: usize = 192;
const HEADER_STEP: usize = 2048;
pub(crate) enum HeaderBytes {
Inline {
buf: [u8; INLINE_HEADER],
len: usize,
},
Heap(Vec<u8>),
}
impl std::ops::Deref for HeaderBytes {
type Target = [u8];
fn deref(&self) -> &[u8] {
match self {
HeaderBytes::Inline { buf, len } => &buf[..*len],
HeaderBytes::Heap(bytes) => bytes,
}
}
}
enum Head {
Hello(Hello),
Data(DataHeader),
Error,
Subscribe(SubscriptionHeader),
Unsubscribe(SubscriptionHeader),
Credit(CreditHeader),
Cursor(CursorHeader),
Flow(FlowHeader),
Report,
}
fn decode_head(kind: FrameKind, bytes: &[u8]) -> Result<Head, HeaderError> {
Ok(match kind {
FrameKind::Hello => Head::Hello(Hello::decode(bytes)?),
FrameKind::Data => Head::Data(DataHeader::decode(bytes)?),
FrameKind::Error => Head::Error,
FrameKind::Subscribe => Head::Subscribe(SubscriptionHeader::decode(bytes)?),
FrameKind::Unsubscribe => Head::Unsubscribe(SubscriptionHeader::decode(bytes)?),
FrameKind::Credit => Head::Credit(CreditHeader::decode(bytes)?),
FrameKind::Cursor => Head::Cursor(CursorHeader::decode(bytes)?),
FrameKind::Flow => Head::Flow(FlowHeader::decode(bytes)?),
FrameKind::Report => {
ReportHead::decode(bytes)?;
Head::Report
}
})
}
async fn fill(stream: &mut RecvHalf, buf: &mut [u8], part: &str) -> Result<(), Error> {
let mut filled = 0;
while filled < buf.len() {
match stream.read(&mut buf[filled..]).await? {
Some(0) => continue,
Some(n) => filled += n,
None => return Err(Error::Protocol(format!("stream ended inside the {part}"))),
}
}
Ok(())
}
async fn read_preamble(stream: &mut RecvHalf, max_header_bytes: u64) -> Result<Preamble, Error> {
let mut head = [0u8; MAX_PREAMBLE_LEN];
fill(stream, &mut head[..3], "preamble").await?;
let end = 2 + (1usize << (head[2] >> 6));
fill(stream, &mut head[3..end], "preamble").await?;
parse_preamble(&head[..end], max_header_bytes)
.map(|(preamble, _)| preamble)
.map_err(|e| Error::Protocol(e.to_string()))
}
async fn read_header(stream: &mut RecvHalf, preamble: &Preamble) -> Result<HeaderBytes, Error> {
let len = usize::try_from(preamble.header_len)
.map_err(|_| Error::Protocol("header length does not fit this platform".into()))?;
if len <= INLINE_HEADER {
let mut buf = [0u8; INLINE_HEADER];
fill(stream, &mut buf[..len], "header").await?;
return Ok(HeaderBytes::Inline { buf, len });
}
let mut bytes: Vec<u8> = Vec::new();
while bytes.len() < len {
let start = bytes.len();
bytes.resize(start + (len - start).min(HEADER_STEP), 0);
match stream.read(&mut bytes[start..]).await? {
Some(n) => bytes.truncate(start + n),
None => return Err(Error::Protocol("stream ended inside the header".into())),
}
}
Ok(HeaderBytes::Heap(bytes))
}
pub(crate) async fn read_frame(
stream: &mut RecvHalf,
max_header_bytes: u64,
) -> Result<(Preamble, HeaderBytes), Error> {
let preamble = read_preamble(stream, max_header_bytes).await?;
let header = read_header(stream, &preamble).await?;
Ok((preamble, header))
}
async fn in_header_phase<T>(
ctx: &ConnCtx,
read: impl Future<Output = Result<T, Error>>,
) -> Result<T, Error> {
let Ok(_slot) = ctx.header_slots.acquire().await else {
return Err(Error::ConnectionLost(LossCause::LocallyClosed));
};
let deadline = Duration::from_millis(ctx.limits.header_timeout_ms);
ctx.exec.within(deadline, read).await.unwrap_or_else(|| {
Err(Error::Transport(
"the frame head did not arrive in time".into(),
))
})
}
async fn read_preamble_within(ctx: &ConnCtx, stream: &mut RecvHalf) -> Result<Preamble, Error> {
in_header_phase(ctx, read_preamble(stream, ctx.limits.max_header_bytes)).await
}
async fn read_header_within<T>(
ctx: &ConnCtx,
stream: &mut RecvHalf,
preamble: &Preamble,
decode: impl FnOnce(&[u8]) -> Result<T, HeaderError>,
) -> Result<Result<T, HeaderError>, Error> {
in_header_phase(ctx, async {
let header = read_header(stream, preamble).await?;
Ok(decode(&header))
})
.await
}
async fn read_head_within(
ctx: &ConnCtx,
stream: &mut RecvHalf,
preamble: &Preamble,
) -> Result<Result<Head, HeaderError>, Error> {
let kind = preamble.kind;
read_header_within(ctx, stream, preamble, |bytes| decode_head(kind, bytes)).await
}
fn refuse_stream(mut stream: RecvHalf, error: Error) -> Result<(), Error> {
stream.stop(codes::CANCELED);
Err(error)
}
async fn handle_stream(
ctx: &ConnHandle,
agreed_tx: &watch::Sender<Option<Agreed>>,
mut stream: RecvHalf,
) -> Result<(), Error> {
let preamble = match read_preamble_within(ctx, &mut stream).await {
Ok(preamble) => preamble,
Err(Error::Protocol(reason)) => return violation(ctx, &reason),
Err(e) => return refuse_stream(stream, e),
};
if preamble.kind != FrameKind::Hello {
ctx.negotiated().await?;
}
let head = match read_head_within(ctx, &mut stream, &preamble).await {
Ok(Ok(head)) => head,
Ok(Err(e)) => return violation(ctx, &e.to_string()),
Err(e) => return refuse_stream(stream, e),
};
match head {
Head::Hello(theirs) => handle_hello(ctx, agreed_tx, &theirs),
Head::Data(header) => dispatch_data(ctx, stream, header).await,
Head::Error => violation(
ctx,
"ERROR is legal only on the reply half of a bidirectional stream",
),
Head::Subscribe(header) => handle_subscription(ctx, header, true).await,
Head::Unsubscribe(header) => handle_subscription(ctx, header, false).await,
Head::Credit(header) => handle_credit(ctx, header).await,
Head::Cursor(header) => handle_cursor(ctx, stream, header).await,
Head::Flow(header) => crate::flow::handle_flow(ctx, stream, header).await,
Head::Report => crate::report::receive_reports(ctx, stream).await,
}
}
pub(crate) fn violation(ctx: &ConnHandle, reason: &str) -> Result<(), Error> {
tracing::debug!(reason, "closing connection: protocol violation");
ctx.conn.close(codes::PROTOCOL_VIOLATION, reason);
Err(Error::Protocol(reason.to_owned()))
}
async fn handle_subscription(
ctx: &ConnHandle,
header: SubscriptionHeader,
subscribe: bool,
) -> Result<(), Error> {
let Some(subs) = ctx.subs.as_ref() else {
tracing::debug!(
endpoint = ?header.endpoint,
"ignoring a subscription frame: this side publishes nothing"
);
return Ok(());
};
let conn_id = ctx.conn.stable_id();
if let Some(Route::Radio(hub)) = ctx.namespace.lookup(&header.endpoint) {
if subscribe {
let joined = hub.join(
ctx,
header.filter,
header.max_age_ms,
header.max_layer,
|| subs.reserve(ctx),
);
if joined.is_err() {
return too_many_subscriptions(ctx);
}
} else {
hub.leave(conn_id, &header.filter);
}
return Ok(());
}
if let Some(Route::Raw(queue)) = ctx.namespace.lookup(&header.endpoint) {
if subscribe {
if ctx
.namespace
.note_consumer(conn_id, &header.endpoint, &header.filter)
{
if subs.reserve(ctx).is_err() {
return too_many_subscriptions(ctx);
}
if ctx.conn.close_reason().is_some() {
ctx.namespace
.forget_consumer(conn_id, &header.endpoint, &header.filter);
return Ok(());
}
let consumer = Consumer::new(
Arc::clone(ctx),
Arc::from(header.endpoint.as_str()),
header.filter,
);
if queue.send(Incoming::Subscribed(consumer)).await.is_err() {
tracing::debug!(endpoint = ?header.endpoint, "acceptor went away; subscription dropped");
}
}
} else if ctx
.namespace
.forget_consumer(conn_id, &header.endpoint, &header.filter)
{
subs.release(conn_id);
let gone = Incoming::Unsubscribed {
id: ConsumerId::from_conn(conn_id),
filter: Some(header.filter),
};
if queue.send(gone).await.is_err() {
tracing::debug!(endpoint = ?header.endpoint, "acceptor went away; unsubscribe dropped");
}
}
return Ok(());
}
if subscribe {
if subs
.subscribe(&header.endpoint, ctx, header.filter)
.is_err()
{
return too_many_subscriptions(ctx);
}
} else {
subs.unsubscribe(&header.endpoint, conn_id, &header.filter);
}
Ok(())
}
fn too_many_subscriptions(ctx: &ConnHandle) -> Result<(), Error> {
tracing::debug!(
max = ctx.limits.max_subscriptions,
"subscription limit reached; closing the connection"
);
ctx.conn.close(
codes::LIMIT_EXCEEDED,
"too many subscriptions on one connection",
);
Err(Error::LimitExceeded)
}
async fn handle_credit(ctx: &ConnHandle, header: CreditHeader) -> Result<(), Error> {
let Some(Route::Raw(queue)) = ctx.namespace.lookup(&header.endpoint) else {
tracing::debug!(
endpoint = ?header.endpoint,
"ignoring a credit frame: no queue serves this path"
);
return Ok(());
};
let grant = Incoming::Credit(CreditGrant {
id: ConsumerId::from_conn(ctx.conn.stable_id()),
filter: header.filter,
limit: header.limit,
});
if queue.send(grant).await.is_err() {
tracing::debug!(endpoint = ?header.endpoint, "acceptor went away; credit dropped");
}
Ok(())
}
pub(crate) struct Departure {
id: ConsumerId,
queues: Vec<(Arc<str>, mpsc::Sender<Incoming>)>,
}
pub(crate) fn take_departure(ctx: &ConnCtx) -> Departure {
let conn_id = ctx.conn.stable_id();
let queues = ctx
.namespace
.take_consumer_routes(conn_id)
.into_iter()
.filter_map(|(path, route)| match route {
Route::Raw(queue) => Some((path, queue)),
_ => None,
})
.collect();
Departure {
id: ConsumerId::from_conn(conn_id),
queues,
}
}
impl Departure {
pub(crate) fn is_empty(&self) -> bool {
self.queues.is_empty()
}
pub(crate) async fn announce(self) {
for (path, queue) in self.queues {
let gone = Incoming::Unsubscribed {
id: self.id,
filter: None,
};
if queue.send(gone).await.is_err() {
tracing::debug!(path = ?path, "acceptor went away before its consumer did");
}
}
}
}
fn handle_hello(
ctx: &ConnHandle,
agreed_tx: &watch::Sender<Option<Agreed>>,
theirs: &Hello,
) -> Result<(), Error> {
if agreed_tx.borrow().is_some() {
return violation(ctx, "a second HELLO on one connection");
}
let ours = hello_for(ctx.limits, ctx.guarantees, ctx.conn.is_quic());
match negotiate(&ours, theirs) {
Ok(agreed) => {
let first = agreed_tx.send_if_modified(|slot| {
if slot.is_some() {
return false;
}
*slot = Some(agreed);
true
});
if !first {
return violation(ctx, "a second HELLO on one connection");
}
tracing::debug!(
version = agreed.version,
send_max_header_bytes = agreed.send_max_header_bytes,
"negotiated"
);
if agreed.path_report {
ctx.exec
.spawn(crate::report::send_reports(ConnHandle::clone(ctx)));
}
Ok(())
}
Err(e) => {
tracing::debug!(error = %e, "negotiation failed");
ctx.conn.close(codes::NEGOTIATION_FAILED, &e.to_string());
Err(e.into())
}
}
}
async fn dispatch_data(
ctx: &ConnHandle,
mut stream: RecvHalf,
header: DataHeader,
) -> Result<(), Error> {
let (sequence, producer) = (header.sequence, header.producer);
let mut meta = Arc::new(IncomingMeta::from_header(
header,
ctx.peer.clone(),
ctx.peer_chain.clone(),
));
let Some(path) = meta.endpoint.as_deref() else {
return violation(ctx, "DATA on a unidirectional stream must name an endpoint");
};
let topic = meta.topic.as_deref();
if ctx.dedup.is_duplicate(producer, path, topic, sequence) {
ctx.shared.duplicates.fetch_add(1, Ordering::Relaxed);
tracing::debug!(path, sequence = ?sequence, "duplicate suppressed");
return stream.discard().await;
}
if ctx.reorder.enabled() {
let held = Held {
stream,
meta: Arc::clone(&meta),
};
let released = ctx.reorder.admit(path, topic, sequence, held);
drop(meta);
for (held, gap) in released {
let mut meta = held.meta;
if gap.is_some() {
Arc::make_mut(&mut meta).gap = gap;
}
dispatch(
ctx,
IncomingTransfer::new(held.stream, meta, Arc::clone(ctx)),
)
.await;
}
return Ok(());
}
let gap = sequence.and_then(|seq| ctx.gaps.observe(path, topic, seq));
if gap.is_some() {
Arc::make_mut(&mut meta).gap = gap;
}
dispatch(ctx, IncomingTransfer::new(stream, meta, Arc::clone(ctx))).await;
Ok(())
}
pub(crate) struct Held {
stream: RecvHalf,
meta: Arc<IncomingMeta>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Refusal {
pub(crate) code: ErrorCode,
pub(crate) stop: u64,
}
impl Refusal {
pub(crate) const UNKNOWN: Refusal = Refusal {
code: ErrorCode::UnknownEndpoint,
stop: codes::UNKNOWN_ENDPOINT,
};
pub(crate) const WRONG_SHAPE: Refusal = Refusal {
code: ErrorCode::Unsupported,
stop: codes::UNSUPPORTED,
};
pub(crate) const PAIR_TAKEN: Refusal = Refusal {
code: ErrorCode::Rejected,
stop: codes::LIMIT_EXCEEDED,
};
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Wanted {
OneWay,
Exchange,
Flow,
}
pub(crate) fn refusal_for(route: Option<&Route>, wanted: Wanted) -> Option<Refusal> {
match (route, wanted) {
(None, _) => Some(Refusal::UNKNOWN),
(Some(Route::Raw(_)), _) => None,
(Some(Route::Transfer(_) | Route::Pair { .. } | Route::Dish(_)), Wanted::OneWay) => None,
(Some(Route::Request(_)), Wanted::Exchange) => None,
(Some(Route::Dish(_)), Wanted::Flow) => None,
(
Some(
Route::Request(_)
| Route::Transfer(_)
| Route::Pub
| Route::Pair { .. }
| Route::Radio(_)
| Route::Dish(_),
),
_,
) => Some(Refusal::WRONG_SHAPE),
}
}
async fn dispatch(ctx: &ConnHandle, transfer: IncomingTransfer) {
let meta = transfer.meta_arc();
let Some(path) = meta.endpoint.as_deref() else {
transfer.refuse(Refusal::UNKNOWN.stop);
return;
};
let route = ctx.namespace.lookup(path);
if let Some(refusal) = refusal_for(route.as_ref(), Wanted::OneWay) {
tracing::debug!(path, ?refusal, "the path does not serve a one-way transfer");
transfer.refuse(refusal.stop);
return;
}
if !matches!(route, Some(Route::Dish(_)))
&& let (Some(topic), Some(segment)) =
(transfer.meta().topic.as_deref(), transfer.meta().segment)
&& !ctx
.segments_in
.fresh(path, topic, segment, transfer.meta().layer.unwrap_or(0))
{
tracing::debug!(
path,
topic,
segment,
"a segment not newer than one delivered here is refused"
);
transfer.refuse(codes::CANCELED);
return;
}
match route {
Some(Route::Transfer(queue)) => {
if let Err(e) = queue.send(transfer).await {
tracing::debug!(path, "endpoint went away while dispatching");
e.0.refuse(Refusal::UNKNOWN.stop);
}
}
Some(Route::Raw(queue)) => {
if let Err(e) = queue.send(Incoming::Stream(transfer)).await {
tracing::debug!(path, "acceptor went away while dispatching");
if let Incoming::Stream(t) = e.0 {
t.refuse(Refusal::UNKNOWN.stop);
}
}
}
Some(Route::Pair { queue, owner }) => {
if !owner.claim(ctx) {
tracing::debug!(path, "a paired endpoint already has its peer");
transfer.refuse(Refusal::PAIR_TAKEN.stop);
return;
}
if let Err(e) = queue.send(transfer).await {
tracing::debug!(path, "endpoint went away while dispatching");
e.0.refuse(Refusal::UNKNOWN.stop);
}
}
Some(Route::Dish(route)) => crate::radio::deliver_segment(ctx, path, &route, transfer),
Some(Route::Request(_) | Route::Pub | Route::Radio(_)) | None => {
unreachable!("refusal_for refuses every route that cannot serve a one-way transfer")
}
}
}
fn request_for(
ctx: &ConnHandle,
header: DataHeader,
recv: RecvHalf,
send: SendHalf,
) -> IncomingRequest {
IncomingRequest::new(
IncomingTransfer::new(
recv,
Arc::new(IncomingMeta::from_header(
header,
ctx.peer.clone(),
ctx.peer_chain.clone(),
)),
Arc::clone(ctx),
),
send,
Arc::clone(ctx),
)
}
fn refuse_head(mut recv: RecvHalf, mut send: SendHalf, error: Error) -> Result<(), Error> {
recv.stop(codes::CANCELED);
send.reset(codes::CANCELED);
Err(error)
}
async fn handle_bi(ctx: &ConnHandle, mut send: SendHalf, mut recv: RecvHalf) -> Result<(), Error> {
let preamble = match read_preamble_within(ctx, &mut recv).await {
Ok(preamble) => preamble,
Err(Error::Protocol(reason)) => return violation(ctx, &reason),
Err(e) => return refuse_head(recv, send, e),
};
if preamble.kind != FrameKind::Data {
return violation(
ctx,
&format!("{} may not open a bidirectional stream", preamble.kind),
);
}
ctx.negotiated().await?;
let header = match read_header_within(ctx, &mut recv, &preamble, DataHeader::decode).await {
Ok(Ok(header)) => header,
Ok(Err(e)) => return violation(ctx, &e.to_string()),
Err(e) => return refuse_head(recv, send, e),
};
let Some(path) = header.endpoint.as_deref() else {
return violation(
ctx,
"the initiating half of an exchange must name an endpoint",
);
};
let route = ctx.namespace.lookup(path);
if let Some(refusal) = refusal_for(route.as_ref(), Wanted::Exchange) {
tracing::debug!(path = ?path, ?refusal, "the path does not serve an exchange");
recv.stop(refusal.stop);
if let Err(e) = write_error_frame(&mut send, refusal.code).await {
tracing::debug!(error = %e, "failed to refuse an exchange");
}
return Ok(());
}
let request = request_for(ctx, header, recv, send);
match route {
Some(Route::Request(queue)) => {
if let Err(gone) = queue.send(request).await {
tracing::debug!(
path = ?gone.0.meta().endpoint,
"endpoint went away while dispatching"
);
}
}
Some(Route::Raw(queue)) => {
if let Err(gone) = queue.send(Incoming::Exchange(request)).await
&& let Incoming::Exchange(request) = gone.0
{
tracing::debug!(
path = ?request.meta().endpoint,
"acceptor went away while dispatching"
);
}
}
Some(
Route::Transfer(_) | Route::Pub | Route::Pair { .. } | Route::Radio(_) | Route::Dish(_),
)
| None => {
unreachable!("refusal_for refuses every route that cannot serve an exchange")
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::{
ConnCtx, ConnHandle, Refusal, Wanted, handle_subscription, read_header_within,
read_preamble_within, refusal_for, take_departure,
};
use crate::listener::{Namespace, PairOwner, Route};
use crate::pubsub::SubRegistry;
use crate::runtime::{Exec, Shared};
use crate::transport::{Link, RecvHalf};
use std::sync::Arc;
use std::sync::atomic::AtomicU64;
use tokio::sync::mpsc;
use weida_core::Limits;
use weida_protocol::header::{GuaranteeSet, OrderingMode};
use weida_protocol::{DataHeader, FrameKind, SubscriptionHeader, encode_frame};
fn transfer() -> Route {
Route::Transfer(mpsc::channel(1).0)
}
fn request() -> Route {
Route::Request(mpsc::channel(1).0)
}
fn raw() -> Route {
Route::Raw(mpsc::channel(1).0)
}
fn pair() -> Route {
Route::Pair {
queue: mpsc::channel(1).0,
owner: Arc::new(PairOwner::new()),
}
}
#[test]
fn every_route_mismatch_earns_the_refusal_the_protocol_names() {
assert_eq!(refusal_for(None, Wanted::OneWay), Some(Refusal::UNKNOWN));
assert_eq!(refusal_for(None, Wanted::Exchange), Some(Refusal::UNKNOWN));
assert_eq!(refusal_for(Some(&raw()), Wanted::OneWay), None);
assert_eq!(refusal_for(Some(&raw()), Wanted::Exchange), None);
for route in [transfer(), pair()] {
assert_eq!(refusal_for(Some(&route), Wanted::OneWay), None);
assert_eq!(
refusal_for(Some(&route), Wanted::Exchange),
Some(Refusal::WRONG_SHAPE)
);
}
assert_eq!(refusal_for(Some(&request()), Wanted::Exchange), None);
assert_eq!(
refusal_for(Some(&request()), Wanted::OneWay),
Some(Refusal::WRONG_SHAPE)
);
assert_eq!(
refusal_for(Some(&Route::Pub), Wanted::OneWay),
Some(Refusal::WRONG_SHAPE)
);
assert_eq!(
refusal_for(Some(&Route::Pub), Wanted::Exchange),
Some(Refusal::WRONG_SHAPE)
);
assert_eq!(refusal_for(None, Wanted::Flow), Some(Refusal::UNKNOWN));
assert_eq!(refusal_for(Some(&raw()), Wanted::Flow), None);
for route in [transfer(), pair(), request(), Route::Pub] {
assert_eq!(
refusal_for(Some(&route), Wanted::Flow),
Some(Refusal::WRONG_SHAPE)
);
}
let radio = Route::Radio(Arc::new(crate::radio::RadioHub::new(
"/r",
weida_core::Limits::default(),
)));
for wanted in [Wanted::OneWay, Wanted::Exchange, Wanted::Flow] {
assert_eq!(
refusal_for(Some(&radio), wanted),
Some(Refusal::WRONG_SHAPE)
);
}
}
#[test]
fn the_three_refusals_are_distinct_on_the_wire() {
use weida_protocol::codes;
assert_eq!(Refusal::UNKNOWN.stop, codes::UNKNOWN_ENDPOINT);
assert_eq!(Refusal::WRONG_SHAPE.stop, codes::UNSUPPORTED);
assert_eq!(Refusal::PAIR_TAKEN.stop, codes::LIMIT_EXCEEDED);
assert_ne!(Refusal::UNKNOWN, Refusal::WRONG_SHAPE);
assert_ne!(Refusal::WRONG_SHAPE, Refusal::PAIR_TAKEN);
}
async fn connection(
namespace: &Arc<Namespace>,
subs: &Arc<SubRegistry>,
bus: &str,
) -> (ConnHandle, crate::inproc::LocalConn) {
let mut dials = crate::inproc::bind(bus).expect("bus");
let dialled = crate::inproc::dial(bus, 255, 1024).expect("dial");
let accepted = dials.recv().await.expect("accepted end");
let shared = Arc::new(Shared {
duplicates: AtomicU64::new(0),
expired: AtomicU64::new(0),
drain: crate::drain::DrainState::new(),
});
let ctx = ConnCtx::spawn(
Link::Local(accepted),
Limits::default(),
Arc::clone(namespace),
Some(Arc::clone(subs)),
Exec::current().expect("a tokio runtime"),
GuaranteeSet::CORE,
shared,
);
(ctx, dialled)
}
#[tokio::test]
async fn a_queue_subscription_handled_after_its_connection_closed_leaves_no_record() {
let namespace = Arc::new(Namespace::new());
let subs = Arc::new(SubRegistry::new(Limits::default(), OrderingMode::None));
let (queue, mut announced) = mpsc::channel(8);
namespace
.register("/q", Route::Raw(queue))
.expect("register");
let (ctx, _dialled) = connection(&namespace, &subs, "conn-unit-closed-subscribe").await;
let conn_id = ctx.conn.stable_id();
ctx.conn.close(
weida_protocol::codes::SHUTDOWN,
"closed before its SUBSCRIBE was handled",
);
take_departure(&ctx).announce().await;
handle_subscription(&ctx, SubscriptionHeader::new("/q", "a.#"), true)
.await
.expect("nothing is wrong with the frame");
assert!(
namespace.take_consumer_routes(conn_id).is_empty(),
"a record made now would never be removed"
);
assert!(
announced.try_recv().is_err(),
"the queue is told of nothing"
);
}
#[tokio::test]
async fn a_header_is_decoded_while_its_slot_is_held() {
let namespace = Arc::new(Namespace::new());
let subs = Arc::new(SubRegistry::new(Limits::default(), OrderingMode::None));
let (ctx, dialled) = connection(&namespace, &subs, "conn-unit-header-slot").await;
let mut send = ctx.open_uni().await.expect("open");
let frame = encode_frame(FrameKind::Data, &DataHeader::addressed("/q").encode());
send.write_all(&frame).await.expect("write");
let mut recv = RecvHalf::Local(dialled.accept_uni().await.expect("accept"));
let preamble = read_preamble_within(&ctx, &mut recv)
.await
.expect("preamble");
let free = ctx.header_slots.available_permits();
let mut during = None;
let header = read_header_within(&ctx, &mut recv, &preamble, |bytes| {
during = Some(ctx.header_slots.available_permits());
DataHeader::decode(bytes)
})
.await
.expect("the head arrived")
.expect("it decodes");
assert_eq!(header.endpoint.as_deref(), Some("/q"));
assert_eq!(during, Some(free - 1), "decoded while the slot was held");
assert_eq!(
ctx.header_slots.available_permits(),
free,
"and the slot is given back after"
);
}
}