async-graphql/derive/src/subscription.rs

402 lines
16 KiB
Rust
Raw Normal View History

2020-10-14 09:08:57 +00:00
use crate::args::{self, RenameRuleExt, RenameTarget, SubscriptionField};
use crate::output_type::OutputType;
2020-09-28 09:44:00 +00:00
use crate::utils::{
generate_default, generate_guards, generate_validator, get_cfg_attrs, get_crate_name,
get_param_getter_ident, get_rustdoc, parse_graphql_attrs, remove_graphql_attrs,
GeneratorResult,
};
2020-03-17 09:26:59 +00:00
use proc_macro::TokenStream;
use quote::quote;
use syn::ext::IdentExt;
use syn::{
Block, Error, FnArg, ImplItem, ItemImpl, Pat, ReturnType, Type, TypeImplTrait, TypeParamBound,
TypeReference,
};
2020-03-17 09:26:59 +00:00
2020-09-28 09:44:00 +00:00
pub fn generate(
subscription_args: &args::Subscription,
item_impl: &mut ItemImpl,
) -> GeneratorResult<TokenStream> {
let crate_name = get_crate_name(subscription_args.internal);
2020-03-17 09:26:59 +00:00
let (self_ty, self_name) = match item_impl.self_ty.as_ref() {
Type::Path(path) => (
path,
path.path
.segments
.last()
.map(|s| s.ident.to_string())
.unwrap(),
),
2020-09-28 09:44:00 +00:00
_ => return Err(Error::new_spanned(&item_impl.self_ty, "Invalid type").into()),
2020-03-17 09:26:59 +00:00
};
let generics = &item_impl.generics;
let where_clause = &generics.where_clause;
2020-03-17 09:26:59 +00:00
2020-09-28 09:44:00 +00:00
let gql_typename = subscription_args
2020-03-17 09:26:59 +00:00
.name
.clone()
2020-10-14 09:08:57 +00:00
.unwrap_or_else(|| RenameTarget::Type.rename(self_name.clone()));
2020-03-19 09:20:12 +00:00
2020-09-28 09:44:00 +00:00
let desc = get_rustdoc(&item_impl.attrs)?
.map(|s| quote! { Some(#s) })
2020-03-17 09:26:59 +00:00
.unwrap_or_else(|| quote! {None});
let mut create_stream = Vec::new();
2020-03-17 09:26:59 +00:00
let mut schema_fields = Vec::new();
for item in &mut item_impl.items {
if let ImplItem::Method(method) = item {
2020-09-28 09:44:00 +00:00
let field: SubscriptionField = parse_graphql_attrs(&method.attrs)?.unwrap_or_default();
if field.skip {
remove_graphql_attrs(&mut method.attrs);
continue;
}
2020-03-17 09:26:59 +00:00
2020-09-28 09:44:00 +00:00
let ident = &method.sig.ident;
2020-10-14 09:08:57 +00:00
let field_name = field.name.clone().unwrap_or_else(|| {
subscription_args
.rename_fields
.rename(method.sig.ident.unraw().to_string(), RenameTarget::Field)
});
2020-09-28 09:44:00 +00:00
let field_desc = get_rustdoc(&method.attrs)?
.map(|s| quote! {Some(#s)})
.unwrap_or_else(|| quote! {None});
let field_deprecation = field
.deprecation
.as_ref()
.map(|s| quote! {Some(#s)})
.unwrap_or_else(|| quote! {None});
let cfg_attrs = get_cfg_attrs(&method.attrs);
if method.sig.asyncness.is_none() {
return Err(Error::new_spanned(
&method,
"The subscription stream function must be asynchronous",
)
.into());
}
2020-03-17 09:26:59 +00:00
2020-09-28 09:44:00 +00:00
let ty = match &method.sig.output {
ReturnType::Type(_, ty) => OutputType::parse(ty)?,
ReturnType::Default => {
return Err(Error::new_spanned(&method.sig.output, "Missing type").into())
2020-03-17 09:26:59 +00:00
}
2020-09-28 09:44:00 +00:00
};
2020-03-17 09:26:59 +00:00
2020-09-28 09:44:00 +00:00
let mut create_ctx = true;
let mut args = Vec::new();
2020-09-28 09:44:00 +00:00
for (idx, arg) in method.sig.inputs.iter_mut().enumerate() {
if let FnArg::Receiver(receiver) = arg {
if idx != 0 {
return Err(Error::new_spanned(
receiver,
"The self receiver must be the first parameter.",
)
.into());
}
} else if let FnArg::Typed(pat) = arg {
if idx == 0 {
return Err(Error::new_spanned(
pat,
"The self receiver must be the first parameter.",
)
.into());
}
2020-03-17 09:26:59 +00:00
2020-09-28 09:44:00 +00:00
match (&*pat.pat, &*pat.ty) {
(Pat::Ident(arg_ident), Type::Path(arg_ty)) => {
args.push((
arg_ident.clone(),
arg_ty.clone(),
parse_graphql_attrs::<args::SubscriptionFieldArgument>(&pat.attrs)?
.unwrap_or_default(),
));
2020-09-28 09:44:00 +00:00
pat.attrs.clear();
}
2020-09-28 09:44:00 +00:00
(arg, Type::Reference(TypeReference { elem, .. })) => {
if let Type::Path(path) = elem.as_ref() {
if idx != 1 || path.path.segments.last().unwrap().ident != "Context"
{
return Err(Error::new_spanned(
arg,
"The Context must be the second argument.",
)
.into());
} else {
create_ctx = false;
}
}
2020-03-17 09:26:59 +00:00
}
2020-09-28 09:44:00 +00:00
_ => {
return Err(Error::new_spanned(arg, "Incorrect argument type").into());
}
2020-03-17 09:26:59 +00:00
}
2020-09-28 09:44:00 +00:00
} else {
return Err(Error::new_spanned(arg, "Incorrect argument type").into());
2020-03-17 09:26:59 +00:00
}
2020-09-28 09:44:00 +00:00
}
2020-03-17 09:26:59 +00:00
2020-09-28 09:44:00 +00:00
if create_ctx {
let arg = syn::parse2::<FnArg>(quote! { _: &#crate_name::Context<'_> }).unwrap();
method.sig.inputs.insert(1, arg);
}
2020-03-17 09:26:59 +00:00
2020-09-28 09:44:00 +00:00
let mut schema_args = Vec::new();
let mut use_params = Vec::new();
let mut get_params = Vec::new();
2020-03-17 09:26:59 +00:00
2020-09-28 09:44:00 +00:00
for (
ident,
ty,
args::SubscriptionFieldArgument {
name,
desc,
default,
default_with,
validator,
},
) in args
{
2020-10-14 09:08:57 +00:00
let name = name.clone().unwrap_or_else(|| {
subscription_args
.rename_args
.rename(ident.ident.unraw().to_string(), RenameTarget::Argument)
});
2020-09-28 09:44:00 +00:00
let desc = desc
.as_ref()
.map(|s| quote! {Some(#s)})
.unwrap_or_else(|| quote! {None});
let default = generate_default(&default, &default_with)?;
2020-03-17 09:26:59 +00:00
2020-09-28 09:44:00 +00:00
let validator = match &validator {
Some(meta) => {
let stream = generate_validator(&crate_name, meta)?;
quote!(Some(#stream))
}
None => quote!(None),
};
2020-09-28 09:44:00 +00:00
let schema_default = default
.as_ref()
.map(|value| {
quote! {Some( <#ty as #crate_name::InputValueType>::to_value(&#value).to_string() )}
})
.unwrap_or_else(|| quote! {None});
2020-05-01 23:57:34 +00:00
2020-09-28 09:44:00 +00:00
schema_args.push(quote! {
args.insert(#name, #crate_name::registry::MetaInputValue {
name: #name,
description: #desc,
ty: <#ty as #crate_name::Type>::create_type_info(registry),
default_value: #schema_default,
validator: #validator,
2020-03-17 09:26:59 +00:00
});
});
2020-09-28 09:44:00 +00:00
use_params.push(quote! { #ident });
let default = match default {
Some(default) => quote! { Some(|| -> #ty { #default }) },
None => quote! { None },
};
2020-09-28 09:44:00 +00:00
let param_getter_name = get_param_getter_ident(&ident.ident.to_string());
get_params.push(quote! {
2020-10-14 09:08:57 +00:00
#[allow(non_snake_case)]
2020-09-30 18:40:17 +00:00
let #param_getter_name = || -> #crate_name::ServerResult<#ty> { ctx.param_value(#name, #default) };
2020-10-14 09:08:57 +00:00
#[allow(non_snake_case)]
2020-09-28 09:44:00 +00:00
let #ident: #ty = ctx.param_value(#name, #default)?;
});
}
2020-09-28 09:44:00 +00:00
let res_ty = ty.value_type();
let stream_ty = if let Type::ImplTrait(TypeImplTrait { bounds, .. }) = &res_ty {
let mut r = None;
for b in bounds {
if let TypeParamBound::Trait(b) = b {
r = Some(quote! { #b });
}
}
quote! { #r }
2020-09-28 09:44:00 +00:00
} else {
quote! { #res_ty }
};
if let OutputType::Value(inner_ty) = &ty {
let block = &method.block;
let new_block = quote!({
{
let value = (move || { async move #block })().await;
Ok(value)
}
2020-05-05 05:02:24 +00:00
});
2020-09-28 09:44:00 +00:00
method.block = syn::parse2::<Block>(new_block).expect("invalid block");
method.sig.output =
2020-09-30 18:40:17 +00:00
syn::parse2::<ReturnType>(quote! { -> #crate_name::Result<#inner_ty> })
2020-09-28 09:44:00 +00:00
.expect("invalid result type");
}
2020-09-28 09:44:00 +00:00
schema_fields.push(quote! {
#(#cfg_attrs)*
fields.insert(#field_name.to_string(), #crate_name::registry::MetaField {
name: #field_name.to_string(),
description: #field_desc,
args: {
let mut args = #crate_name::indexmap::IndexMap::new();
#(#schema_args)*
args
},
ty: <<#stream_ty as #crate_name::futures::stream::Stream>::Item as #crate_name::Type>::create_type_info(registry),
deprecation: #field_deprecation,
cache_control: Default::default(),
external: false,
requires: None,
provides: None,
2020-05-05 05:02:24 +00:00
});
2020-09-28 09:44:00 +00:00
});
let create_field_stream = quote! {
self.#ident(ctx, #(#use_params),*)
.await
.map_err(|err| {
2020-09-30 18:40:17 +00:00
err.into_server_error().at(ctx.item.pos)
2020-09-28 09:44:00 +00:00
})?
};
2020-09-28 09:44:00 +00:00
let guard = match &field.guard {
Some(meta_list) => generate_guards(&crate_name, meta_list)?,
None => None,
};
let guard = guard.map(|guard| quote! {
2020-09-30 18:40:17 +00:00
#guard.check(ctx).await.map_err(|err| err.into_server_error().at(ctx.item.pos))?;
2020-09-28 09:44:00 +00:00
});
2020-09-28 09:44:00 +00:00
let stream_fn = quote! {
#(#get_params)*
#guard
let field_name = ::std::sync::Arc::new(ctx.item.node.response_key().node.clone());
let field = ::std::sync::Arc::new(ctx.item.clone());
let pos = ctx.item.pos;
let schema_env = ctx.schema_env.clone();
let query_env = ctx.query_env.clone();
let stream = #crate_name::futures::StreamExt::then(#create_field_stream, {
let field_name = field_name.clone();
move |msg| {
let schema_env = schema_env.clone();
let query_env = query_env.clone();
let field = field.clone();
let field_name = field_name.clone();
2020-09-28 09:44:00 +00:00
async move {
let resolve_id = #crate_name::ResolveId {
parent: Some(0),
current: 1,
};
let inc_resolve_id = ::std::sync::atomic::AtomicUsize::new(1);
let ctx_selection_set = query_env.create_context(
&schema_env,
Some(#crate_name::QueryPathNode {
parent: None,
segment: #crate_name::QueryPathSegment::Name(&field_name),
}),
&field.node.selection_set,
resolve_id,
&inc_resolve_id,
);
2020-09-29 12:47:37 +00:00
let ctx_extension = #crate_name::extensions::ExtensionContext {
schema_data: &schema_env.data,
query_data: &query_env.ctx_data,
};
2020-10-12 06:49:32 +00:00
query_env.extensions.execution_start(&ctx_extension);
2020-09-28 09:44:00 +00:00
#[allow(bare_trait_objects)]
let ri = #crate_name::extensions::ResolveInfo {
resolve_id,
path_node: ctx_selection_set.path_node.as_ref().unwrap(),
parent_type: #gql_typename,
return_type: &<<#stream_ty as #crate_name::futures::stream::Stream>::Item as #crate_name::Type>::qualified_type_name(),
};
2020-10-12 06:49:32 +00:00
query_env.extensions.resolve_start(&ctx_extension, &ri);
2020-09-28 09:44:00 +00:00
2020-09-30 17:24:24 +00:00
let res = #crate_name::OutputValueType::resolve(&msg, &ctx_selection_set, &*field).await;
2020-09-28 09:44:00 +00:00
2020-10-12 06:49:32 +00:00
query_env.extensions.resolve_end(&ctx_extension, &ri);
query_env.extensions.execution_end(&ctx_extension);
2020-09-30 18:40:17 +00:00
res
}
2020-03-17 09:26:59 +00:00
}
});
2020-09-30 18:40:17 +00:00
#crate_name::ServerResult::Ok(#crate_name::futures::StreamExt::scan(
2020-09-28 09:44:00 +00:00
stream,
false,
|errored, item| {
if *errored {
return #crate_name::futures::future::ready(None);
}
if item.is_err() {
*errored = true;
}
#crate_name::futures::future::ready(Some(item))
},
))
};
2020-03-17 09:26:59 +00:00
2020-09-28 09:44:00 +00:00
create_stream.push(quote! {
#(#cfg_attrs)*
if ctx.item.node.name.node == #field_name {
2020-09-30 17:24:24 +00:00
return ::std::option::Option::Some(::std::boxed::Box::pin(
2020-09-28 09:44:00 +00:00
#crate_name::futures::TryStreamExt::try_flatten(
#crate_name::futures::stream::once((move || async move { #stream_fn })())
)
2020-09-30 17:24:24 +00:00
));
2020-09-28 09:44:00 +00:00
}
});
2020-03-17 09:26:59 +00:00
2020-09-28 09:44:00 +00:00
remove_graphql_attrs(&mut method.attrs);
2020-03-17 09:26:59 +00:00
}
}
let expanded = quote! {
#item_impl
#[allow(clippy::all, clippy::pedantic)]
impl #generics #crate_name::Type for #self_ty #where_clause {
fn type_name() -> ::std::borrow::Cow<'static, str> {
::std::borrow::Cow::Borrowed(#gql_typename)
2020-03-17 09:26:59 +00:00
}
#[allow(bare_trait_objects)]
2020-03-17 09:26:59 +00:00
fn create_type_info(registry: &mut #crate_name::registry::Registry) -> String {
registry.create_type::<Self, _>(|registry| #crate_name::registry::MetaType::Object {
2020-03-19 09:20:12 +00:00
name: #gql_typename.to_string(),
2020-03-17 09:26:59 +00:00
description: #desc,
fields: {
let mut fields = #crate_name::indexmap::IndexMap::new();
2020-03-17 09:26:59 +00:00
#(#schema_fields)*
fields
},
cache_control: ::std::default::Default::default(),
2020-04-09 14:03:09 +00:00
extends: false,
keys: None,
2020-03-17 09:26:59 +00:00
})
}
}
#[allow(clippy::all, clippy::pedantic)]
#[allow(unused_braces, unused_variables)]
impl #crate_name::SubscriptionType for #self_ty #where_clause {
fn create_field_stream<'a>(
&'a self,
ctx: &'a #crate_name::Context<'a>,
2020-10-10 02:32:43 +00:00
) -> ::std::option::Option<::std::pin::Pin<::std::boxed::Box<dyn #crate_name::futures::Stream<Item = #crate_name::ServerResult<#crate_name::Value>> + Send + 'a>>> {
#(#create_stream)*
Rework errors This completely overhauls the error system used in async-graphql. - `Error` has been renamed to `ServerError` and `FieldError` has been renamed to just `Error`. This is because `FieldError` is by far the most common error that users will have to use so it makes sense to use the most obvious error name. Also, the current name didn't make sense as it was used for things other than field errors, such as the data callback for websockets. - `ServerError` has been made completely opaque. Before it was an enum of all the possible errors, but now it just contains an error message, the locations, the path and extensions. It is a shame that we lose information, it makes more sense as _conceptually_ GraphQL does not provide that information. It also frees us to change the internals of async-graphql a lot more. - The path of errors is no longer an opaque JSON value but a regular type, `Vec<PathSegment>`. The type duplication of `PathSegment` and `QueryPathSegment` is unfortunate, I plan to work on this in the future. - Now that `ServerError` is opaque, `RuleError` has been removed from the public API, making it simpler. - Additionally `QueryError` has been completely removed. Instead the error messages are constructed ad-hoc; I took care to never repeat an error message. - Instead of constructing field-not-found errors inside the implementations of field resolvers they now return `Option`s, where a `None` value is representative of the field not being found. - As an unfortunate consequence of the last change, self-referential types based on the output of a subscription resolver can no longer be created. This does not mean anything for users, but causes lifetime issues in the implementation of merged objects. I fixed it with a bit of a hack, but this'll have to be looked into further. - `InputValueError` now has a generic parameter - it's kind of weird but it's necessary for ergonomics. It also improves error messages. - The `ErrorExtensions` trait has been removed. I didn't think the `extend` method was necessary since `From` impls exist. But the ergonomics are still there with a new trait `ExtendError`, which is implemented for both errors and results. - `Response` now supports serializing multiple errors. This allows for nice things like having multiple validation errors not be awkwardly shoved into a single error. - When an error occurs in execution, data is sent as `null`. This is slightly more compliant with the spec but the algorithm described in <https://spec.graphql.org/June2018/#sec-Errors-and-Non-Nullability> has yet to be implemented.
2020-09-29 19:06:44 +00:00
None
2020-03-17 09:26:59 +00:00
}
}
};
Ok(expanded.into())
}