Merge pull request #438 from tyranron/remove-async-closure-feature

* Upgrade futures-preview, tokio crates and remove unnecessary 'async_await' feature

* Remove async_closure feature usage

* Fix type inferring for trivial resolver code

Additionally:
- fix inconsistencies after merge with master
This commit is contained in:
Christian Legnitto 2019-10-10 07:22:52 -07:00 committed by GitHub
commit c903d5e004
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 91 additions and 221 deletions

View file

@ -2,8 +2,6 @@
//! This example demonstrates async/await usage with warp. //! This example demonstrates async/await usage with warp.
//! NOTE: this uses tokio 0.1 , not the alpha tokio 0.2. //! NOTE: this uses tokio 0.1 , not the alpha tokio 0.2.
#![feature(async_closure)]
use juniper::{EmptyMutation, RootNode, FieldError}; use juniper::{EmptyMutation, RootNode, FieldError};
use warp::{http::Response, Filter}; use warp::{http::Response, Filter};

View file

@ -1,5 +1,3 @@
#![feature(async_closure)]
use juniper::{graphql_value, RootNode, Value}; use juniper::{graphql_value, RootNode, Value};
#[derive(juniper::GraphQLEnum)] #[derive(juniper::GraphQLEnum)]

View file

@ -828,121 +828,10 @@ where
None => return Err(GraphQLError::UnknownOperationName), None => return Err(GraphQLError::UnknownOperationName),
}; };
let default_variable_values = op.item.variable_definitions.map(|defs| { if op.item.operation_type == OperationType::Subscription {
defs.item return Err(GraphQLError::IsSubscription);
.items
.iter()
.filter_map(|&(ref name, ref def)| {
def.default_value
.as_ref()
.map(|i| (name.item.to_owned(), i.item.clone()))
})
.collect::<HashMap<String, InputValue<S>>>()
});
let errors = RwLock::new(Vec::new());
let value;
{
let mut all_vars;
let mut final_vars = variables;
if let Some(defaults) = default_variable_values {
all_vars = variables.clone();
for (name, value) in defaults {
all_vars.entry(name).or_insert(value);
} }
final_vars = &all_vars;
}
let root_type = match op.item.operation_type {
OperationType::Query => root_node.schema.query_type(),
OperationType::Mutation => root_node
.schema
.mutation_type()
.expect("No mutation type found"),
};
let executor = Executor {
fragments: &fragments
.iter()
.map(|f| (f.item.name.item, &f.item))
.collect(),
variables: final_vars,
current_selection_set: Some(&op.item.selection_set[..]),
parent_selection_set: None,
current_type: root_type,
schema: &root_node.schema,
context,
errors: &errors,
field_path: FieldPath::Root(op.start),
};
value = match op.item.operation_type {
OperationType::Query => {
executor
.resolve_into_value_async(&root_node.query_info, &root_node)
.await
}
OperationType::Mutation => {
executor
.resolve_into_value_async(&root_node.mutation_info, &root_node.mutation_type)
.await
}
};
}
let mut errors = errors.into_inner().unwrap();
errors.sort();
Ok((value, errors))
}
#[cfg(feature = "async")]
pub async fn execute_validated_query_async<'a, QueryT, MutationT, CtxT, S>(
document: Document<'a, S>,
operation_name: Option<&str>,
root_node: &RootNode<'a, QueryT, MutationT, S>,
variables: &Variables<S>,
context: &CtxT,
) -> Result<(Value<S>, Vec<ExecutionError<S>>), GraphQLError<'a>>
where
S: ScalarValue + Send + Sync,
QueryT: crate::GraphQLTypeAsync<S, Context = CtxT> + Send + Sync,
QueryT::TypeInfo: Send + Sync,
MutationT: crate::GraphQLTypeAsync<S, Context = CtxT> + Send + Sync,
MutationT::TypeInfo: Send + Sync,
CtxT: Send + Sync,
for<'b> &'b S: ScalarRefValue<'b>,
{
let mut fragments = vec![];
let mut operation = None;
for def in document {
match def {
Definition::Operation(op) => {
if operation_name.is_none() && operation.is_some() {
return Err(GraphQLError::MultipleOperationsProvided);
}
let move_op = operation_name.is_none()
|| op.item.name.as_ref().map(|s| s.item) == operation_name;
if move_op {
operation = Some(op);
}
}
Definition::Fragment(f) => fragments.push(f),
};
}
let op = match operation {
Some(op) => op,
None => return Err(GraphQLError::UnknownOperationName),
};
let default_variable_values = op.item.variable_definitions.map(|defs| { let default_variable_values = op.item.variable_definitions.map(|defs| {
defs.item defs.item
.items .items
@ -978,6 +867,7 @@ where
.schema .schema
.mutation_type() .mutation_type()
.expect("No mutation type found"), .expect("No mutation type found"),
OperationType::Subscription => unreachable!(),
}; };
let executor = Executor { let executor = Executor {
@ -1006,6 +896,7 @@ where
.resolve_into_value_async(&root_node.mutation_info, &root_node.mutation_type) .resolve_into_value_async(&root_node.mutation_info, &root_node.mutation_type)
.await .await
} }
OperationType::Subscription => unreachable!(),
}; };
} }

