use std::collections::HashMap;
use std::pin::Pin;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;
use bytes::Bytes;
use tokio::sync::{Semaphore, mpsc};
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, 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
}
}
struct DishEntry {
conn: ConnHandle,
conn_id: usize,
filters: HashMap<String, JoinTerms>,
budget: Arc<Semaphore>,
flows: Arc<Mutex<HashMap<Arc<str>, FlowSlot>>>,
drops: Arc<Causes>,
}
enum FlowSlot {
Opening(Option<Bytes>),
Open(Flow),
}
impl DishEntry {
fn matching(&self, topic: &str) -> Option<JoinTerms> {
let mut combined: Option<JoinTerms> = None;
for (f, terms) in &self.filters {
if !filter::matches(topic, f) {
continue;
}
combined = Some(match combined {
None => terms.clone(),
Some(seen) => JoinTerms {
max_age: match (seen.max_age, terms.max_age) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
},
max_layer: seen.max_layer.zip(terms.max_layer).map(|(a, b)| a.max(b)),
},
});
}
combined
}
fn drop_filter(&mut self, withdrawn: &str) -> bool {
if self.filters.remove(withdrawn).is_none() {
return false;
}
if let Some(subs) = self.conn.subs.as_ref() {
subs.release(self.conn_id);
}
let filters = &self.filters;
lock(&self.flows).retain(|topic, _| filters.keys().any(|f| filter::matches(topic, f)));
true
}
}
pub(crate) struct RadioHub {
path: Arc<str>,
dishes: Mutex<Vec<DishEntry>>,
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: Mutex::new(Vec::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<'_, Vec<DishEntry>> {
let mut dishes = lock(&self.dishes);
dishes.retain(|d| d.conn.conn.close_reason().is_none());
dishes
}
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 dishes = 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 index = match dishes.iter().position(|d| d.conn_id == conn_id) {
Some(index) => index,
None => {
dishes.push(DishEntry {
conn: ConnHandle::clone(ctx),
conn_id,
filters: HashMap::new(),
budget: Arc::new(Semaphore::new(self.limits.subscriber_buffer_bytes)),
flows: Arc::new(Mutex::new(HashMap::new())),
drops: Arc::new(Causes::default()),
});
dishes.len() - 1
}
};
let entry = &mut dishes[index];
if let Some(held) = entry.filters.get_mut(&filter) {
*held = terms;
return Ok(());
}
if let Err(e) = reserve() {
if entry.filters.is_empty() {
dishes.swap_remove(index);
}
return Err(e);
}
entry.filters.insert(filter, terms);
Ok(())
}
pub(crate) fn leave(&self, conn_id: usize, filter: &str) {
let mut dishes = self.dishes();
let Some(index) = dishes.iter().position(|d| d.conn_id == conn_id) else {
return;
};
dishes[index].drop_filter(filter);
if dishes[index].filters.is_empty() {
dishes.swap_remove(index);
}
}
pub(crate) fn evict(&self, peer: &PeerIdentity, filter: &str) -> usize {
let mut dishes = self.dishes();
let mut evicted = 0;
for entry in dishes.iter_mut() {
if entry.conn.peer.as_ref() == Some(peer) && entry.drop_filter(filter) {
evicted += 1;
}
}
dishes.retain(|d| !d.filters.is_empty());
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()
.iter()
.map(|d| {
(
d.conn_id,
ConnHandle::clone(&d.conn),
d.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 dishes = self.dishes();
for (conn_id, filter) in &refused {
if let Some(entry) = dishes.iter_mut().find(|d| d.conn_id == *conn_id) {
entry.drop_filter(filter);
}
}
dishes.retain(|d| !d.filters.is_empty());
}
}
#[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 = hub
.dishes()
.iter()
.filter_map(|entry| {
entry.matching(&topic).map(|joined| CopyTarget {
conn: ConnHandle::clone(&entry.conn),
path: Arc::clone(&hub.path),
budget: Arc::clone(&entry.budget),
max_age: joined.max_age,
max_layer: joined.max_layer,
dish: Some(Arc::clone(&entry.drops)),
})
})
.collect();
Ok(open_segment(
&hub.topics,
&hub.drops,
topic,
number,
&terms,
targets,
))
}
pub fn datagram(&self, topic: &str, payload: impl Into<Bytes>) -> 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.into();
let mut body = Vec::with_capacity(8 + payload.len());
encode_varint(number, &mut body).expect("segment numbers stay below 2^62");
body.extend_from_slice(&payload);
let body = Bytes::from(body);
let mut handed = 0;
for entry in hub.dishes().iter() {
if entry.matching(&topic).is_none() {
continue;
}
if !entry.conn.agreed_now().is_some_and(|a| a.datagrams) {
record(&hub.drops, &entry.drops, &topic, DropCause::NoDatagrams);
continue;
}
let mut flows = lock(&entry.flows);
match flows.get_mut(&topic) {
Some(FlowSlot::Open(flow)) => match flow.send(body.clone()) {
Ok(()) => handed += 1,
Err(Error::TooLarge { .. }) => {
record(&hub.drops, &entry.drops, &topic, DropCause::TooLarge);
}
Err(Error::DatagramsUnavailable) => {
record(&hub.drops, &entry.drops, &topic, DropCause::NoDatagrams);
}
Err(_) => {
flows.remove(&topic);
record(&hub.drops, &entry.drops, &topic, DropCause::SubscriberQueue);
}
},
Some(FlowSlot::Opening(pending)) => {
if pending.replace(body.clone()).is_some() {
record(&hub.drops, &entry.drops, &topic, DropCause::SubscriberQueue);
}
handed += 1;
}
None => {
flows.insert(Arc::clone(&topic), FlowSlot::Opening(Some(body.clone())));
entry.conn.exec.spawn(open_datagram_flow(
ConnHandle::clone(&entry.conn),
Arc::clone(&hub.path),
Arc::clone(&topic),
Arc::clone(&entry.flows),
Arc::clone(&hub.drops),
Arc::clone(&entry.drops),
));
handed += 1;
}
}
}
Ok(handed)
}
pub fn path(&self) -> &str {
&self.hub().path
}
pub fn dish_count(&self) -> usize {
self.hub().dishes().len()
}
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()
.iter()
.map(|d| d.drops.dish_snapshot(d.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(
conn: ConnHandle,
path: Arc<str>,
topic: Arc<str>,
flows: Arc<Mutex<HashMap<Arc<str>, FlowSlot>>>,
drops: Arc<DropTable>,
dish: Arc<Causes>,
) {
let meta = FlowMeta::default().with_topic(topic.as_ref());
let opened = open_flow_on(&conn, &path, &meta).await;
let mut flows = lock(&flows);
match opened {
Ok(flow) => {
let Some(slot) = flows.get_mut(&topic) else {
return;
};
if let FlowSlot::Opening(pending) = slot
&& let Some(body) = pending.take()
{
match flow.send(body) {
Ok(()) => {}
Err(Error::TooLarge { .. }) => {
record(&drops, &dish, &topic, DropCause::TooLarge);
}
Err(_) => record(&drops, &dish, &topic, DropCause::SubscriberQueue),
}
}
*slot = FlowSlot::Open(flow);
}
Err(e) => {
if let Some(FlowSlot::Opening(Some(_))) = flows.remove(&topic) {
let cause = match e {
Error::DatagramsUnavailable => DropCause::NoDatagrams,
_ => DropCause::SubscriberQueue,
};
record(&drops, &dish, &topic, cause);
}
}
}
}
pub(crate) async fn pump_flow(ctx: ConnHandle, route: DishRoute, flow: IncomingFlow) {
let Some(topic) = flow.info().topic.clone() 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: topic.clone(),
segment,
payload: datagram.slice(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: String,
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(),
});
}
}
}
}