use std::collections::BTreeMap;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use microrti_proto::{CallRequest, CallResponse, CallbackRequest, CallbackResponse};
use crate::types::RtiConfiguration;
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum LinkError {
#[error("connection to the RTI lost: {0}")]
Lost(String),
#[error("the link to the RTI is closed")]
Closed,
#[error("cannot reach the RTI: {0}")]
Unreachable(String),
#[error("link failure: {0}")]
Failed(String),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LinkState {
Open,
Closed,
Lost(String),
}
#[derive(Clone, Debug, PartialEq)]
pub struct LinkCallback {
pub id: u64,
pub request: CallbackRequest,
}
pub trait RtiLink: Send + Sync {
fn call(&self, request: CallRequest) -> Result<CallResponse, LinkError>;
fn next_callback(&self, timeout: Option<Duration>) -> Result<Option<LinkCallback>, LinkError>;
fn respond(&self, id: u64, response: CallbackResponse) -> Result<(), LinkError>;
fn state(&self) -> LinkState;
fn close(&self);
}
pub trait LinkFactory: Send + Sync {
fn open(&self, configuration: &RtiConfiguration) -> Result<Arc<dyn RtiLink>, LinkError>;
}
impl<F> LinkFactory for F
where
F: Fn(&RtiConfiguration) -> Result<Arc<dyn RtiLink>, LinkError> + Send + Sync,
{
fn open(&self, configuration: &RtiConfiguration) -> Result<Arc<dyn RtiLink>, LinkError> {
self(configuration)
}
}
#[derive(Clone, Default)]
pub struct Connectors {
by_scheme: BTreeMap<String, Arc<dyn LinkFactory>>,
fallback: Option<Arc<dyn LinkFactory>>,
}
impl Connectors {
pub const fn new() -> Self {
Self { by_scheme: BTreeMap::new(), fallback: None }
}
pub fn register(&mut self, scheme: &str, factory: impl LinkFactory + 'static) -> &mut Self {
self.by_scheme.insert(scheme.to_ascii_lowercase(), Arc::new(factory));
self
}
pub fn register_default(&mut self, factory: impl LinkFactory + 'static) -> &mut Self {
self.fallback = Some(Arc::new(factory));
self
}
pub fn schemes(&self) -> Vec<String> {
self.by_scheme.keys().cloned().collect()
}
pub fn resolve(&self, rti_address: &str) -> Option<Arc<dyn LinkFactory>> {
if let Some((scheme, rest)) = rti_address.split_once(':')
&& is_scheme(scheme)
{
if let Some(factory) = self.by_scheme.get(&scheme.to_ascii_lowercase()) {
return Some(Arc::clone(factory));
}
if rest.starts_with("//") {
return None;
}
}
self.fallback.clone()
}
pub fn open(&self, configuration: &RtiConfiguration) -> Result<Arc<dyn RtiLink>, LinkError> {
let address = configuration.rti_address();
match self.resolve(address) {
Some(factory) => factory.open(configuration),
None => {
Err(LinkError::Unreachable(format!("no connector registered for RTI address {address:?}")))
}
}
}
}
impl std::fmt::Debug for Connectors {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Connectors")
.field("schemes", &self.schemes())
.field("default", &self.fallback.is_some())
.finish()
}
}
fn is_scheme(text: &str) -> bool {
let mut chars = text.chars();
chars.next().is_some_and(|c| c.is_ascii_alphabetic())
&& chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
}
static GLOBAL: Mutex<Connectors> = Mutex::new(Connectors::new());
fn global() -> std::sync::MutexGuard<'static, Connectors> {
#[cfg(feature = "fedpro")]
{
static BUILT_IN: std::sync::Once = std::sync::Once::new();
BUILT_IN.call_once(|| {
let mut connectors = GLOBAL.lock().unwrap_or_else(PoisonError::into_inner);
crate::fedpro::FedProConnector::default().register(&mut connectors);
});
}
GLOBAL.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn register_connector(scheme: &str, factory: impl LinkFactory + 'static) {
global().register(scheme, factory);
}
pub fn register_default_connector(factory: impl LinkFactory + 'static) {
global().register_default(factory);
}
pub fn global_connectors() -> Connectors {
global().clone()
}