View file

@ -90,7 +90,6 @@ Juniper has not reached 1.0 yet, thus some API instability should be expected.
*/ */
#![doc(html_root_url = "https://docs.rs/juniper/0.14.0")] #![doc(html_root_url = "https://docs.rs/juniper/0.14.0")]
#![warn(missing_docs)] #![warn(missing_docs)]
#![cfg_attr(feature = "async", feature(async_closure))]
#[doc(hidden)] #[doc(hidden)]
pub extern crate serde; pub extern crate serde;

View file

@ -1,5 +1,3 @@
#![feature(async_closure)]
use juniper::{ use juniper::{
object, DefaultScalarValue, ExecutionError, FieldError, GraphQLEnum, Value, Variables, object, DefaultScalarValue, ExecutionError, FieldError, GraphQLEnum, Value, Variables,
}; };

View file

@ -59,7 +59,8 @@ pub fn build_derive_object(ast: syn::DeriveInput, is_internal: bool) -> TokenStr
description: field_attrs.description, description: field_attrs.description,
deprecation: field_attrs.deprecation, deprecation: field_attrs.deprecation,
resolver_code, resolver_code,
resolver_code_async: None, is_type_inferred: true,
is_async: false,
}) })
} }
}); });

View file

@ -197,29 +197,10 @@ pub fn build_object(args: TokenStream, body: TokenStream, is_internal: bool) ->
} }
let body = &method.block; let body = &method.block;
let return_ty = &method.sig.output; let resolver_code = quote!(
let (resolver_code, resolver_code_async) = if is_async {
(
quote!(),
Some(quote!(
(async move || #return_ty {
#( #resolve_parts )* #( #resolve_parts )*
#body #body
})() );
)),
)
} else {
(
quote!(
(|| #return_ty {
#( #resolve_parts )*
#body
})()
),
None,
)
};
let ident = &method.sig.ident; let ident = &method.sig.ident;
let name = attrs let name = attrs
@ -233,7 +214,8 @@ pub fn build_object(args: TokenStream, body: TokenStream, is_internal: bool) ->
description: attrs.description, description: attrs.description,
deprecation: attrs.deprecation, deprecation: attrs.deprecation,
resolver_code, resolver_code,
resolver_code_async, is_type_inferred: false,
is_async,
}); });
} }
_ => { _ => {

View file

@ -597,14 +597,8 @@ pub struct GraphQLTypeDefinitionField {
pub deprecation: Option<DeprecationAttr>, pub deprecation: Option<DeprecationAttr>,
pub args: Vec<GraphQLTypeDefinitionFieldArg>, pub args: Vec<GraphQLTypeDefinitionFieldArg>,
pub resolver_code: proc_macro2::TokenStream, pub resolver_code: proc_macro2::TokenStream,
pub resolver_code_async: Option<proc_macro2::TokenStream>, pub is_type_inferred: bool,
} pub is_async: bool,
impl GraphQLTypeDefinitionField {
#[inline]
fn is_async(&self) -> bool {
self.resolver_code_async.is_some()
}
} }
/// Definition of a graphql type based on information extracted /// Definition of a graphql type based on information extracted
@ -638,7 +632,7 @@ pub struct GraphQLTypeDefiniton {
impl GraphQLTypeDefiniton { impl GraphQLTypeDefiniton {
fn has_async_field(&self) -> bool { fn has_async_field(&self) -> bool {
self.fields.iter().any(|field| field.is_async()) self.fields.iter().any(|field| field.is_async)
} }
pub fn into_tokens(self, juniper_crate_name: &str) -> proc_macro2::TokenStream { pub fn into_tokens(self, juniper_crate_name: &str) -> proc_macro2::TokenStream {
@ -711,7 +705,7 @@ impl GraphQLTypeDefiniton {
let name = &field.name; let name = &field.name;
let code = &field.resolver_code; let code = &field.resolver_code;
if field.is_async() { if field.is_async {
// TODO: better error message with field/type name. // TODO: better error message with field/type name.
quote!( quote!(
#name => { #name => {
@ -719,9 +713,15 @@ impl GraphQLTypeDefiniton {
}, },
) )
} else { } else {
let _type = if field.is_type_inferred {
quote!()
} else {
let _type = &field._type;
quote!(: #_type)
};
quote!( quote!(
#name => { #name => {
let res = { #code }; let res #_type = { #code };
#juniper_crate_name::IntoResolvable::into( #juniper_crate_name::IntoResolvable::into(
res, res,
executor.context() executor.context()
@ -811,12 +811,19 @@ impl GraphQLTypeDefiniton {
let resolve_field_async = { let resolve_field_async = {
let resolve_matches_async = self.fields.iter().map(|field| { let resolve_matches_async = self.fields.iter().map(|field| {
let name = &field.name; let name = &field.name;
let code = &field.resolver_code;
let _type = if field.is_type_inferred {
quote!()
} else {
let _type = &field._type;
quote!(: #_type)
};
if let Some(code) = field.resolver_code_async.as_ref() { if field.is_async {
quote!( quote!(
#name => { #name => {
let f = async move { let f = async move {
let res = { #code }.await; let res #_type = async move { #code }.await;
let inner_res = #juniper_crate_name::IntoResolvable::into( let inner_res = #juniper_crate_name::IntoResolvable::into(
res, res,
@ -837,8 +844,6 @@ impl GraphQLTypeDefiniton {
}, },
) )
} else { } else {
let code = &field.resolver_code;
let inner = if !self.no_async { let inner = if !self.no_async {
quote!( quote!(
let f = async move { let f = async move {
@ -866,7 +871,7 @@ impl GraphQLTypeDefiniton {
quote!( quote!(
#name => { #name => {
let res = { #code }; let res #_type = { #code };
let res2 = #juniper_crate_name::IntoResolvable::into( let res2 = #juniper_crate_name::IntoResolvable::into(
res, res,
executor.context() executor.context()
@ -877,7 +882,7 @@ impl GraphQLTypeDefiniton {
} }
}); });
let mut where_async = where_clause.cloned().unwrap_or_else(|| parse_quote!(where));; let mut where_async = where_clause.cloned().unwrap_or_else(|| parse_quote!(where));
where_async where_async
.predicates .predicates

View file

@ -38,7 +38,6 @@ Check the LICENSE file for details.
#![doc(html_root_url = "https://docs.rs/juniper_rocket/0.2.0")] #![doc(html_root_url = "https://docs.rs/juniper_rocket/0.2.0")]
#![feature(decl_macro, proc_macro_hygiene)] #![feature(decl_macro, proc_macro_hygiene)]
#![cfg_attr(feature = "async", feature(async_closure))]
use std::{error::Error, io::Cursor}; use std::{error::Error, io::Cursor};

View file

@ -39,7 +39,6 @@ Check the LICENSE file for details.
#![deny(missing_docs)] #![deny(missing_docs)]
#![deny(warnings)] #![deny(warnings)]
#![doc(html_root_url = "https://docs.rs/juniper_warp/0.2.0")] #![doc(html_root_url = "https://docs.rs/juniper_warp/0.2.0")]
#![cfg_attr(feature = "async", feature(async_closure))]
use futures::{future::poll_fn, Future}; use futures::{future::poll_fn, Future};
use serde::Deserialize; use serde::Deserialize;