Skip to content

Commit

Permalink
refactor: converted return error type from anyhow to CLIError
Browse files Browse the repository at this point in the history
  • Loading branch information
mehulmathur001 committed Apr 11, 2024
1 parent fa44f7d commit 5717727
Show file tree
Hide file tree
Showing 13 changed files with 41 additions and 23 deletions.
11 changes: 11 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use colored::Colorize;
use derive_setters::Setters;
use thiserror::Error;

use crate::lambda::EvaluationError;
use crate::valid::ValidationError;

/// A versatile error container that's optimized for CLI and Web.
Expand Down Expand Up @@ -149,6 +150,16 @@ impl From<hyper::Error> for Error {
}
}

impl From<EvaluationError> for Error {
// TODO: implement EvaluationError conversion to Error
// Below is some test code
fn from(error: EvaluationError) -> Self {
let cli_error = Error::new("Server Failed");
let message = error.to_string();
cli_error.description(message)
}
}

impl From<anyhow::Error> for Error {
fn from(error: anyhow::Error) -> Self {
// Convert other errors to CLIError
Expand Down
3 changes: 2 additions & 1 deletion src/http/request_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use crate::async_cache::AsyncCache;
use crate::auth::context::AuthContext;
use crate::blueprint::{Server, Upstream};
use crate::data_loader::DataLoader;
use crate::error::Error;
use crate::graphql::GraphqlDataLoader;
use crate::grpc;
use crate::grpc::data_loader::GrpcDataLoader;
Expand All @@ -33,7 +34,7 @@ pub struct RequestContext {
pub min_max_age: Arc<Mutex<Option<i32>>>,
pub cache_public: Arc<Mutex<Option<bool>>>,
pub runtime: TargetRuntime,
pub cache: AsyncCache<u64, ConstValue, String>,
pub cache: AsyncCache<u64, ConstValue, Error>,
}

impl RequestContext {
Expand Down
3 changes: 2 additions & 1 deletion src/lambda/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use anyhow::Result;
use async_graphql_value::ConstValue;

use super::{Concurrent, Eval, EvaluationContext, Expression, ResolverContextLike};
use crate::error::Error;

pub trait CacheKey<Ctx> {
fn cache_key(&self, ctx: &Ctx) -> u64;
Expand Down Expand Up @@ -39,7 +40,7 @@ impl Eval for Cache {
&'a self,
ctx: EvaluationContext<'a, Ctx>,
conc: &'a Concurrent,
) -> Pin<Box<dyn Future<Output = Result<ConstValue>> + 'a + Send>> {
) -> Pin<Box<dyn Future<Output = Result<ConstValue, Error>> + 'a + Send>> {
Box::pin(async move {
if let Expression::IO(io) = self.expr.deref() {
let key = io.cache_key(&ctx);
Expand Down
4 changes: 3 additions & 1 deletion src/lambda/concurrent.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use futures_util::stream::FuturesUnordered;
use futures_util::{Future, StreamExt};

use crate::error::Error;

///
/// Concurrent controls the concurrency of a fold or foreach operation on lists.
/// It's a flag that is set based on operators that are applied on a list.
Expand Down Expand Up @@ -48,7 +50,7 @@ impl Concurrent {
f: impl Fn(A) -> B,
) -> anyhow::Result<Vec<B>>
where
F: Future<Output = anyhow::Result<A>>,
F: Future<Output = anyhow::Result<A, Error>>,
{
self.fold(iter, vec![], |mut acc, val| {
acc.push(f(val?));
Expand Down
3 changes: 2 additions & 1 deletion src/lambda/eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::pin::Pin;
use anyhow::Result;

use super::{Concurrent, EvaluationContext, ResolverContextLike};
use crate::error::Error;

pub trait Eval<Output = async_graphql::Value>
where
Expand All @@ -13,7 +14,7 @@ where
&'a self,
ctx: EvaluationContext<'a, Ctx>,
conc: &'a Concurrent,
) -> Pin<Box<dyn Future<Output = Result<Output>> + 'a + Send>>
) -> Pin<Box<dyn Future<Output = Result<Output, Error>> + 'a + Send>>
where
Output: 'a;
}
2 changes: 1 addition & 1 deletion src/lambda/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ impl Eval for Expression {
&'a self,
ctx: EvaluationContext<'a, Ctx>,
conc: &'a Concurrent,
) -> Pin<Box<dyn Future<Output = Result<ConstValue>> + 'a + Send>> {
) -> Pin<Box<dyn Future<Output = Result<ConstValue, Error>> + 'a + Send>> {
Box::pin(async move {
match self {
Expression::Context(op) => match op {
Expand Down
10 changes: 3 additions & 7 deletions src/lambda/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,20 +50,16 @@ impl Eval for IO {
&'a self,
ctx: super::EvaluationContext<'a, Ctx>,
_conc: &'a super::Concurrent,
) -> Pin<Box<dyn Future<Output = Result<ConstValue>> + 'a + Send>> {
) -> Pin<Box<dyn Future<Output = Result<ConstValue, Error>> + 'a + Send>> {
let key = self.cache_key(&ctx);
Box::pin(async move {
ctx.request_ctx
.cache
.get_or_eval(key, move || {
Box::pin(async {
self.eval_inner(ctx, _conc)
.await
.map_err(|err| err.to_string())
})
Box::pin(async { self.eval_inner(ctx, _conc).await.map_err(|err| err.into()) })
})
.await
.map_err(|err| anyhow::anyhow!(err))
.map_err(|err: Error| err)
})
}
}
Expand Down
7 changes: 4 additions & 3 deletions src/lambda/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use futures_util::future::join_all;
use super::{
Concurrent, Eval, EvaluationContext, EvaluationError, Expression, ResolverContextLike,
};
use crate::error::Error;

#[derive(Clone, Debug, strum_macros::Display)]
pub enum List {
Expand All @@ -19,7 +20,7 @@ impl Eval for List {
&'a self,
ctx: EvaluationContext<'a, Ctx>,
conc: &'a Concurrent,
) -> Pin<Box<dyn Future<Output = Result<ConstValue>> + 'a + Send>> {
) -> Pin<Box<dyn Future<Output = Result<ConstValue, Error>> + 'a + Send>> {
Box::pin(async move {
match self {
List::Concat(list) => {
Expand Down Expand Up @@ -52,7 +53,7 @@ where
&'a self,
ctx: EvaluationContext<'a, Ctx>,
conc: &'a Concurrent,
) -> Pin<Box<dyn Future<Output = Result<C>> + 'a + Send>> {
) -> Pin<Box<dyn Future<Output = Result<C, Error>> + 'a + Send>> {
Box::pin(async move {
let future_iter = self
.as_ref()
Expand All @@ -62,7 +63,7 @@ where
Concurrent::Parallel => join_all(future_iter)
.await
.into_iter()
.collect::<Result<C>>(),
.collect::<Result<C, Error>>(),
Concurrent::Sequential => {
let mut results = Vec::with_capacity(self.as_ref().len());
for future in future_iter {
Expand Down
3 changes: 2 additions & 1 deletion src/lambda/logic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use anyhow::Result;
use async_graphql_value::ConstValue;

use super::{Concurrent, Eval, EvaluationContext, Expression, ResolverContextLike};
use crate::error::Error;

#[derive(Clone, Debug, strum_macros::Display)]
pub enum Logic {
Expand All @@ -26,7 +27,7 @@ impl Eval for Logic {
&'a self,
ctx: EvaluationContext<'a, Ctx>,
conc: &'a Concurrent,
) -> Pin<Box<dyn Future<Output = Result<ConstValue>> + 'a + Send>> {
) -> Pin<Box<dyn Future<Output = Result<ConstValue, Error>> + 'a + Send>> {
Box::pin(async move {
Ok(match self {
Logic::Or(list) => {
Expand Down
3 changes: 2 additions & 1 deletion src/lambda/math.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use async_graphql_value::ConstValue;
use super::{
Concurrent, Eval, EvaluationContext, EvaluationError, Expression, ResolverContextLike,
};
use crate::error::Error;
use crate::json::JsonLike;

#[derive(Clone, Debug, strum_macros::Display)]
Expand All @@ -29,7 +30,7 @@ impl Eval for Math {
&'a self,
ctx: EvaluationContext<'a, Ctx>,
conc: &'a Concurrent,
) -> Pin<Box<dyn Future<Output = Result<ConstValue>> + 'a + Send>> {
) -> Pin<Box<dyn Future<Output = Result<ConstValue, Error>> + 'a + Send>> {
Box::pin(async move {
Ok(match self {
Math::Mod(lhs, rhs) => {
Expand Down
3 changes: 2 additions & 1 deletion src/lambda/relation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use super::{
Concurrent, Eval, EvaluationContext, EvaluationError, Expression, ResolverContextLike,
};
use crate::helpers::value::HashableConstValue;
use crate::error::Error;

#[derive(Clone, Debug, strum_macros::Display)]
pub enum Relation {
Expand All @@ -35,7 +36,7 @@ impl Eval for Relation {
&'a self,
ctx: EvaluationContext<'a, Ctx>,
conc: &'a Concurrent,
) -> Pin<Box<dyn Future<Output = Result<ConstValue>> + 'a + Send>> {
) -> Pin<Box<dyn Future<Output = Result<ConstValue, Error>> + 'a + Send>> {
Box::pin(async move {
Ok(match self {
Relation::Intersection(exprs) => {
Expand Down
9 changes: 5 additions & 4 deletions src/serde_value_ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@ use async_graphql::{Name, Value as GraphQLValue};
use indexmap::IndexMap;

use crate::blueprint::DynamicValue;
use crate::error::Error;
use crate::path::PathString;

pub trait ValueExt {
fn render_value(&self, ctx: &impl PathString) -> Result<GraphQLValue>;
fn render_value(&self, ctx: &impl PathString) -> Result<GraphQLValue, Error>;
}

impl ValueExt for DynamicValue {
fn render_value<'a>(&self, ctx: &'a impl PathString) -> Result<GraphQLValue> {
fn render_value<'a>(&self, ctx: &'a impl PathString) -> Result<GraphQLValue, Error> {
match self {
DynamicValue::Value(value) => Ok(value.to_owned()),
DynamicValue::Mustache(m) => {
Expand All @@ -25,7 +26,7 @@ impl ValueExt for DynamicValue {
.or_else(|_| Ok(GraphQLValue::String(rendered.into_owned())))
}
DynamicValue::Object(obj) => {
let out: Result<IndexMap<_, _>> = obj
let out: Result<IndexMap<_, _>, Error> = obj
.iter()
.map(|(k, v)| {
let key = Cow::Borrowed(k.as_str());
Expand All @@ -35,7 +36,7 @@ impl ValueExt for DynamicValue {
out.map(GraphQLValue::Object)
}
DynamicValue::Array(arr) => {
let out: Result<Vec<_>> = arr.iter().map(|v| v.render_value(ctx)).collect();
let out: Result<Vec<_>, Error> = arr.iter().map(|v| v.render_value(ctx)).collect();
out.map(GraphQLValue::List)
}
}
Expand Down
3 changes: 2 additions & 1 deletion tests/expression_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ use async_graphql::Value;
use pretty_assertions::assert_eq;
use serde_json::json;
use tailcall::blueprint::{Blueprint, DynamicValue};
use tailcall::error::Error;
use tailcall::http::RequestContext;
use tailcall::lambda::{Concurrent, EmptyResolverContext, Eval, EvaluationContext, Expression};
use tailcall::mustache::Mustache;

async fn eval(expr: &Expression) -> anyhow::Result<Value> {
async fn eval(expr: &Expression) -> anyhow::Result<Value, Error> {
let runtime = tailcall::cli::runtime::init(&Blueprint::default());
let req_ctx = RequestContext::new(runtime);
let res_ctx = EmptyResolverContext {};
Expand Down

0 comments on commit 5717727

Please sign in to comment.