mod dispatch;
pub mod ext;
pub mod protocols;
#[cfg(rings_native)]
pub mod transport;
use std::sync::Arc;
use bytes::Bytes;
use futures::FutureExt;
use rings_core::lifecycle::StopToken;
use rings_core::message::CustomMessage;
use rings_core::swarm::application::ApplicationData;
use rings_core::swarm::application::ApplicationDelivery;
use rings_core::swarm::application::ApplicationInbox;
use rings_core::swarm::application::ApplicationMessage;
pub use crate::extension::dispatch::DispatchDropCounters;
pub(crate) use crate::extension::dispatch::DispatchDrops;
use crate::extension::ext::Extensions;
use crate::extension::ext::LinkFact;
use crate::provider::Provider;
pub trait BackendObserver: Send + Sync {
fn link_fact(&self, _fact: LinkFact) {}
fn e2e_message(&self, _message: &ApplicationMessage) {}
}
pub struct Backend {
extensions: Extensions,
drops: Arc<DispatchDrops>,
observer: Option<Arc<dyn BackendObserver>>,
}
impl Backend {
pub fn new(provider: Arc<Provider>) -> Self {
Self {
extensions: provider.extensions(),
drops: provider.dispatch_drops(),
observer: None,
}
}
pub fn observed_by(mut self, observer: Arc<dyn BackendObserver>) -> Self {
self.observer = Some(observer);
self
}
pub async fn serve(self, inbox: ApplicationInbox, stop: StopToken) {
let mut namespaces = dispatch::NamespaceQueues::new(
self.extensions.core(),
Arc::clone(&self.drops),
stop.clone(),
);
loop {
let delivery = futures::select_biased! {
() = stop.stopped().fuse() => return,
delivery = inbox.next().fuse() => delivery,
};
let Some(delivery) = delivery else {
return;
};
self.route(&mut namespaces, delivery);
}
}
fn route(&self, namespaces: &mut dispatch::NamespaceQueues, delivery: ApplicationDelivery) {
match delivery {
ApplicationDelivery::Message(ApplicationMessage {
from,
data: ApplicationData::Custom(CustomMessage(bytes)),
..
}) => namespaces.submit(from, &Bytes::from(bytes)),
ApplicationDelivery::Message(message) => {
if let Some(observer) = self.observer.as_deref() {
observer.e2e_message(&message);
}
}
ApplicationDelivery::Event(event) => {
if let Some(fact) = LinkFact::of(&event) {
namespaces.submit_link_fact(fact);
if let Some(observer) = self.observer.as_deref() {
observer.link_fact(fact);
}
}
}
_ => {}
}
}
}