use std::collections::HashMap;
use std::pin::Pin;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
use std::time::{Duration, Instant};
use bytes::Bytes;
use tokio::sync::{Semaphore, mpsc};
use tokio::task::JoinHandle;
use weida_core::{Error, Limits, PeerIdentity};
use weida_protocol::header::limits::MAX_TOPIC_BYTES;
use weida_protocol::{FrameKind, codes, encode_varint, filter, split_flow_datagram};
use crate::config::ClientTls;
use crate::conn::{ConnHandle, Ctl};
use crate::endpoint::{Dish, Radio, send_subscription};
use crate::flow::{Flow, FlowMeta, IncomingFlow, open_flow_on};
use crate::identity::PeerChain;
use crate::listener::{Namespace, Route};
use crate::pubsub::{Causes, DishDrops, DropCause, DropTable, FilterIndex, TopicDrops};
use crate::reconnect::PeerEvents;
use crate::runtime::RuntimeInner;
use crate::segment::{CopyTarget, Segment, SegmentTerms, SegmentTopics, open_segment};
use crate::stream::{Attach, Peer};
use crate::transfer::IncomingTransfer;
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
#[derive(Debug)]
#[non_exhaustive]
pub struct Join<'a> {
pub peer: Option<&'a PeerIdentity>,
pub peer_chain: Option<&'a PeerChain>,
pub filter: &'a str,
}
impl<'a> Join<'a> {
fn of(conn: &'a ConnHandle, filter: &'a str) -> Join<'a> {
Join {
peer: conn.peer.as_ref(),
peer_chain: conn.peer_chain.as_ref(),
filter,
}
}
}
type Admission = Arc<dyn Fn(&Join<'_>) -> bool + Send + Sync>;
#[non_exhaustive]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct JoinTerms {
pub max_age: Option<Duration>,
pub max_layer: Option<u8>,
}
impl JoinTerms {
#[must_use]
pub fn with_max_age(mut self, max_age: Duration) -> Self {
self.max_age = Some(max_age);
self
}
#[must_use]
pub fn with_max_layer(mut self, max_layer: u8) -> Self {
self.max_layer = Some(max_layer);
self
}
fn merge(&self, other: &JoinTerms) -> JoinTerms {
JoinTerms {
max_age: match (self.max_age, other.max_age) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
},
max_layer: self.max_layer.zip(other.max_layer).map(|(a, b)| a.max(b)),
}
}
}
struct DishPort {
conn: ConnHandle,
budget: Arc<Semaphore>,
flows: Mutex<HashMap<Arc<str>, FlowSlot>>,
drops: Arc<Causes>,
}
struct DishEntry {
port: Arc<DishPort>,
filters: HashMap<String, JoinTerms>,
watch: JoinHandle<()>,
}
impl Drop for DishEntry {
fn drop(&mut self) {
self.watch.abort();
}
}
struct DishTable {
dishes: HashMap<usize, DishEntry>,
index: FilterIndex<JoinTerms>,
}
impl DishTable {
fn live(&self) -> impl Iterator<Item = (usize, &DishEntry)> {
self.dishes
.iter()
.filter(|(_, dish)| dish.port.conn.conn.close_reason().is_none())
.map(|(conn_id, dish)| (*conn_id, dish))
}
fn matching(&self, topic: &str) -> Vec<(Arc<DishPort>, JoinTerms)> {
let mut combined: HashMap<usize, JoinTerms> = HashMap::new();
self.index.matching(topic, |conn_id, terms| {
combined
.entry(conn_id)
.and_modify(|seen| *seen = seen.merge(terms))
.or_insert_with(|| terms.clone());
});
combined
.into_iter()
.filter_map(|(conn_id, terms)| {
let dish = self.dishes.get(&conn_id)?;
Some((Arc::clone(&dish.port), terms))
})
.collect()
}
fn withdraw(&mut self, conn_id: usize, withdrawn: &str) -> bool {
let Some(dish) = self.dishes.get_mut(&conn_id) else {
return false;
};
if dish.filters.remove(withdrawn).is_none() {
return false;
}
self.index.remove(conn_id, withdrawn);
if let Some(subs) = dish.port.conn.subs.as_ref() {
subs.release(conn_id);
}
let filters = &dish.filters;
lock(&dish.port.flows).retain(|topic, _| filters.keys().any(|f| filter::matches(topic, f)));
if dish.filters.is_empty() {
self.dishes.remove(&conn_id);
}
true
}
fn forget(&mut self, conn_id: usize, conn: &ConnHandle) {
let same = self
.dishes
.get(&conn_id)
.is_some_and(|dish| Arc::ptr_eq(&dish.port.conn, conn));
if !same {
return;
}
if let Some(dish) = self.dishes.remove(&conn_id) {
for filter in dish.filters.keys() {
self.index.remove(conn_id, filter);
}
}
}
}
enum FlowSlot {
Opening(Option<Bytes>),
Open {
flow: Flow,
since: Instant,
backoff: Duration,
},
Refused { until: Instant, backoff: Duration },
}
const FLOW_BACKOFF_START: Duration = Duration::from_millis(100);
const FLOW_BACKOFF_MAX: Duration = Duration::from_secs(30);
const FLOW_SETTLE: Duration = FLOW_BACKOFF_MAX;
fn doubled(backoff: Duration) -> Duration {
(backoff * 2).min(FLOW_BACKOFF_MAX)
}
pub(crate) struct RadioHub {
path: Arc<str>,
dishes: Arc<Mutex<DishTable>>,
topics: SegmentTopics,
drops: Arc<DropTable>,
limits: Limits,
admission: Mutex<(u64, Option<Admission>)>,
}
impl RadioHub {
pub(crate) fn new(path: &str, limits: Limits) -> RadioHub {
RadioHub {
path: Arc::from(path),
dishes: Arc::new(Mutex::new(DishTable {
dishes: HashMap::new(),
index: FilterIndex::new(),
})),
topics: SegmentTopics::new(limits.max_sequence_scopes),
drops: Arc::new(DropTable::new(limits.max_sequence_scopes)),
limits,
admission: Mutex::new((0, None)),
}
}
fn dishes(&self) -> MutexGuard<'_, DishTable> {
lock(&self.dishes)
}
fn new_dish(&self, ctx: &ConnHandle, conn_id: usize) -> DishEntry {
let port = Arc::new(DishPort {
conn: ConnHandle::clone(ctx),
budget: Arc::new(Semaphore::new(
self.limits
.subscriber_buffer_bytes
.min(Semaphore::MAX_PERMITS),
)),
flows: Mutex::new(HashMap::new()),
drops: Arc::new(Causes::default()),
});
let watch = ctx.exec.spawn(forget_when_closed(
Arc::downgrade(&self.dishes),
ConnHandle::clone(ctx),
conn_id,
));
DishEntry {
port,
filters: HashMap::new(),
watch,
}
}
pub(crate) fn join(
&self,
ctx: &ConnHandle,
filter: String,
max_age_ms: Option<u64>,
max_layer: Option<u8>,
reserve: impl FnOnce() -> Result<(), Error>,
) -> Result<(), Error> {
let conn_id = ctx.conn.stable_id();
let terms = JoinTerms {
max_age: max_age_ms.map(Duration::from_millis),
max_layer,
};
let mut guard = loop {
let (generation, admit) = {
let admission = lock(&self.admission);
(admission.0, admission.1.clone())
};
if let Some(admit) = admit
&& !admit(&Join::of(ctx, &filter))
{
tracing::debug!(path = %self.path, filter, "join refused by admission");
return Ok(());
}
let dishes = self.dishes();
if lock(&self.admission).0 == generation {
break dishes;
}
};
let table = &mut *guard;
if let Some(dish) = table.dishes.get_mut(&conn_id)
&& let Some(held) = dish.filters.get_mut(&filter)
{
*held = terms.clone();
table.index.insert(conn_id, &filter, terms);
return Ok(());
}
reserve()?;
let dish = table
.dishes
.entry(conn_id)
.or_insert_with(|| self.new_dish(ctx, conn_id));
dish.filters.insert(filter.clone(), terms.clone());
table.index.insert(conn_id, &filter, terms);
Ok(())
}
pub(crate) fn leave(&self, conn_id: usize, filter: &str) {
self.dishes().withdraw(conn_id, filter);
}
pub(crate) fn evict(&self, peer: &PeerIdentity, filter: &str) -> usize {
let mut table = self.dishes();
let holders: Vec<usize> = table
.live()
.filter(|(_, dish)| {
dish.port.conn.peer.as_ref() == Some(peer) && dish.filters.contains_key(filter)
})
.map(|(conn_id, _)| conn_id)
.collect();
let mut evicted = 0;
for conn_id in holders {
if table.withdraw(conn_id, filter) {
evicted += 1;
}
}
evicted
}
pub(crate) fn set_admission(&self, admit: Admission) {
{
let mut admission = lock(&self.admission);
admission.0 += 1;
admission.1 = Some(Arc::clone(&admit));
}
let recorded: Vec<(usize, ConnHandle, Vec<String>)> = self
.dishes()
.live()
.map(|(conn_id, dish)| {
(
conn_id,
ConnHandle::clone(&dish.port.conn),
dish.filters.keys().cloned().collect(),
)
})
.collect();
let refused: Vec<(usize, String)> = recorded
.iter()
.flat_map(|(conn_id, conn, filters)| {
filters
.iter()
.filter(|f| !admit(&Join::of(conn, f)))
.map(|f| (*conn_id, f.clone()))
})
.collect();
if refused.is_empty() {
return;
}
let mut table = self.dishes();
for (conn_id, filter) in &refused {
table.withdraw(*conn_id, filter);
}
}
}
async fn forget_when_closed(dishes: Weak<Mutex<DishTable>>, conn: ConnHandle, conn_id: usize) {
let _ = conn.conn.closed().await;
if let Some(dishes) = dishes.upgrade() {
lock(&dishes).forget(conn_id, &conn);
}
}
#[derive(Clone)]
pub struct RadioState {
hub: Arc<RadioHub>,
_claim: Arc<Claim>,
}
struct Claim {
namespace: Arc<Namespace>,
path: Arc<str>,
}
impl Drop for Claim {
fn drop(&mut self) {
self.namespace.unregister(&self.path);
}
}
impl RadioState {
pub(crate) fn new(hub: Arc<RadioHub>, namespace: Arc<Namespace>) -> RadioState {
let path = Arc::clone(&hub.path);
RadioState {
hub,
_claim: Arc::new(Claim { namespace, path }),
}
}
}
impl Clone for Radio {
fn clone(&self) -> Radio {
Radio::from_state(self.state().clone())
}
}
impl Radio {
fn hub(&self) -> &RadioHub {
&self.state().hub
}
pub fn segment(&self, topic: &str, terms: SegmentTerms) -> Result<Segment, Error> {
if topic.len() > MAX_TOPIC_BYTES {
return Err(Error::LimitExceeded);
}
let hub = self.hub();
let topic: Arc<str> = Arc::from(topic);
let number = hub.topics.next(&topic)?;
let targets: Vec<CopyTarget> = hub
.dishes()
.matching(&topic)
.into_iter()
.map(|(port, joined)| CopyTarget {
conn: ConnHandle::clone(&port.conn),
path: Arc::clone(&hub.path),
budget: Arc::clone(&port.budget),
max_age: joined.max_age,
max_layer: joined.max_layer,
dish: Some(Arc::clone(&port.drops)),
})
.collect();
Ok(open_segment(
&hub.topics,
&hub.drops,
topic,
number,
&terms,
targets,
))
}
pub fn datagram(&self, topic: &str, payload: impl AsRef<[u8]>) -> Result<usize, Error> {
if topic.len() > MAX_TOPIC_BYTES {
return Err(Error::LimitExceeded);
}
let hub = self.hub();
let topic: Arc<str> = Arc::from(topic);
let number = hub.topics.next(&topic)?;
let payload = payload.as_ref();
let mut frame = Vec::with_capacity(8 + payload.len());
encode_varint(number, &mut frame).expect("segment numbers stay below 2^62");
frame.extend_from_slice(payload);
let body = Bytes::from(frame);
let dishes = hub.dishes().matching(&topic);
let mut handed = 0;
for (port, _) in dishes {
if !port.conn.agreed_now().is_some_and(|a| a.datagrams) {
record(&hub.drops, &port.drops, &topic, DropCause::NoDatagrams);
continue;
}
let mut flows = lock(&port.flows);
match flows.get_mut(&topic) {
None => {
flows.insert(Arc::clone(&topic), FlowSlot::Opening(Some(body.clone())));
spawn_flow_open(&port, hub, &topic, FLOW_BACKOFF_START);
handed += 1;
}
Some(slot) => {
let next = match &mut *slot {
FlowSlot::Opening(pending) => {
if pending.replace(body.clone()).is_some() {
record(&hub.drops, &port.drops, &topic, DropCause::SubscriberQueue);
}
handed += 1;
None
}
FlowSlot::Open {
flow,
since,
backoff,
} => match flow.send(body.clone()) {
Ok(()) => {
handed += 1;
if since.elapsed() >= FLOW_SETTLE {
*backoff = FLOW_BACKOFF_START;
}
None
}
Err(Error::TooLarge { .. }) => {
record(&hub.drops, &port.drops, &topic, DropCause::TooLarge);
None
}
Err(Error::DatagramsUnavailable) => {
record(&hub.drops, &port.drops, &topic, DropCause::NoDatagrams);
None
}
Err(_) => {
record(&hub.drops, &port.drops, &topic, DropCause::SubscriberQueue);
Some(FlowSlot::Refused {
until: Instant::now() + *backoff,
backoff: doubled(*backoff),
})
}
},
FlowSlot::Refused { until, backoff } => {
if Instant::now() < *until {
record(&hub.drops, &port.drops, &topic, DropCause::SubscriberQueue);
None
} else {
spawn_flow_open(&port, hub, &topic, *backoff);
handed += 1;
Some(FlowSlot::Opening(Some(body.clone())))
}
}
};
if let Some(next) = next {
*slot = next;
}
}
}
}
Ok(handed)
}
pub fn path(&self) -> &str {
&self.hub().path
}
pub fn dish_count(&self) -> usize {
self.hub().dishes().live().count()
}
pub fn dropped(&self) -> u64 {
self.hub().drops.total()
}
pub fn dropped_on(&self, topic: &str) -> Option<TopicDrops> {
self.hub().drops.on_topic(topic)
}
pub fn drops(&self) -> Vec<TopicDrops> {
self.hub().drops.by_topic()
}
pub fn with_admission(
self,
admit: impl Fn(&Join<'_>) -> bool + Send + Sync + 'static,
) -> Radio {
self.hub().set_admission(Arc::new(admit));
self
}
pub fn evict(&self, peer: &PeerIdentity, filter: &str) -> usize {
self.hub().evict(peer, filter)
}
pub fn dish_drops(&self) -> Vec<DishDrops> {
self.hub()
.dishes()
.live()
.map(|(_, dish)| dish.port.drops.dish_snapshot(dish.port.conn.peer.clone()))
.collect()
}
}
fn record(drops: &DropTable, dish: &Causes, topic: &Arc<str>, cause: DropCause) {
drops.record(topic, cause);
dish.record(cause);
}
async fn open_datagram_flow(
port: Arc<DishPort>,
path: Arc<str>,
topic: Arc<str>,
drops: Arc<DropTable>,
backoff: Duration,
) {
let meta = FlowMeta::default().with_topic(topic.as_ref());
let opened = open_flow_on(&port.conn, &path, &meta).await;
let mut flows = lock(&port.flows);
let Some(slot) = flows.get_mut(&topic) else {
return;
};
let pending = match &mut *slot {
FlowSlot::Opening(pending) => pending.take(),
_ => return,
};
match opened {
Ok(flow) => {
if let Some(body) = pending {
match flow.send(body) {
Ok(()) => {}
Err(Error::TooLarge { .. }) => {
record(&drops, &port.drops, &topic, DropCause::TooLarge);
}
Err(_) => record(&drops, &port.drops, &topic, DropCause::SubscriberQueue),
}
}
*slot = FlowSlot::Open {
flow,
since: Instant::now(),
backoff,
};
}
Err(e) => {
if pending.is_some() {
let cause = match e {
Error::DatagramsUnavailable => DropCause::NoDatagrams,
_ => DropCause::SubscriberQueue,
};
record(&drops, &port.drops, &topic, cause);
}
*slot = FlowSlot::Refused {
until: Instant::now() + backoff,
backoff: doubled(backoff),
};
}
}
}
fn spawn_flow_open(port: &Arc<DishPort>, hub: &RadioHub, topic: &Arc<str>, backoff: Duration) {
port.conn.exec.spawn(open_datagram_flow(
Arc::clone(port),
Arc::clone(&hub.path),
Arc::clone(topic),
Arc::clone(&hub.drops),
backoff,
));
}
pub(crate) async fn pump_flow(ctx: ConnHandle, route: DishRoute, flow: IncomingFlow) {
let Some(topic) = flow.info().topic.as_deref().map(Arc::<str>::from) else {
return;
};
while let Some(datagram) = flow.recv().await {
let Some((segment, offset)) = split_flow_datagram(&datagram) else {
route.shared.overflow.fetch_add(1, Ordering::Relaxed);
continue;
};
if !ctx
.segments_in
.fresh(&flow.info().endpoint, &topic, segment, 0)
{
route.shared.stale.fetch_add(1, Ordering::Relaxed);
continue;
}
let received = Received::Datagram {
topic: Arc::clone(&topic),
segment,
payload: Bytes::copy_from_slice(&datagram[offset..]),
};
if route.queue.try_send(received).is_err() {
route.shared.overflow.fetch_add(1, Ordering::Relaxed);
}
}
}
#[derive(Debug)]
pub enum Received {
Segment(IncomingTransfer),
Datagram {
topic: Arc<str>,
segment: u64,
payload: Bytes,
},
}
pub(crate) struct DishShared {
stale: AtomicU64,
overflow: AtomicU64,
}
#[derive(Clone)]
pub(crate) struct DishRoute {
queue: mpsc::Sender<Received>,
shared: Arc<DishShared>,
}
pub(crate) fn deliver_segment(
ctx: &ConnHandle,
path: &str,
route: &DishRoute,
transfer: IncomingTransfer,
) {
let meta = transfer.meta();
let (Some(topic), Some(segment)) = (meta.topic.as_deref(), meta.segment) else {
transfer.refuse(codes::UNSUPPORTED);
return;
};
if !ctx
.segments_in
.fresh(path, topic, segment, meta.layer.unwrap_or(0))
{
route.shared.stale.fetch_add(1, Ordering::Relaxed);
transfer.refuse(codes::CANCELED);
return;
}
if let Err(e) = route.queue.try_send(Received::Segment(transfer)) {
route.shared.overflow.fetch_add(1, Ordering::Relaxed);
if let Received::Segment(transfer) = e.into_inner() {
transfer.refuse(codes::CANCELED);
}
}
}
struct DishAttach {
joins: Arc<Mutex<HashMap<String, JoinTerms>>>,
route: DishRoute,
}
impl Attach for DishAttach {
fn attach<'a>(
&'a self,
conn: &'a ConnHandle,
path: &'a str,
) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'a>> {
Box::pin(async move {
if conn.conn.needs_reverse_pool() && conn.conn.park_reverse().await? == 0 {
return Err(Error::Unsupported);
}
conn.namespace
.register(path, Route::Dish(self.route.clone()))?;
if conn.conn.needs_reverse_pool() {
let maintaining = ConnHandle::clone(conn);
conn.exec
.spawn(async move { maintaining.conn.maintain_reverse().await });
}
let joins: Vec<(String, JoinTerms)> = lock(&self.joins)
.iter()
.map(|(f, terms)| (f.clone(), terms.clone()))
.collect();
for (filter, terms) in joins {
send_subscription(
conn,
FrameKind::Subscribe,
path,
&filter,
terms.max_age.map(millis),
terms.max_layer,
)
.await?;
}
Ok(())
})
}
}
fn millis(age: Duration) -> u64 {
u64::try_from(age.as_millis()).unwrap_or(u64::MAX)
}
pub struct DishState {
peer: Peer,
joins: Arc<Mutex<HashMap<String, JoinTerms>>>,
queue: tokio::sync::Mutex<mpsc::Receiver<Received>>,
shared: Arc<DishShared>,
}
impl DishState {
pub(crate) fn new(runtime: Arc<RuntimeInner>, tls: Arc<ClientTls>, depth: usize) -> DishState {
let (queue_tx, queue) = mpsc::channel(depth);
let joins = Arc::new(Mutex::new(HashMap::new()));
let shared = Arc::new(DishShared {
stale: AtomicU64::new(0),
overflow: AtomicU64::new(0),
});
let attach = DishAttach {
joins: Arc::clone(&joins),
route: DishRoute {
queue: queue_tx,
shared: Arc::clone(&shared),
},
};
DishState {
peer: Peer::with_attach(runtime, tls, Some(Arc::new(attach))),
joins,
queue: tokio::sync::Mutex::new(queue),
shared,
}
}
}
impl Dish {
pub async fn connect(&self, url: &str) -> Result<(), Error> {
self.state().peer.connect(url).await
}
pub fn peer_count(&self) -> usize {
self.state().peer.peer_count()
}
pub fn connection_stats(&self) -> Vec<crate::ConnectionStats> {
self.state().peer.connection_stats()
}
pub fn events(&self) -> PeerEvents {
self.state().peer.events()
}
pub async fn join(&self, filter: &str, terms: JoinTerms) -> Result<(), Error> {
if terms
.max_layer
.is_some_and(|l| l >= crate::segment::MAX_SEGMENT_LAYERS)
{
return Err(Error::LimitExceeded);
}
weida_protocol::filter::validate(filter)?;
lock(&self.state().joins).insert(filter.to_owned(), terms.clone());
for (conn, path) in self.state().peer.live_peers() {
send_subscription(
&conn,
FrameKind::Subscribe,
&path,
filter,
terms.max_age.map(millis),
terms.max_layer,
)
.await?;
}
Ok(())
}
pub async fn leave(&self, filter: &str) -> Result<(), Error> {
if lock(&self.state().joins).remove(filter).is_none() {
return Ok(());
}
for (conn, path) in self.state().peer.live_peers() {
send_subscription(&conn, FrameKind::Unsubscribe, &path, filter, None, None).await?;
}
Ok(())
}
pub async fn recv(&self) -> Result<Received, Error> {
let mut queue = self.state().queue.lock().await;
queue.recv().await.ok_or(Error::NotConnected)
}
pub fn stale(&self) -> u64 {
self.state().shared.stale.load(Ordering::Relaxed)
}
pub fn overflow(&self) -> u64 {
self.state().shared.overflow.load(Ordering::Relaxed)
}
}
impl Drop for DishState {
fn drop(&mut self) {
let joins: Vec<String> = lock(&self.joins).keys().cloned().collect();
for (conn, path) in self.peer.live_peers() {
conn.namespace.unregister(&path);
for filter in &joins {
conn.notify(Ctl::SendUnsubscribe {
path: Arc::clone(&path),
filter: filter.clone(),
});
}
}
}
}