use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use std::io;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, PoisonError, RwLock, Weak};
use std::time::{Duration, Instant};
use quinn::VarInt;
use tokio::sync::{OwnedSemaphorePermit, Semaphore, mpsc, watch};
use weida_core::{EndpointAddr, Error, Fingerprint, Limits, RELAY_PATH, validate_endpoint_path};
use weida_protocol::codes;
use weida_protocol::header::GuaranteeSet;
use crate::config::{ClientTls, ServerTls};
use crate::conn::ConnCtx;
use crate::endpoint::{
BusMember, BusState, Endpoint, PairState, Paired, PubState, Publisher, PullState, Puller,
RepState, Replier, RespondState, Respondent,
};
use crate::handoff::{self, Handoff, HandoverSocket};
use crate::inproc;
use crate::network::{AddrLease, BoundSocket};
use crate::pubsub::SubRegistry;
use crate::relay::{RegisterAttach, Relay, RelaySocket};
use crate::runtime::{Exec, RuntimeInner, Shared};
use crate::stream::{Acceptor, Incoming, Peer};
use crate::tls;
use crate::transfer::{IncomingRequest, IncomingTransfer};
use crate::transport::{Link, QuicLink};
pub(crate) enum Route {
Request(mpsc::Sender<IncomingRequest>),
Transfer(mpsc::Sender<IncomingTransfer>),
Raw(mpsc::Sender<Incoming>),
Pub,
Pair {
queue: mpsc::Sender<IncomingTransfer>,
owner: Arc<PairOwner>,
},
Radio(Arc<crate::radio::RadioHub>),
Dish(crate::radio::DishRoute),
}
pub(crate) struct PairOwner {
id: AtomicU64,
conn: watch::Sender<Option<Weak<ConnCtx>>>,
}
impl PairOwner {
pub(crate) fn new() -> PairOwner {
PairOwner {
id: AtomicU64::new(0),
conn: watch::channel(None).0,
}
}
pub(crate) fn claim(&self, conn: &Arc<ConnCtx>) -> bool {
let id = conn.conn.stable_id() as u64 + 1;
loop {
match self
.id
.compare_exchange(0, id, Ordering::AcqRel, Ordering::Acquire)
{
Ok(_) => {
self.conn.send_replace(Some(Arc::downgrade(conn)));
return true;
}
Err(held) if held == id => return true,
Err(held) => {
if self.holder_is_live() {
return false;
}
if self
.id
.compare_exchange(held, 0, Ordering::AcqRel, Ordering::Acquire)
.is_ok()
{
self.conn.send_replace(None);
}
}
}
}
}
fn holder_is_live(&self) -> bool {
let held = self.conn.borrow().clone();
held.and_then(|weak| weak.upgrade())
.is_some_and(|ctx| ctx.conn.close_reason().is_none())
}
pub(crate) async fn peer(&self) -> Result<Arc<ConnCtx>, Error> {
let mut rx = self.conn.subscribe();
loop {
if let Some(weak) = rx.borrow_and_update().clone() {
return weak.upgrade().ok_or(Error::NotConnected);
}
rx.changed().await.map_err(|_| Error::NotConnected)?;
}
}
}
type ConsumerFilters = HashMap<usize, HashMap<Arc<str>, HashSet<String>>>;
pub(crate) struct Namespace {
routes: RwLock<HashMap<Arc<str>, Route>>,
consumers: RwLock<ConsumerFilters>,
}
impl Namespace {
pub(crate) fn new() -> Namespace {
Namespace {
routes: RwLock::new(HashMap::new()),
consumers: RwLock::new(HashMap::new()),
}
}
pub(crate) fn lookup(&self, path: &str) -> Option<Route> {
self.routes
.read()
.expect("namespace lock poisoned")
.get(path)
.map(Route::clone_sender)
}
pub(crate) fn register(&self, path: &str, route: Route) -> Result<(), Error> {
let mut routes = self.routes.write().expect("namespace lock poisoned");
match routes.entry(Arc::from(path)) {
Entry::Occupied(_) => Err(Error::AlreadyRegistered),
Entry::Vacant(slot) => {
slot.insert(route);
Ok(())
}
}
}
pub(crate) fn unregister(&self, path: &str) {
self.routes
.write()
.expect("namespace lock poisoned")
.remove(path);
}
pub(crate) fn note_consumer(&self, conn_id: usize, path: &str, filter: &str) -> bool {
let mut consumers = self.consumers.write().expect("namespace lock poisoned");
let paths = consumers.entry(conn_id).or_default();
match paths.get_mut(path) {
Some(filters) if filters.contains(filter) => false,
Some(filters) => filters.insert(filter.to_owned()),
None => {
paths.insert(Arc::from(path), HashSet::from([filter.to_owned()]));
true
}
}
}
pub(crate) fn forget_consumer(&self, conn_id: usize, path: &str, filter: &str) -> bool {
let mut consumers = self.consumers.write().expect("namespace lock poisoned");
let Some(paths) = consumers.get_mut(&conn_id) else {
return false;
};
let Some(filters) = paths.get_mut(path) else {
return false;
};
let held = filters.remove(filter);
if filters.is_empty() {
paths.remove(path);
}
if paths.is_empty() {
consumers.remove(&conn_id);
}
held
}
pub(crate) fn take_consumer_routes(&self, conn_id: usize) -> Vec<(Arc<str>, Route)> {
let taken = self
.consumers
.write()
.expect("namespace lock poisoned")
.remove(&conn_id);
let Some(paths) = taken else {
return Vec::new();
};
let routes = self.routes.read().expect("namespace lock poisoned");
paths
.into_keys()
.filter_map(|path| {
let route = routes.get(&path)?.clone_sender();
Some((path, route))
})
.collect()
}
}
impl Route {
fn clone_sender(&self) -> Route {
match self {
Route::Request(tx) => Route::Request(tx.clone()),
Route::Transfer(tx) => Route::Transfer(tx.clone()),
Route::Raw(tx) => Route::Raw(tx.clone()),
Route::Pair { queue, owner } => Route::Pair {
queue: queue.clone(),
owner: Arc::clone(owner),
},
Route::Pub => Route::Pub,
Route::Radio(hub) => Route::Radio(Arc::clone(hub)),
Route::Dish(route) => Route::Dish(route.clone()),
}
}
}
pub(crate) struct ListenerInner {
pub(crate) runtime: Arc<RuntimeInner>,
pub(crate) namespace: Arc<Namespace>,
pub(crate) subs: Arc<SubRegistry>,
}
#[derive(Clone)]
pub struct Listener {
inner: Arc<ListenerInner>,
}
impl Listener {
pub(crate) fn new(runtime: Arc<RuntimeInner>) -> Listener {
let limits = runtime.config.limits;
let ordering = runtime.config.guarantees.ordering;
Listener {
inner: Arc::new(ListenerInner {
runtime,
namespace: Arc::new(Namespace::new()),
subs: Arc::new(SubRegistry::new(limits, ordering)),
}),
}
}
pub async fn bind_quic(
&self,
addr: SocketAddr,
tls: impl Into<ServerTls>,
) -> Result<Binding, Error> {
let server_config = tls::server_config(&tls.into(), &self.inner.runtime.config.limits)?;
let socket = self
.inner
.runtime
.config
.network
.bind_server(addr, &self.inner.runtime.exec)?;
self.serve_quic(socket, server_config)
}
pub async fn bind_quic_socket(
&self,
socket: std::net::UdpSocket,
tls: impl Into<ServerTls>,
) -> Result<Binding, Error> {
let server_config = tls::server_config(&tls.into(), &self.inner.runtime.config.limits)?;
self.serve_quic(
BoundSocket::os(socket, &self.inner.runtime.exec)?,
server_config,
)
}
pub async fn bind_relay(
&self,
relay: &str,
via: impl Into<ClientTls>,
tls: impl Into<ServerTls>,
) -> Result<Binding, Error> {
let runtime = &self.inner.runtime;
let server_config = tls::server_config(&tls.into(), &runtime.config.limits)?;
if EndpointAddr::parse(relay)?.path != RELAY_PATH {
return Err(Error::InvalidAddress(format!(
"a relay serves on {RELAY_PATH}: {relay:?}"
)));
}
let socket = Arc::new(RelaySocket::new());
let peer = Peer::with_attach(
Arc::clone(runtime),
Arc::new(via.into()),
Some(Arc::new(RegisterAttach::new(&socket))),
);
peer.connect(relay).await?;
socket.set_peer(peer);
let served = BoundSocket::relay(Arc::clone(&socket), &runtime.exec)
.and_then(|bound| self.serve_quic(bound, server_config));
match served {
Ok(mut binding) => {
binding.relay = Some(socket);
Ok(binding)
}
Err(e) => {
socket.release();
Err(e)
}
}
}
fn serve_quic(
&self,
socket: BoundSocket,
server_config: quinn::ServerConfig,
) -> Result<Binding, Error> {
let exec = self.inner.runtime.exec.clone();
let BoundSocket {
inner,
runtime,
lease,
} = socket;
let (endpoint, socket) = {
let _guard = exec.enter();
let socket = Arc::new(HandoverSocket::new(inner));
let endpoint = quinn::Endpoint::new_with_abstract_socket(
quinn::EndpointConfig::default(),
Some(server_config),
Arc::clone(&socket) as Arc<dyn quinn::AsyncUdpSocket>,
runtime,
)
.map_err(Error::Io)?;
(endpoint, socket)
};
let local_addr = endpoint.local_addr().map_err(Error::Io)?;
let served = Arc::new(ServedEndpoint::new(endpoint, lease));
self.inner.runtime.track_endpoint(Arc::clone(&served));
let peers = Arc::new(PeerConns::default());
let open = Arc::new(OpenConns::default());
exec.spawn(accept_connections(
Arc::clone(&served),
Arc::clone(&self.inner),
Arc::clone(&peers),
Arc::clone(&open),
));
tracing::info!(%local_addr, "quic binding listening");
Ok(Binding {
served,
local_addr,
peers,
socket,
open,
close_timeout: self.inner.runtime.config.shutdown_timeout,
exec,
relay: None,
})
}
pub fn bind_inproc(&self, bus: &str) -> Result<LocalBinding, Error> {
let incoming = inproc::bind(bus)?;
let exec = self.inner.runtime.exec.clone();
exec.spawn(accept_local(
incoming,
Arc::clone(&self.inner.namespace),
Arc::clone(&self.inner.subs),
self.inner.runtime.config.limits,
exec.clone(),
self.inner.runtime.config.guarantees,
self.inner.runtime.shared(),
));
tracing::info!(bus, "inproc binding listening");
Ok(LocalBinding {
bus: bus.to_owned(),
})
}
#[cfg(unix)]
pub fn bind_unix(&self, path: impl AsRef<std::path::Path>) -> Result<UnixBinding, Error> {
let path = path.as_ref();
let exec = self.inner.runtime.exec.clone();
#[cfg(feature = "test-util")]
if let Some(net) = self.inner.runtime.config.network.sim_net() {
let crate::sim::LocalListener { incoming, lease } = net.bind_local(path)?;
let (serve, requests) = self.local_accept(|link| Link::Unix(Box::new(link)));
exec.spawn(accept_sim_unix(incoming, requests, serve));
tracing::info!(path = %path.display(), "simulated unix binding listening");
return Ok(UnixBinding {
inner: UnixBound::Sim(lease),
});
}
let (binding, listener) = {
let _guard = exec.enter();
weida_runtime::BoundUnixSocket::bind(path)?
};
let (serve, requests) = self.local_accept(|link| Link::Unix(Box::new(link)));
exec.spawn(accept_unix(listener, requests, serve));
tracing::info!(path = %path.display(), "unix binding listening");
Ok(UnixBinding {
inner: UnixBound::Os(binding),
})
}
#[cfg(windows)]
pub fn bind_pipe(&self, name: &str) -> Result<PipeBinding, Error> {
let addr = weida_core::PipeAddr::parse(&format!("{}://{name}/", weida_core::SCHEME_PIPE))?;
let exec = self.inner.runtime.exec.clone();
let (binding, first) = {
let _guard = exec.enter();
weida_runtime::BoundPipe::bind(addr.os_path())?
};
let name = addr.name.clone();
let (stop_tx, stop_rx) = tokio::sync::oneshot::channel();
let (serve, requests) = self.local_accept(|link| Link::Pipe(Box::new(link)));
exec.spawn(accept_pipe(binding, first, stop_rx, requests, serve));
tracing::info!(pipe = %name, "pipe binding listening");
Ok(PipeBinding {
name,
_stop: stop_tx,
})
}
#[cfg(any(unix, windows))]
fn local_accept<S: crate::grouped::Stream>(
&self,
link: fn(crate::grouped::Grouped<S>) -> Link,
) -> (LocalAccept<S>, crate::grouped::BarrierRequests) {
let max_connections = self.inner.runtime.config.max_connections;
let (barrier, requests) = crate::grouped::AcceptBarrier::new();
let serve = LocalAccept {
groups: Arc::new(crate::grouped::Groups::new(Arc::clone(&barrier))),
barrier,
namespace: Arc::clone(&self.inner.namespace),
subs: Arc::clone(&self.inner.subs),
limits: self.inner.runtime.config.limits,
exec: self.inner.runtime.exec.clone(),
guarantees: self.inner.runtime.config.guarantees,
shared: self.inner.runtime.shared(),
link,
admitted: Arc::new(Semaphore::new(max_connections.min(Semaphore::MAX_PERMITS))),
departing: Arc::new(Semaphore::new(
max_connections.clamp(1, Semaphore::MAX_PERMITS),
)),
refusals: Arc::new(LogThrottle::new(REFUSAL_LOG_INTERVAL)),
};
(serve, requests)
}
pub fn replier(&self, path: &str) -> Result<Replier, Error> {
validate_endpoint_path(path)?;
let (tx, rx) = mpsc::channel(self.inner.runtime.config.endpoint_queue);
self.inner.namespace.register(path, Route::Request(tx))?;
Ok(Endpoint::from_state(RepState::new(path, rx)))
}
pub fn puller(&self, path: &str) -> Result<Puller, Error> {
validate_endpoint_path(path)?;
let (tx, rx) = mpsc::channel(self.inner.runtime.config.endpoint_queue);
self.inner.namespace.register(path, Route::Transfer(tx))?;
Ok(Endpoint::from_state(PullState::new(path, rx)))
}
pub fn publisher(&self, path: &str) -> Result<Publisher, Error> {
validate_endpoint_path(path)?;
self.inner.namespace.register(path, Route::Pub)?;
Ok(Endpoint::from_state(PubState::new(
path,
Arc::clone(&self.inner.subs),
self.inner.runtime.config.limits.subscriber_buffer_bytes,
)))
}
pub fn radio(&self, path: &str) -> Result<crate::Radio, Error> {
validate_endpoint_path(path)?;
let hub = Arc::new(crate::radio::RadioHub::new(
path,
self.inner.runtime.config.limits,
));
self.inner
.namespace
.register(path, Route::Radio(Arc::clone(&hub)))?;
Ok(Endpoint::from_state(crate::radio::RadioState::new(
hub,
Arc::clone(&self.inner.namespace),
)))
}
pub fn acceptor(&self, path: &str) -> Result<Acceptor, Error> {
validate_endpoint_path(path)?;
let (tx, rx) = mpsc::channel(self.inner.runtime.config.endpoint_queue);
self.inner.namespace.register(path, Route::Raw(tx))?;
Ok(Acceptor::new(path, rx))
}
pub fn relay(&self) -> Result<Relay, Error> {
Relay::serve_on(&self.inner)
}
pub fn pair(&self, path: &str) -> Result<Paired, Error> {
validate_endpoint_path(path)?;
let (tx, rx) = mpsc::channel(self.inner.runtime.config.endpoint_queue);
let owner = Arc::new(PairOwner::new());
self.inner.namespace.register(
path,
Route::Pair {
queue: tx,
owner: Arc::clone(&owner),
},
)?;
Ok(Endpoint::from_state(PairState::bound(path, owner, rx)))
}
pub fn respondent(&self, path: &str) -> Result<Respondent, Error> {
validate_endpoint_path(path)?;
let (tx, rx) = mpsc::channel(self.inner.runtime.config.endpoint_queue);
self.inner.namespace.register(path, Route::Request(tx))?;
Ok(Endpoint::from_state(RespondState::new(path, rx)))
}
#[cfg(feature = "swarm")]
pub fn seeder(&self, path: &str) -> Result<crate::Seeder, Error> {
validate_endpoint_path(path)?;
let (tx, rx) = mpsc::channel(self.inner.runtime.config.endpoint_queue);
self.inner.namespace.register(path, Route::Request(tx))?;
Ok(Endpoint::from_state(crate::swarm::SeedState::new(
path,
rx,
&self.inner.runtime,
)))
}
pub fn bus(&self, path: &str, tls: impl Into<ClientTls>) -> Result<BusMember, Error> {
validate_endpoint_path(path)?;
let (tx, rx) = mpsc::channel(self.inner.runtime.config.endpoint_queue);
self.inner.namespace.register(path, Route::Transfer(tx))?;
Ok(Endpoint::from_state(BusState::new(
path,
Arc::clone(&self.inner.runtime),
Arc::new(tls.into()),
rx,
self.inner.runtime.config.endpoint_queue,
self.inner.runtime.config.limits.subscriber_buffer_bytes,
)))
}
}
impl std::fmt::Debug for Listener {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Listener").finish_non_exhaustive()
}
}
pub(crate) struct ServedEndpoint {
endpoint: quinn::Endpoint,
lease: AddrLease,
closed: AtomicBool,
}
impl ServedEndpoint {
fn new(endpoint: quinn::Endpoint, lease: AddrLease) -> ServedEndpoint {
ServedEndpoint {
endpoint,
lease,
closed: AtomicBool::new(false),
}
}
pub(crate) fn close(&self, code: VarInt, reason: &[u8]) {
self.closed.store(true, Ordering::Release);
self.endpoint.close(code, reason);
}
fn is_closed(&self) -> bool {
self.closed.load(Ordering::Acquire)
}
pub(crate) async fn wait_idle(&self) {
self.endpoint.wait_idle().await;
}
pub(crate) fn release(&self) {
self.lease.release();
}
fn take_handed(&self) -> Option<std::net::UdpSocket> {
self.lease.take_handed()
}
}
pub struct Binding {
served: Arc<ServedEndpoint>,
local_addr: SocketAddr,
peers: Arc<PeerConns>,
socket: Arc<HandoverSocket>,
open: Arc<OpenConns>,
exec: Exec,
close_timeout: Duration,
relay: Option<Arc<RelaySocket>>,
}
impl std::fmt::Debug for Binding {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Binding")
.field("local_addr", &self.local_addr)
.finish_non_exhaustive()
}
}
impl Binding {
pub fn local_addr(&self) -> SocketAddr {
self.local_addr
}
pub fn relay_events(&self) -> Option<crate::PeerEvents> {
self.relay.as_ref().and_then(|socket| socket.events())
}
pub async fn close(&self) {
self.served
.close(VarInt::from_u32(codes::SHUTDOWN as u32), b"binding closed");
if self
.exec
.within(self.close_timeout, self.served.wait_idle())
.await
.is_none()
{
tracing::debug!(
timeout_ms = self.close_timeout.as_millis(),
"timeout reached before the binding's socket went idle"
);
}
self.served.release();
}
pub async fn hand_over(self) -> Handoff {
let handed = self.served.take_handed().expect(
"Binding::hand_over needs an open OS socket; a closed binding, or one on a simulated network or a relay, has none",
);
self.socket.hold();
let pending: Vec<quinn::Connection> = self
.open
.snapshot()
.into_iter()
.filter(|conn| conn.close_reason().is_none())
.collect();
self.served.close(
VarInt::from_u32(codes::RESTARTING as u32),
b"server restarting",
);
let all_held = self
.exec
.within(self.close_timeout, async {
for conn in &pending {
conn.closed().await;
}
})
.await
.is_some();
if !all_held {
tracing::debug!(
timeout_ms = self.close_timeout.as_millis(),
"timeout reached before every close was held"
);
}
let held = self.socket.release();
tracing::info!(
local_addr = %self.local_addr,
connections = pending.len(),
datagrams = held.len(),
"binding handed over"
);
Handoff {
socket: handed,
local_addr: self.local_addr,
held,
}
}
pub async fn take_over(&self, held: &[u8]) -> Result<usize, Error> {
let (from, datagrams) = handoff::decode(held)?;
if from != self.local_addr {
return Err(Error::Io(io::Error::new(
io::ErrorKind::InvalidInput,
format!(
"handoff for {from} offered to a binding on {}",
self.local_addr
),
)));
}
let mut sent = 0;
for datagram in &datagrams {
match self.socket.send_raw(datagram).await {
Ok(()) => sent += 1,
Err(e) => tracing::debug!(
destination = %datagram.destination,
error = %e,
"handed-over datagram not sent"
),
}
}
tracing::info!(local_addr = %self.local_addr, sent, "binding took over");
Ok(sent)
}
pub fn disconnect(&self, peer: Fingerprint) -> usize {
self.peers.disconnect(&peer)
}
}
#[derive(Debug)]
pub struct LocalBinding {
bus: String,
}
impl LocalBinding {
pub fn bus(&self) -> &str {
&self.bus
}
}
impl Drop for LocalBinding {
fn drop(&mut self) {
inproc::unbind(&self.bus);
}
}
#[cfg(unix)]
#[derive(Debug)]
pub struct UnixBinding {
inner: UnixBound,
}
#[cfg(unix)]
#[derive(Debug)]
enum UnixBound {
Os(weida_runtime::BoundUnixSocket),
#[cfg(feature = "test-util")]
Sim(crate::sim::LocalLease),
}
#[cfg(unix)]
impl UnixBinding {
pub fn path(&self) -> &std::path::Path {
match &self.inner {
UnixBound::Os(socket) => socket.path(),
#[cfg(feature = "test-util")]
UnixBound::Sim(lease) => lease.path(),
}
}
}
#[cfg(windows)]
#[derive(Debug)]
pub struct PipeBinding {
name: String,
_stop: tokio::sync::oneshot::Sender<()>,
}
#[cfg(windows)]
impl PipeBinding {
pub fn name(&self) -> &str {
&self.name
}
}
#[cfg(any(unix, windows))]
const ACCEPT_RETRY: Duration = Duration::from_millis(100);
#[cfg(any(unix, windows))]
struct LocalAccept<S: crate::grouped::Stream> {
groups: Arc<crate::grouped::Groups<S>>,
barrier: Arc<crate::grouped::AcceptBarrier>,
namespace: Arc<Namespace>,
subs: Arc<SubRegistry>,
limits: Limits,
exec: Exec,
guarantees: GuaranteeSet,
shared: Arc<Shared>,
link: fn(crate::grouped::Grouped<S>) -> Link,
admitted: Arc<Semaphore>,
departing: Arc<Semaphore>,
refusals: Arc<LogThrottle>,
}
#[cfg(any(unix, windows))]
impl<S: crate::grouped::Stream> LocalAccept<S> {
fn clone_for(&self) -> LocalAccept<S> {
LocalAccept {
groups: Arc::clone(&self.groups),
barrier: Arc::clone(&self.barrier),
namespace: Arc::clone(&self.namespace),
subs: Arc::clone(&self.subs),
limits: self.limits,
exec: self.exec.clone(),
guarantees: self.guarantees,
shared: Arc::clone(&self.shared),
link: self.link,
admitted: Arc::clone(&self.admitted),
departing: Arc::clone(&self.departing),
refusals: Arc::clone(&self.refusals),
}
}
fn spawn(&self, stream: S, place: OwnedSemaphorePermit) {
let ticket = self.barrier.ticket();
self.exec
.spawn(self.clone_for().serve(stream, place, ticket));
}
async fn serve(self, stream: S, place: OwnedSemaphorePermit, ticket: crate::grouped::Ticket) {
use crate::grouped::{
Accepted, accept_control, admit_reverse, admit_transfer, read_accepted,
};
let deadline = Duration::from_millis(self.limits.hello_timeout_ms);
let accepted = match self.exec.within(deadline, read_accepted(stream)).await {
Some(Ok(accepted)) => accepted,
Some(Err(e)) => {
tracing::debug!(error = %e, "local connection preamble rejected");
return;
}
None => {
tracing::debug!("local connection sent no preamble in time");
return;
}
};
match accepted {
Accepted::Control(stream, principal) => {
drop(ticket);
let link = match accept_control(
stream,
principal,
Arc::clone(&self.groups),
self.limits.max_local_streams,
self.limits.max_parked_reverse,
self.exec.clone(),
Some(place),
)
.await
{
Ok(link) => link,
Err(e) => {
tracing::debug!(error = %e, "local control connection failed");
return;
}
};
let ctx = ConnCtx::spawn(
(self.link)(link),
self.limits,
self.namespace,
Some(Arc::clone(&self.subs)),
self.exec,
self.guarantees,
self.shared,
);
let conn_id = ctx.conn.stable_id();
let reason = ctx.conn.closed().await;
self.subs.remove_connection(conn_id);
let departure = crate::conn::take_departure(&ctx);
tracing::debug!(%reason, "local connection closed");
depart(departure, &self.departing, move || drop(ctx)).await;
}
Accepted::Transfer(token, stream, principal) => {
if !admit_transfer(&self.groups, &token, &principal, stream, place)
&& let Some(held_back) = self.refusals.pass()
{
tracing::warn!(
held_back,
"local transfer connection refused: unknown or mismatched group"
);
}
}
Accepted::Reverse(token, stream, principal) => {
if !admit_reverse(&self.groups, &token, &principal, stream, place) {
tracing::debug!(
"local reverse connection not parked: unknown group or pool full"
);
}
}
}
}
}
#[cfg(unix)]
async fn accept_unix(
listener: tokio::net::UnixListener,
mut requests: crate::grouped::BarrierRequests,
serve: LocalAccept<crate::unix::UnixLocal>,
) {
loop {
tokio::select! {
Some(request) = requests.recv() => drain_unix_queue(&listener, &serve, request, None),
place = Arc::clone(&serve.admitted).acquire_owned() => {
let Ok(place) = place else { return };
tokio::select! {
accepted = listener.accept() => match accepted {
Ok((stream, _)) => take_unix(&serve, stream, place),
Err(e) => {
if let Some(held_back) = serve.refusals.pass() {
tracing::warn!(error = %e, held_back, "accepting a unix connection failed; retrying");
}
serve.exec.sleep(ACCEPT_RETRY).await;
}
},
Some(request) = requests.recv() => {
drain_unix_queue(&listener, &serve, request, Some(place));
}
}
}
}
}
}
#[cfg(unix)]
fn drain_unix_queue(
listener: &tokio::net::UnixListener,
serve: &LocalAccept<crate::unix::UnixLocal>,
mut request: crate::grouped::BarrierRequest,
mut held: Option<OwnedSemaphorePermit>,
) {
use std::os::fd::AsFd;
let queue = match listener.as_fd().try_clone_to_owned() {
Ok(fd) => Some(std::os::unix::net::UnixListener::from(fd)),
Err(e) => {
tracing::debug!(error = %e, "the unix accept queue could not be read");
None
}
};
if let Some(queue) = queue {
while let Some(place) = held.take().or_else(|| request.next_place(&serve.admitted)) {
let stream = queue.accept().and_then(|(stream, _)| {
stream.set_nonblocking(true)?;
let _guard = serve.exec.enter();
tokio::net::UnixStream::from_std(stream)
});
match stream {
Ok(stream) => take_unix(serve, stream, place),
Err(e) if e.kind() == io::ErrorKind::WouldBlock => break,
Err(e) => {
tracing::debug!(error = %e, "accepting a queued unix connection failed");
break;
}
}
}
}
let _ = request.answer.send(serve.barrier.last());
}
#[cfg(unix)]
fn take_unix(
serve: &LocalAccept<crate::unix::UnixLocal>,
stream: tokio::net::UnixStream,
place: OwnedSemaphorePermit,
) {
if serve.shared.drain.is_draining() {
return;
}
serve.spawn(
crate::unix::UnixLocal::accepted(stream, serve.exec.clone()),
place,
);
}
#[cfg(all(unix, feature = "test-util"))]
async fn accept_sim_unix(
mut incoming: tokio::sync::mpsc::Receiver<tokio::io::DuplexStream>,
mut requests: crate::grouped::BarrierRequests,
serve: LocalAccept<crate::unix::UnixLocal>,
) {
let take = |stream, place| {
if !serve.shared.drain.is_draining() {
serve.spawn(
crate::unix::UnixLocal::accepted_sim(stream, serve.exec.clone()),
place,
);
}
};
let drain = |incoming: &mut tokio::sync::mpsc::Receiver<tokio::io::DuplexStream>,
mut request: crate::grouped::BarrierRequest,
mut held: Option<OwnedSemaphorePermit>| {
while let Some(place) = held.take().or_else(|| request.next_place(&serve.admitted)) {
match incoming.try_recv() {
Ok(stream) => take(stream, place),
Err(_) => break,
}
}
let _ = request.answer.send(serve.barrier.last());
};
loop {
tokio::select! {
Some(request) = requests.recv() => drain(&mut incoming, request, None),
place = Arc::clone(&serve.admitted).acquire_owned() => {
let Ok(place) = place else { return };
tokio::select! {
stream = incoming.recv() => {
let Some(stream) = stream else { return };
take(stream, place);
}
Some(request) = requests.recv() => drain(&mut incoming, request, Some(place)),
}
}
}
}
}
#[cfg(windows)]
const PIPE_LISTENING: usize = 16;
#[cfg(windows)]
struct PipeListening {
server: Arc<tokio::net::windows::named_pipe::NamedPipeServer>,
connect: std::pin::Pin<Box<dyn Future<Output = (OwnedSemaphorePermit, io::Result<()>)> + Send>>,
}
#[cfg(windows)]
type PipeAccepted = (
tokio::net::windows::named_pipe::NamedPipeServer,
OwnedSemaphorePermit,
io::Result<()>,
);
#[cfg(windows)]
fn pipe_listen(
server: tokio::net::windows::named_pipe::NamedPipeServer,
place: OwnedSemaphorePermit,
) -> PipeListening {
let server = Arc::new(server);
let connecting = Arc::clone(&server);
PipeListening {
server,
connect: Box::pin(async move {
let connected = connecting.connect().await;
(place, connected)
}),
}
}
#[cfg(windows)]
impl PipeListening {
fn accepted(self, out: (OwnedSemaphorePermit, io::Result<()>)) -> Option<PipeAccepted> {
let PipeListening { server, connect } = self;
drop(connect);
let (place, connected) = out;
Arc::try_unwrap(server)
.ok()
.map(|server| (server, place, connected))
}
}
#[cfg(windows)]
async fn pipe_connected(listening: &mut Vec<PipeListening>) -> Option<PipeAccepted> {
std::future::poll_fn(|cx| {
for i in 0..listening.len() {
if let std::task::Poll::Ready(out) = listening[i].connect.as_mut().poll(cx) {
return std::task::Poll::Ready(listening.swap_remove(i).accepted(out));
}
}
std::task::Poll::Pending
})
.await
}
#[cfg(windows)]
async fn accept_pipe(
binding: weida_runtime::BoundPipe,
first: tokio::net::windows::named_pipe::NamedPipeServer,
mut stop: tokio::sync::oneshot::Receiver<()>,
mut requests: crate::grouped::BarrierRequests,
serve: LocalAccept<crate::pipe::PipeStream>,
) {
let mut spare = Some(first);
let mut listening: Vec<PipeListening> = Vec::with_capacity(PIPE_LISTENING);
loop {
while spare.is_none() && listening.is_empty() {
match binding.next_instance() {
Ok(next) => spare = Some(next),
Err(e) => {
if let Some(held_back) = serve.refusals.pass() {
tracing::warn!(error = %e, held_back, "pipe instance not created; retrying");
}
tokio::select! {
() = serve.exec.sleep(ACCEPT_RETRY) => {}
_ = &mut stop => return,
}
}
}
}
tokio::select! {
Some(request) = requests.recv() => {
drain_pipe_instances(&binding, &mut spare, &mut listening, &serve, request).await;
}
place = Arc::clone(&serve.admitted).acquire_owned(),
if listening.len() < PIPE_LISTENING =>
{
let Ok(place) = place else { return };
let server = match spare.take() {
Some(spare) => spare,
None => match binding.next_instance() {
Ok(next) => next,
Err(e) => {
if let Some(held_back) = serve.refusals.pass() {
tracing::warn!(error = %e, held_back, "pipe instance not created; retrying");
}
tokio::select! {
() = serve.exec.sleep(ACCEPT_RETRY) => {}
_ = &mut stop => return,
}
continue;
}
},
};
listening.push(pipe_listen(server, place));
}
accepted = pipe_connected(&mut listening), if !listening.is_empty() => {
let Some((accepted, place, connected)) = accepted else { continue };
if let Err(e) = connected {
if let Some(held_back) = serve.refusals.pass() {
tracing::warn!(error = %e, held_back, "pipe accept failed; retrying");
}
drop((accepted, place));
tokio::select! {
() = serve.exec.sleep(ACCEPT_RETRY) => {}
_ = &mut stop => return,
}
continue;
}
if listening.is_empty() && spare.is_none() {
spare = binding.next_instance().ok();
}
if serve.shared.drain.is_draining() {
continue;
}
serve.spawn(
crate::pipe::PipeStream::accepted(accepted, serve.exec.clone()),
place,
);
}
_ = &mut stop => {
tracing::debug!("pipe binding dropped; accept loop ending");
return;
}
}
}
}
#[cfg(windows)]
async fn drain_pipe_instances(
binding: &weida_runtime::BoundPipe,
spare: &mut Option<tokio::net::windows::named_pipe::NamedPipeServer>,
listening: &mut Vec<PipeListening>,
serve: &LocalAccept<crate::pipe::PipeStream>,
mut request: crate::grouped::BarrierRequest,
) {
let has_client = |server: &tokio::net::windows::named_pipe::NamedPipeServer| {
weida_runtime::client_principal(server).is_ok()
};
if spare.as_ref().is_some_and(has_client)
&& let Some(place) = request.next_place(&serve.admitted)
&& let Some(server) = spare.take()
{
listening.push(pipe_listen(server, place));
}
let mut ready = Vec::new();
let mut i = 0;
while i < listening.len() {
if !has_client(listening[i].server.as_ref()) {
i += 1;
continue;
}
let mut taken = listening.swap_remove(i);
let out = taken.connect.as_mut().await;
ready.extend(taken.accepted(out));
}
if listening.is_empty() && spare.is_none() {
*spare = binding.next_instance().ok();
}
for (accepted, place, connected) in ready {
if let Err(e) = connected {
tracing::debug!(error = %e, "a connected pipe instance failed");
continue;
}
if serve.shared.drain.is_draining() {
continue;
}
serve.spawn(
crate::pipe::PipeStream::accepted(accepted, serve.exec.clone()),
place,
);
}
let _ = request.answer.send(serve.barrier.last());
}
async fn accept_local(
mut incoming: mpsc::UnboundedReceiver<inproc::LocalConn>,
namespace: Arc<Namespace>,
subs: Arc<SubRegistry>,
limits: Limits,
exec: Exec,
guarantees: GuaranteeSet,
shared: Arc<Shared>,
) {
while let Some(conn) = incoming.recv().await {
if shared.drain.is_draining() {
conn.close(codes::SHUTDOWN, "runtime draining");
continue;
}
let namespace = Arc::clone(&namespace);
let subs = Arc::clone(&subs);
let exec_for_conn = exec.clone();
let shared = Arc::clone(&shared);
exec.spawn(async move {
let ctx = ConnCtx::spawn(
Link::Local(conn),
limits,
namespace,
Some(Arc::clone(&subs)),
exec_for_conn,
guarantees,
shared,
);
let conn_id = ctx.conn.stable_id();
let reason = ctx.conn.closed().await;
subs.remove_connection(conn_id);
let departure = crate::conn::take_departure(&ctx);
tracing::debug!(%reason, "local connection closed");
drop(ctx);
departure.announce().await;
});
}
}
#[derive(Default)]
struct PeerConns(std::sync::Mutex<HashMap<Fingerprint, Vec<quinn::Connection>>>);
impl PeerConns {
fn admit(&self, peer: Option<Fingerprint>, conn: &quinn::Connection, max: usize) -> bool {
let Some(peer) = peer else {
return true;
};
let mut conns = self.0.lock().expect("peer table poisoned");
let held = conns.entry(peer).or_default();
if held.len() >= max {
return false;
}
held.push(conn.clone());
true
}
fn release(&self, peer: Option<Fingerprint>, conn_id: usize) {
let Some(peer) = peer else {
return;
};
let mut conns = self.0.lock().expect("peer table poisoned");
if let Some(held) = conns.get_mut(&peer) {
held.retain(|c| c.stable_id() != conn_id);
if held.is_empty() {
conns.remove(&peer);
}
}
}
fn disconnect(&self, peer: &Fingerprint) -> usize {
let held = self
.0
.lock()
.expect("peer table poisoned")
.get(peer)
.cloned()
.unwrap_or_default();
for conn in &held {
conn.close(
VarInt::from_u32(codes::REJECTED as u32),
b"disconnected by the application",
);
}
held.len()
}
}
impl std::fmt::Debug for PeerConns {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let peers = self.0.lock().map_or(0, |conns| conns.len());
f.debug_struct("PeerConns").field("peers", &peers).finish()
}
}
#[derive(Default)]
struct OpenConns(std::sync::Mutex<HashMap<usize, quinn::Connection>>);
impl OpenConns {
fn insert(&self, conn: &quinn::Connection) {
self.0
.lock()
.expect("open connections poisoned")
.insert(conn.stable_id(), conn.clone());
}
fn remove(&self, conn_id: usize) {
self.0
.lock()
.expect("open connections poisoned")
.remove(&conn_id);
}
fn snapshot(&self) -> Vec<quinn::Connection> {
self.0
.lock()
.expect("open connections poisoned")
.values()
.cloned()
.collect()
}
}
const REFUSAL_LOG_INTERVAL: Duration = Duration::from_secs(1);
struct LogThrottle {
every: Duration,
state: Mutex<ThrottleState>,
}
struct ThrottleState {
next: Option<Instant>,
held_back: u64,
}
impl LogThrottle {
fn new(every: Duration) -> LogThrottle {
LogThrottle {
every,
state: Mutex::new(ThrottleState {
next: None,
held_back: 0,
}),
}
}
fn pass(&self) -> Option<u64> {
self.pass_at(Instant::now())
}
fn pass_at(&self, now: Instant) -> Option<u64> {
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
match state.next {
Some(next) if now < next => {
state.held_back += 1;
None
}
_ => {
state.next = Some(now + self.every);
Some(std::mem::take(&mut state.held_back))
}
}
}
}
struct Counted(Arc<AtomicUsize>);
impl Counted {
fn take(counter: &Arc<AtomicUsize>) -> Counted {
counter.fetch_add(1, Ordering::Relaxed);
Counted(Arc::clone(counter))
}
}
impl Drop for Counted {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::Relaxed);
}
}
async fn depart(
departure: crate::conn::Departure,
departing: &Arc<Semaphore>,
release: impl FnOnce() + Send,
) {
if departure.is_empty() {
release();
return;
}
match Arc::clone(departing).try_acquire_owned() {
Ok(_wait) => {
release();
departure.announce().await;
}
Err(_) => {
departure.announce().await;
release();
}
}
}
async fn accept_connections(
served: Arc<ServedEndpoint>,
listener: Arc<ListenerInner>,
peers: Arc<PeerConns>,
open: Arc<OpenConns>,
) {
let config = &listener.runtime.config;
let limits = config.limits;
let max_connections = config.max_connections;
let max_connections_per_peer = config.max_connections_per_peer;
let max_handshakes = config.max_handshakes;
let retry_above = config.retry_above_handshakes;
let guarantees = config.guarantees;
let exec = listener.runtime.exec.clone();
let shared = listener.runtime.shared();
let namespace = Arc::clone(&listener.namespace);
let subs = Arc::clone(&listener.subs);
let live = Arc::new(AtomicUsize::new(0));
let handshaking = Arc::new(AtomicUsize::new(0));
let refusals = Arc::new(LogThrottle::new(REFUSAL_LOG_INTERVAL));
let departing = Arc::new(Semaphore::new(
max_connections.clamp(1, Semaphore::MAX_PERMITS),
));
while let Some(incoming) = served.endpoint.accept().await {
if shared.drain.is_draining() || served.is_closed() {
incoming.refuse();
continue;
}
if live.load(Ordering::Relaxed) >= max_connections {
if let Some(held_back) = refusals.pass() {
tracing::warn!(
max = max_connections,
held_back,
"connection limit reached; refusing"
);
}
incoming.refuse();
continue;
}
let in_progress = handshaking.load(Ordering::Relaxed);
if in_progress >= max_handshakes {
if let Some(held_back) = refusals.pass() {
tracing::warn!(
max = max_handshakes,
held_back,
"handshake limit reached; refusing"
);
}
incoming.refuse();
continue;
}
if in_progress >= retry_above && !incoming.remote_address_validated() {
if let Err(unretried) = incoming.retry() {
unretried.into_incoming().refuse();
}
continue;
}
let namespace = Arc::clone(&namespace);
let subs = Arc::clone(&subs);
let live = Counted::take(&live);
let handshake = Counted::take(&handshaking);
let exec_for_conn = exec.clone();
let shared = Arc::clone(&shared);
let peers = Arc::clone(&peers);
let open = Arc::clone(&open);
let refusals = Arc::clone(&refusals);
let departing = Arc::clone(&departing);
let served = Arc::clone(&served);
exec.spawn(async move {
let connecting = match incoming.accept() {
Ok(connecting) => connecting,
Err(e) => {
tracing::debug!(error = %e, "handshake failed");
return; }
};
if served.is_closed() {
tracing::debug!("binding closed during the handshake; connection dropped");
return;
}
let connected = connecting.await;
drop(handshake);
match connected {
Ok(conn) => {
open.insert(&conn);
let remote = conn.remote_address();
let quic_id = conn.stable_id();
let peer = crate::tls::peer_fingerprint(&conn);
if !peers.admit(peer, &conn, max_connections_per_peer) {
if let Some(held_back) = refusals.pass() {
tracing::warn!(
%remote,
max = max_connections_per_peer,
held_back,
"per-peer connection limit reached; refusing"
);
}
conn.close(
VarInt::from_u32(codes::LIMIT_EXCEEDED as u32),
b"per-peer connection limit reached",
);
open.remove(quic_id);
} else {
tracing::debug!(%remote, "connection accepted");
let ctx = ConnCtx::spawn(
Link::Quic(QuicLink::new(conn.clone())),
limits,
namespace,
Some(Arc::clone(&subs)),
exec_for_conn,
guarantees,
shared,
);
let serial = ctx.conn.stable_id();
let reason = conn.closed().await;
subs.remove_connection(serial);
let departure = crate::conn::take_departure(&ctx);
tracing::debug!(%remote, %reason, "connection closed");
depart(departure, &departing, move || {
peers.release(peer, quic_id);
open.remove(quic_id);
drop((ctx, conn, live));
})
.await;
}
}
Err(e) => tracing::debug!(error = %e, "handshake failed"),
}
});
}
tracing::debug!("binding stopped accepting");
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn namespace_rejects_duplicate_paths() {
let ns = Namespace::new();
let (tx, _rx) = mpsc::channel(1);
ns.register("/a", Route::Request(tx.clone())).unwrap();
assert!(matches!(
ns.register("/a", Route::Request(tx.clone())),
Err(Error::AlreadyRegistered)
));
assert!(matches!(
ns.register("/a", Route::Pub),
Err(Error::AlreadyRegistered)
));
ns.register("/b", Route::Request(tx)).unwrap();
}
#[tokio::test]
async fn namespace_lookup_is_exact() {
let ns = Namespace::new();
let (tx, _rx) = mpsc::channel(1);
ns.register("/jobs/a", Route::Request(tx)).unwrap();
assert!(ns.lookup("/jobs/a").is_some());
assert!(ns.lookup("/jobs").is_none());
assert!(ns.lookup("/jobs/a/").is_none());
assert!(ns.lookup("/jobs/*").is_none());
assert!(ns.lookup("/JOBS/A").is_none());
}
#[tokio::test]
async fn unregistering_releases_the_path() {
let ns = Namespace::new();
let (tx, _rx) = mpsc::channel(1);
ns.register("/s", Route::Transfer(tx)).unwrap();
ns.unregister("/s");
assert!(ns.lookup("/s").is_none());
ns.unregister("/s");
ns.register("/s", Route::Pub).unwrap();
}
}
#[cfg(test)]
mod accept_tests {
use super::*;
#[test]
fn a_log_throttle_passes_one_record_per_interval_and_counts_the_rest() {
let throttle = LogThrottle::new(Duration::from_secs(1));
let start = Instant::now();
assert_eq!(throttle.pass_at(start), Some(0));
for _ in 0..5 {
assert_eq!(throttle.pass_at(start + Duration::from_millis(500)), None);
}
assert_eq!(
throttle.pass_at(start + Duration::from_millis(1500)),
Some(5)
);
assert_eq!(throttle.pass_at(start + Duration::from_millis(1600)), None);
}
#[test]
fn a_consumer_is_recorded_per_filter_and_reported_with_its_last_path() {
let ns = Namespace::new();
assert!(ns.note_consumer(7, "/q", "a"));
assert!(!ns.note_consumer(7, "/q", "a"));
assert!(ns.note_consumer(7, "/q", "b"));
assert!(!ns.forget_consumer(7, "/q", "never"));
assert!(ns.forget_consumer(7, "/q", "a"));
assert!(!ns.forget_consumer(7, "/q", "a"));
let (tx, _rx) = mpsc::channel(1);
ns.register("/q", Route::Raw(tx)).expect("register");
assert_eq!(ns.take_consumer_routes(7).len(), 1);
assert!(ns.take_consumer_routes(7).is_empty());
}
}