use crate::client::{ApplicationError, Error, MutateRequest, Mutator, Transaction};
use crate::ivm::ViewValue;
use crate::json::{self, Value};
use crate::query::{AnyQuery, ZeroQuery};
use crate::typed::{Query, QueryValue, TypedQuery, ZeroValueError};
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::borrow::Cow;
use std::sync::Arc;
fn encode_args<A: Serialize>(args: &A) -> Option<Value> {
let value = json::to_value(args).expect("arguments must encode as JSON");
(size_of::<A>() != 0 || !value.is_null()).then_some(value)
}
fn decode_args<A: DeserializeOwned>(args: Option<&Value>) -> Result<A, String> {
json::from_value(args.unwrap_or(&Value::Null)).map_err(|e| e.to_string())
}
pub struct QueryDefinition<A, C, R, T = Vec<R>> {
pub name: &'static str,
body: fn(&A, &C) -> Query<R, T>,
}
impl<A, C, R, T> Clone for QueryDefinition<A, C, R, T> {
fn clone(&self) -> Self {
*self
}
}
impl<A, C, R, T> Copy for QueryDefinition<A, C, R, T> {}
pub const fn define_query<A, C, R, T>(
name: &'static str,
body: fn(&A, &C) -> Query<R, T>,
) -> QueryDefinition<A, C, R, T> {
QueryDefinition { name, body }
}
impl<A, C, R, T> QueryDefinition<A, C, R, T>
where
A: Serialize + Send + Sync + 'static,
C: 'static,
R: 'static,
T: 'static,
{
pub fn with(&self, args: A) -> QueryRequest<C, R, T> {
let encoded = encode_args(&args).into_iter().collect();
let body = self.body;
QueryRequest {
name: self.name,
args: encoded,
build: Arc::new(move |context| body(&args, context)),
}
}
}
type BuildQuery<C, R, T> = Arc<dyn Fn(&C) -> Query<R, T> + Send + Sync>;
pub struct QueryRequest<C, R, T = Vec<R>> {
name: &'static str,
args: Vec<Value>,
build: BuildQuery<C, R, T>,
}
impl<C, R, T> Clone for QueryRequest<C, R, T> {
fn clone(&self) -> Self {
QueryRequest {
name: self.name,
args: self.args.clone(),
build: self.build.clone(),
}
}
}
impl<C, R, T> QueryRequest<C, R, T> {
pub fn name(&self) -> &'static str {
self.name
}
pub fn args(&self) -> &[Value] {
&self.args
}
pub fn query(&self, context: &C) -> Query<R, T> {
let any = (self.build)(context).into_any();
Query::from_any(any.name_and_args(self.name, self.args.clone()))
}
}
impl<C, R, T: QueryValue> QueryRequest<C, R, T> {
pub fn read(&self, view: &ViewValue) -> Result<T, ZeroValueError> {
T::from_view(view)
}
}
impl<C, R, T> ZeroQuery<C> for QueryRequest<C, R, T> {
fn any_query(&self, context: &C) -> Cow<'_, AnyQuery> {
Cow::Owned(self.query(context).into_any())
}
}
impl<C, R, T: QueryValue> TypedQuery<C> for QueryRequest<C, R, T> {
type Value = T;
}
pub trait NamedQuery<C> {
fn name(&self) -> &'static str;
fn query_from_json(
&self,
args: &[Value],
context: &C,
) -> Result<(AnyQuery, Vec<Value>), String>;
}
impl<A, C, R, T> NamedQuery<C> for QueryDefinition<A, C, R, T>
where
A: Serialize + DeserializeOwned + Send + Sync + 'static,
C: 'static,
R: 'static,
T: 'static,
{
fn name(&self) -> &'static str {
self.name
}
fn query_from_json(
&self,
args: &[Value],
context: &C,
) -> Result<(AnyQuery, Vec<Value>), String> {
let decoded: A = match args {
[] => decode_args(None)?,
[a] => decode_args(Some(a))?,
_ => return Err(format!("expected at most one argument, got {}", args.len())),
};
let request = self.with(decoded);
Ok((request.query(context).into_any(), request.args))
}
}
type MutatorBody<A, C, O> = fn(&Transaction, A, &C) -> Result<O, Error>;
pub struct MutatorDefinition<A, C, O = ()> {
pub name: &'static str,
body: MutatorBody<A, C, O>,
}
impl<A, C, O> Clone for MutatorDefinition<A, C, O> {
fn clone(&self) -> Self {
*self
}
}
impl<A, C, O> Copy for MutatorDefinition<A, C, O> {}
pub const fn define_mutator<A, C, O>(
name: &'static str,
body: MutatorBody<A, C, O>,
) -> MutatorDefinition<A, C, O> {
MutatorDefinition { name, body }
}
impl<A, C, O> MutatorDefinition<A, C, O>
where
A: Serialize + DeserializeOwned + 'static,
C: 'static,
O: Serialize + 'static,
{
pub fn with(&self, args: A) -> MutateRequest {
MutateRequest::new(self.name, encode_args(&args))
}
pub fn mutator(&self) -> Mutator<C> {
let body = self.body;
Mutator::new(self.name, move |tx, args, context: &C| {
let args: A = decode_args(args).map_err(ApplicationError::new)?;
Ok(encode_args(&body(tx, args, context)?))
})
}
pub fn reencode(&self, args: Option<&Value>) -> Result<Option<Value>, String> {
Ok(encode_args(&decode_args::<A>(args)?))
}
}
pub trait NamedMutator<C> {
fn name(&self) -> &'static str;
fn mutator(&self) -> Mutator<C>;
fn reencode(&self, args: Option<&Value>) -> Result<Option<Value>, String>;
}
impl<A, C, O> NamedMutator<C> for MutatorDefinition<A, C, O>
where
A: Serialize + DeserializeOwned + 'static,
C: 'static,
O: Serialize + 'static,
{
fn name(&self) -> &'static str {
self.name
}
fn mutator(&self) -> Mutator<C> {
MutatorDefinition::mutator(self)
}
fn reencode(&self, args: Option<&Value>) -> Result<Option<Value>, String> {
MutatorDefinition::reencode(self, args)
}
}