use std::collections::{BTreeMap, VecDeque};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant};
use microrti_proto::{CallRequest, CallResponse, CallbackRequest, CallbackResponse};
use crate::link::{LinkCallback, LinkError, LinkFactory, LinkState, RtiLink};
use crate::types::RtiConfiguration;
pub trait LocalRti: Send {
fn open_connection(&mut self) -> u64;
fn call(&mut self, connection: u64, request: CallRequest) -> CallResponse;
fn take_callbacks(&mut self, connection: u64) -> Vec<CallbackRequest>;
fn callback_response(&mut self, connection: u64, callback: u64, response: CallbackResponse) {
let _ = (connection, callback, response);
}
fn close_connection(&mut self, connection: u64);
}
struct Session {
queue: VecDeque<CallbackRequest>,
next_id: u64,
}
struct Hub<R> {
rti: R,
sessions: BTreeMap<u64, Session>,
}
struct Inner<R> {
hub: Mutex<Hub<R>>,
wake: Condvar,
}
impl<R> Inner<R> {
fn lock(&self) -> MutexGuard<'_, Hub<R>> {
self.hub.lock().unwrap_or_else(PoisonError::into_inner)
}
}
pub struct LocalRtiHub<R: LocalRti> {
inner: Arc<Inner<R>>,
}
impl<R: LocalRti> Clone for LocalRtiHub<R> {
fn clone(&self) -> Self {
Self { inner: Arc::clone(&self.inner) }
}
}
impl<R: LocalRti + 'static> LocalRtiHub<R> {
pub fn new(rti: R) -> Self {
Self {
inner: Arc::new(Inner {
hub: Mutex::new(Hub { rti, sessions: BTreeMap::new() }),
wake: Condvar::new(),
}),
}
}
pub fn link(&self) -> Arc<dyn RtiLink> {
let mut hub = self.inner.lock();
let connection = hub.rti.open_connection();
hub.sessions.insert(connection, Session { queue: VecDeque::new(), next_id: 1 });
Arc::new(LocalLink { inner: Arc::clone(&self.inner), connection })
}
pub fn with_rti<T>(&self, action: impl FnOnce(&mut R) -> T) -> T {
let mut hub = self.inner.lock();
let value = action(&mut hub.rti);
self.inner.wake.notify_all();
value
}
}
impl<R: LocalRti + 'static> LinkFactory for LocalRtiHub<R> {
fn open(&self, _: &RtiConfiguration) -> Result<Arc<dyn RtiLink>, LinkError> {
Ok(self.link())
}
}
struct LocalLink<R: LocalRti> {
inner: Arc<Inner<R>>,
connection: u64,
}
impl<R: LocalRti> RtiLink for LocalLink<R> {
fn call(&self, request: CallRequest) -> Result<CallResponse, LinkError> {
let mut hub = self.inner.lock();
if !hub.sessions.contains_key(&self.connection) {
return Err(LinkError::Closed);
}
let response = hub.rti.call(self.connection, request);
self.inner.wake.notify_all();
Ok(response)
}
fn next_callback(&self, timeout: Option<Duration>) -> Result<Option<LinkCallback>, LinkError> {
let deadline = timeout.map(|timeout| Instant::now() + timeout);
let mut hub = self.inner.lock();
loop {
if !hub.sessions.contains_key(&self.connection) {
return Err(LinkError::Closed);
}
let fresh = hub.rti.take_callbacks(self.connection);
if let Some(session) = hub.sessions.get_mut(&self.connection) {
session.queue.extend(fresh);
if let Some(request) = session.queue.pop_front() {
let id = session.next_id;
session.next_id += 1;
return Ok(Some(LinkCallback { id, request }));
}
}
hub = match deadline {
None => self.inner.wake.wait(hub).unwrap_or_else(PoisonError::into_inner),
Some(deadline) => {
let now = Instant::now();
if now >= deadline {
return Ok(None);
}
self.inner
.wake
.wait_timeout(hub, deadline - now)
.unwrap_or_else(PoisonError::into_inner)
.0
}
};
}
}
fn respond(&self, id: u64, response: CallbackResponse) -> Result<(), LinkError> {
if let Some(microrti_proto::callback_response::CallbackResponse::CallbackFailed(failure)) =
&response.callback_response
{
tracing::debug!(callback = id, exception = %failure.exception_name, details = %failure.details, "callback failed");
}
let mut hub = self.inner.lock();
if hub.sessions.contains_key(&self.connection)
&& let Some(position) = id.checked_sub(1)
{
hub.rti.callback_response(self.connection, position, response);
self.inner.wake.notify_all();
}
Ok(())
}
fn state(&self) -> LinkState {
if self.inner.lock().sessions.contains_key(&self.connection) {
LinkState::Open
} else {
LinkState::Closed
}
}
fn close(&self) {
let mut hub = self.inner.lock();
if hub.sessions.remove(&self.connection).is_some() {
hub.rti.close_connection(self.connection);
self.inner.wake.notify_all();
}
}
}
impl<R: LocalRti> Drop for LocalLink<R> {
fn drop(&mut self) {
self.close();
}
}