use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use super::{
ActionCallError, ActionProvider, Caller, CataloguePage, CatalogueQuery, CatalogueRow,
InvocationReceipt, InvocationState, InvokeRequest, Pending, ReceiptStatus,
};
use crate::api::{ActionDescriptor, PlacedAction};
use crate::{
ActionAddress, ActionContract, ActionFailure, ActionOutput, InvocationId, OperationKind,
ResourceSemanticIdentity,
};
pub type Outcome = Result<ActionOutput, Box<ActionFailure>>;
pub type ReportsProgress = Arc<dyn Fn(&str, Option<u64>, Option<u64>) + Send + Sync>;
#[derive(Clone)]
pub struct Admitted {
pub through: Option<Arc<dyn ActionProvider + Send + Sync>>,
pub stop: Arc<AtomicBool>,
pub serving: Option<Arc<dyn Serving>>,
pub progress: ReportsProgress,
}
impl Default for Admitted {
fn default() -> Self {
Self {
through: None,
stop: Arc::new(AtomicBool::new(false)),
serving: None,
progress: Arc::new(|_, _, _| {}),
}
}
}
pub trait Serving: Send + Sync {
fn invocation(&self) -> InvocationId;
fn app(&self) -> &str;
fn workspace(&self) -> &str;
fn record(&self) -> &str;
fn address(&self) -> &ActionAddress;
fn kind(&self) -> OperationKind;
fn contract(&self) -> &ActionContract;
fn argument(&self) -> Option<&str>;
fn resource_identity(&self) -> Result<&ResourceSemanticIdentity, String>;
fn recheck(&self) -> Result<(), String>;
}
pub trait Admits {
const PROVIDER: &'static str;
const APP: &'static str;
fn rows(&self) -> Vec<PlacedAction>;
fn start(
&self,
caller: &Caller,
request: &InvokeRequest,
admitted: &Admitted,
) -> Result<Pending<Outcome>, String>;
fn asks_first(
&self,
caller: &Caller,
request: &InvokeRequest,
admitted: &Admitted,
) -> Option<Pending<Result<(), ActionCallError>>> {
let _ = (caller, request, admitted);
None
}
fn described(
&self,
address: &ActionAddress,
argument: Option<&str>,
) -> Option<ActionDescriptor> {
let _ = (address, argument);
None
}
fn live(&self, caller: &Caller, request: &InvokeRequest) -> Result<LiveView, String> {
let _ = (caller, request);
Err("this action has no live result".into())
}
}
impl<T: Admits> ActionProvider for T {
fn query(
&self,
_caller: &Caller,
query: CatalogueQuery,
) -> Pending<Result<CataloguePage, ActionCallError>> {
offered(T::PROVIDER, T::APP, self.rows(), &query)
}
fn invoke(
&self,
caller: &Caller,
request: InvokeRequest,
) -> Pending<Result<InvocationReceipt, ActionCallError>> {
self.run(caller, request, Admitted::default())
}
fn observe(&self, _caller: &Caller, _id: &InvocationId) -> Option<InvocationState> {
None
}
fn cancel(&self, _caller: &Caller, _id: &InvocationId) -> Pending<Result<(), ActionCallError>> {
Pending::ready(Err(ActionCallError::UnknownInvocation))
}
fn invocation(
&self,
address: &ActionAddress,
argument: Option<&str>,
) -> Option<ActionDescriptor> {
self.described(address, argument)
}
fn run(
&self,
caller: &Caller,
request: InvokeRequest,
admitted: Admitted,
) -> Pending<Result<InvocationReceipt, ActionCallError>> {
settled(request.invocation, self.start(caller, &request, &admitted))
}
fn asks_first(
&self,
caller: &Caller,
request: &InvokeRequest,
admitted: &Admitted,
) -> Option<Pending<Result<(), ActionCallError>>> {
Admits::asks_first(self, caller, request, admitted)
}
fn watch(&self, caller: &Caller, request: &InvokeRequest) -> Result<LiveView, String> {
self.live(caller, request)
}
}
pub struct LiveView {
pub read: Box<dyn FnMut() -> Pending<LiveRead> + Send>,
pub changes: Box<dyn FnMut() -> Pending<()> + Send>,
}
pub type LiveRead = Result<serde_json::Value, Box<ActionFailure>>;
#[must_use]
pub fn settled(
invocation: InvocationId,
started: Result<Pending<Outcome>, String>,
) -> Pending<Result<InvocationReceipt, ActionCallError>> {
match started {
Err(reason) => Pending::ready(Err(ActionCallError::Refused { reason })),
Ok(started) => started.map(move |outcome| {
Ok(InvocationReceipt {
invocation,
status: match outcome {
Ok(output) => ReceiptStatus::Completed { output },
Err(error) => ReceiptStatus::Failed { error: *error },
},
})
}),
}
}
#[must_use]
pub fn offered(
provider: &str,
app_id: &str,
rows: Vec<PlacedAction>,
query: &CatalogueQuery,
) -> Pending<Result<CataloguePage, ActionCallError>> {
let rows: Vec<CatalogueRow> = rows
.into_iter()
.map(|placed| CatalogueRow::for_placed_action(provider, app_id, placed))
.collect();
let revision = rows.len().to_string();
Pending::ready(Ok(CataloguePage::from_rows(revision, rows, query)))
}
#[must_use]
pub fn top_level(actions: Vec<ActionDescriptor>) -> Vec<PlacedAction> {
actions
.into_iter()
.map(|action| PlacedAction {
parent: String::new(),
has_children: false,
action,
})
.collect()
}