use std::sync::Mutex;
use tilo_lock::MutexRecover as _;
use super::{
ActionCallError, ActionProvider, Caller, CataloguePage, CatalogueQuery, InvocationReceipt,
InvocationState, InvokeRequest, Pending, ReceiptStatus,
};
use crate::outcome::{ActionOutput, InvocationId};
type Catalogue =
dyn Fn(&Caller, CatalogueQuery) -> Result<CataloguePage, ActionCallError> + Send + Sync;
type Answer = dyn Fn(&Caller, &InvokeRequest) -> Pending<Result<InvocationReceipt, ActionCallError>>
+ Send
+ Sync;
pub struct TestProvider {
catalogue: Box<Catalogue>,
answer: Box<Answer>,
asked: Mutex<Vec<InvokeRequest>>,
callers: Mutex<Vec<Caller>>,
}
impl Default for TestProvider {
fn default() -> Self {
Self::new()
}
}
impl TestProvider {
#[must_use]
pub fn new() -> Self {
Self {
catalogue: Box::new(|_, _| Ok(CataloguePage::default())),
answer: Box::new(|_, request| {
Pending::ready(Ok(InvocationReceipt {
invocation: request.invocation,
status: ReceiptStatus::Completed {
output: ActionOutput::default(),
},
}))
}),
asked: Mutex::new(Vec::new()),
callers: Mutex::new(Vec::new()),
}
}
#[must_use]
pub fn with_catalogue(
mut self,
catalogue: impl Fn(&Caller, CatalogueQuery) -> Result<CataloguePage, ActionCallError>
+ Send
+ Sync
+ 'static,
) -> Self {
self.catalogue = Box::new(catalogue);
self
}
#[must_use]
pub fn completing(
self,
output: impl Fn(&InvokeRequest) -> ActionOutput + Send + Sync + 'static,
) -> Self {
self.answering(move |_, request| {
Pending::ready(Ok(InvocationReceipt {
invocation: request.invocation,
status: ReceiptStatus::Completed {
output: output(request),
},
}))
})
}
#[must_use]
pub fn answering(
mut self,
answer: impl Fn(&Caller, &InvokeRequest) -> Pending<Result<InvocationReceipt, ActionCallError>>
+ Send
+ Sync
+ 'static,
) -> Self {
self.answer = Box::new(answer);
self
}
pub fn asked(&self) -> Vec<InvokeRequest> {
self.asked.lock_recover().clone()
}
pub fn take_asked(&self) -> Vec<InvokeRequest> {
std::mem::take(&mut *self.asked.lock_recover())
}
pub fn callers(&self) -> Vec<Caller> {
self.callers.lock_recover().clone()
}
}
impl ActionProvider for TestProvider {
fn query(
&self,
caller: &Caller,
query: CatalogueQuery,
) -> Pending<Result<CataloguePage, ActionCallError>> {
self.callers.lock_recover().push(caller.clone());
Pending::ready((self.catalogue)(caller, query))
}
fn invoke(
&self,
caller: &Caller,
request: InvokeRequest,
) -> Pending<Result<InvocationReceipt, ActionCallError>> {
self.callers.lock_recover().push(caller.clone());
let answer = (self.answer)(caller, &request);
self.asked.lock_recover().push(request);
answer
}
fn observe(&self, _caller: &Caller, _id: &InvocationId) -> Option<InvocationState> {
None
}
fn cancel(&self, _caller: &Caller, _id: &InvocationId) -> Pending<Result<(), ActionCallError>> {
Pending::ready(Ok(()))
}
}