use std::collections::VecDeque;
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant};
use microrti_proto as proto;
use proto::call_request::CallRequest as Call;
use proto::call_response::CallResponse as Reply;
use proto::callback_request::CallbackRequest as WireCallback;
use proto::callback_response::CallbackResponse as CallbackReply;
use crate::link::{LinkCallback, LinkError, LinkState, RtiLink};
mod replies;
pub use replies::default_reply;
pub type Responder = dyn Fn(&Call) -> Option<Reply> + Send + Sync;
enum Step {
Reply(Reply),
Raw(proto::CallResponse),
Fail(LinkError),
}
struct Inner {
state: LinkState,
requests: Vec<Call>,
script: VecDeque<Step>,
responder: Option<Arc<Responder>>,
callbacks: VecDeque<LinkCallback>,
next_callback_id: u64,
responses: Vec<(u64, CallbackReply)>,
}
pub struct MockLink {
inner: Mutex<Inner>,
changed: Condvar,
}
impl MockLink {
pub fn new() -> Arc<Self> {
Arc::new(MockLink {
inner: Mutex::new(Inner {
state: LinkState::Open,
requests: Vec::new(),
script: VecDeque::new(),
responder: None,
callbacks: VecDeque::new(),
next_callback_id: 1,
responses: Vec::new(),
}),
changed: Condvar::new(),
})
}
fn lock(&self) -> MutexGuard<'_, Inner> {
self.inner.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn push_reply(&self, reply: Reply) {
self.lock().script.push_back(Step::Reply(reply));
}
pub fn push_exception(&self, exception_name: &str, details: &str) {
self.push_reply(Reply::ExceptionData(proto::ExceptionData {
exception_name: exception_name.to_owned(),
details: details.to_owned(),
}));
}
pub fn push_raw_reply(&self, response: proto::CallResponse) {
self.lock().script.push_back(Step::Raw(response));
}
pub fn push_failure(&self, error: LinkError) {
self.lock().script.push_back(Step::Fail(error));
}
pub fn set_responder(&self, responder: impl Fn(&Call) -> Option<Reply> + Send + Sync + 'static) {
self.lock().responder = Some(Arc::new(responder));
}
pub fn requests(&self) -> Vec<Call> {
self.lock().requests.clone()
}
pub fn last_request(&self) -> Option<Call> {
self.lock().requests.last().cloned()
}
pub fn take_requests(&self) -> Vec<Call> {
std::mem::take(&mut self.lock().requests)
}
pub fn push_callback(&self, request: WireCallback) -> u64 {
self.push_raw_callback(proto::CallbackRequest { callback_request: Some(request) })
}
pub fn push_raw_callback(&self, request: proto::CallbackRequest) -> u64 {
let mut inner = self.lock();
let id = inner.next_callback_id;
inner.next_callback_id += 1;
inner.callbacks.push_back(LinkCallback { id, request });
self.changed.notify_all();
id
}
pub fn queued_callbacks(&self) -> usize {
self.lock().callbacks.len()
}
pub fn callback_responses(&self) -> Vec<(u64, CallbackReply)> {
self.lock().responses.clone()
}
pub fn wait_for_callback_responses(&self, count: usize, timeout: Duration) -> bool {
let deadline = Instant::now() + timeout;
let mut inner = self.lock();
while inner.responses.len() < count {
let now = Instant::now();
if now >= deadline {
return false;
}
inner =
self.changed.wait_timeout(inner, deadline - now).unwrap_or_else(PoisonError::into_inner).0;
}
true
}
pub fn lose_connection(&self, fault_description: &str) {
let mut inner = self.lock();
if inner.state == LinkState::Open {
inner.state = LinkState::Lost(fault_description.to_owned());
}
self.changed.notify_all();
}
pub fn is_closed(&self) -> bool {
self.lock().state == LinkState::Closed
}
}
impl std::fmt::Debug for MockLink {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let inner = self.lock();
f.debug_struct("MockLink")
.field("state", &inner.state)
.field("requests", &inner.requests.len())
.field("queued_callbacks", &inner.callbacks.len())
.finish()
}
}
impl RtiLink for MockLink {
fn call(&self, request: proto::CallRequest) -> Result<proto::CallResponse, LinkError> {
let Some(request) = request.call_request else {
return Err(LinkError::Failed("call request without an alternative".to_owned()));
};
let (step, responder) = {
let mut inner = self.lock();
match &inner.state {
LinkState::Open => {}
LinkState::Closed => return Err(LinkError::Closed),
LinkState::Lost(reason) => return Err(LinkError::Lost(reason.clone())),
}
inner.requests.push(request.clone());
(inner.script.pop_front(), inner.responder.clone())
};
let reply = match step {
Some(Step::Fail(error)) => return Err(error),
Some(Step::Raw(response)) => return Ok(response),
Some(Step::Reply(reply)) => reply,
None => {
responder.and_then(|responder| responder(&request)).unwrap_or_else(|| default_reply(&request))
}
};
Ok(proto::CallResponse { call_response: Some(reply) })
}
fn next_callback(&self, timeout: Option<Duration>) -> Result<Option<LinkCallback>, LinkError> {
let deadline = timeout.map(|timeout| Instant::now() + timeout);
let mut inner = self.lock();
loop {
if inner.state == LinkState::Closed {
return Err(LinkError::Closed);
}
if let Some(callback) = inner.callbacks.pop_front() {
return Ok(Some(callback));
}
if let LinkState::Lost(reason) = &inner.state {
return Err(LinkError::Lost(reason.clone()));
}
inner = match deadline {
None => self.changed.wait(inner).unwrap_or_else(PoisonError::into_inner),
Some(deadline) => {
let now = Instant::now();
if now >= deadline {
return Ok(None);
}
self.changed.wait_timeout(inner, deadline - now).unwrap_or_else(PoisonError::into_inner).0
}
};
}
}
fn respond(&self, id: u64, response: proto::CallbackResponse) -> Result<(), LinkError> {
let Some(response) = response.callback_response else {
return Err(LinkError::Failed("callback response without an alternative".to_owned()));
};
let mut inner = self.lock();
inner.responses.push((id, response));
self.changed.notify_all();
Ok(())
}
fn state(&self) -> LinkState {
self.lock().state.clone()
}
fn close(&self) {
let mut inner = self.lock();
inner.state = LinkState::Closed;
self.changed.notify_all();
}
}