use std::collections::BTreeMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use super::{FunctionError, FunctionRequest, FunctionResponse};
use crate::Error;
pub type FunctionFuture =
Pin<Box<dyn Future<Output = Result<FunctionResponse, FunctionError>> + Send>>;
type AsyncMethod = dyn Fn(FunctionRequest) -> FunctionFuture + Send + Sync;
type SyncMethod = dyn Fn(FunctionRequest) -> Result<FunctionResponse, FunctionError> + Send + Sync;
#[derive(Clone, Default)]
pub struct Functions {
methods: BTreeMap<String, Method>,
invalid: Option<String>,
}
#[cfg_attr(
not(any(
feature = "boa",
feature = "quickjs",
feature = "v8",
feature = "fuzzing",
test
)),
allow(dead_code, reason = "only the host bridge calls methods")
)]
#[derive(Clone)]
pub(crate) enum Method {
Async(Arc<AsyncMethod>),
Sync(Arc<SyncMethod>),
}
impl Functions {
pub fn new() -> Self {
Self::default()
}
pub fn method<F, Fut, R>(self, name: impl Into<String>, method: F) -> Self
where
F: Fn(FunctionRequest) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<R, FunctionError>> + Send + 'static,
R: Into<FunctionResponse> + 'static,
{
self.insert(
name.into(),
Method::Async(Arc::new(move |request| {
let future = method(request);
Box::pin(async move { future.await.map(Into::into) })
})),
)
}
pub fn sync_method<F, R>(self, name: impl Into<String>, method: F) -> Self
where
F: Fn(FunctionRequest) -> Result<R, FunctionError> + Send + Sync + 'static,
R: Into<FunctionResponse>,
{
self.insert(
name.into(),
Method::Sync(Arc::new(move |request| method(request).map(Into::into))),
)
}
fn insert(mut self, name: String, method: Method) -> Self {
if self.invalid.is_none() && (name == "then" || self.methods.contains_key(&name)) {
self.invalid = Some(name.clone());
}
self.methods.insert(name, method);
self
}
pub(crate) fn validate(&self) -> crate::Result<()> {
match &self.invalid {
Some(name) if name == "then" => Err(Error::Configuration(
"a function binding cannot have a method named then".into(),
)),
Some(name) => Err(Error::Configuration(format!(
"duplicate function method {name}"
))),
None => Ok(()),
}
}
}
#[cfg(any(
feature = "boa",
feature = "quickjs",
feature = "v8",
feature = "fuzzing",
test
))]
impl Functions {
pub(crate) fn get(&self, name: &str) -> Option<&Method> {
self.methods.get(name)
}
pub(crate) fn describe(&self) -> serde_json::Value {
let methods: serde_json::Map<String, serde_json::Value> = self
.methods
.iter()
.map(|(name, method)| {
let kind = match method {
Method::Async(_) => "async",
Method::Sync(_) => "sync",
};
(name.clone(), serde_json::Value::from(kind))
})
.collect();
serde_json::Value::Object(methods)
}
}