async-graphql/src/schema.rs

870 lines
29 KiB
Rust
Raw Normal View History

use std::{
any::Any,
collections::{HashMap, HashSet},
ops::Deref,
sync::Arc,
};
2020-10-15 06:38:10 +00:00
2020-10-16 06:49:22 +00:00
use futures_util::stream::{self, Stream, StreamExt};
2020-10-15 06:38:10 +00:00
use indexmap::map::IndexMap;
2022-04-13 03:00:24 +00:00
use crate::{
context::{Data, QueryEnvInner},
2022-04-19 04:25:11 +00:00
custom_directive::CustomDirectiveFactory,
extensions::{ExtensionFactory, Extensions},
model::__DirectiveLocation,
parser::{
parse_query,
types::{
Directive, DocumentOperations, ExecutableDocument, OperationType, Selection,
SelectionSet,
},
2022-04-19 04:25:11 +00:00
Positioned,
},
registry::{MetaDirective, MetaInputValue, Registry, SDLExportOptions},
2022-04-19 04:25:11 +00:00
resolver_utils::{resolve_container, resolve_container_serial},
subscription::collect_subscription_streams,
types::QueryRoot,
validation::{check_rules, ValidationMode},
BatchRequest, BatchResponse, CacheControl, ContextBase, EmptyMutation, EmptySubscription,
InputType, ObjectType, OutputType, QueryEnv, Request, Response, ServerError, ServerResult,
SubscriptionType, Variables, ID,
2020-03-29 12:02:52 +00:00
};
2020-03-01 10:54:34 +00:00
2022-04-13 03:00:24 +00:00
/// Introspection mode
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum IntrospectionMode {
2022-05-27 03:31:10 +00:00
/// Introspection only
2022-04-13 03:00:24 +00:00
IntrospectionOnly,
2022-05-27 03:31:10 +00:00
/// Enables introspection
2022-04-13 03:00:24 +00:00
Enabled,
2022-05-27 03:31:10 +00:00
/// Disables introspection
2022-04-13 03:00:24 +00:00
Disabled,
}
impl Default for IntrospectionMode {
fn default() -> Self {
IntrospectionMode::Enabled
}
}
2020-03-29 12:02:52 +00:00
/// Schema builder
pub struct SchemaBuilder<Query, Mutation, Subscription> {
validation_mode: ValidationMode,
query: QueryRoot<Query>,
mutation: Mutation,
subscription: Subscription,
registry: Registry,
data: Data,
complexity: Option<usize>,
depth: Option<usize>,
recursive_depth: usize,
2020-09-29 12:47:37 +00:00
extensions: Vec<Box<dyn ExtensionFactory>>,
2021-11-19 10:49:37 +00:00
custom_directives: HashMap<&'static str, Box<dyn CustomDirectiveFactory>>,
}
2020-03-29 12:02:52 +00:00
2020-10-15 11:36:54 +00:00
impl<Query, Mutation, Subscription> SchemaBuilder<Query, Mutation, Subscription> {
/// Manually register a input type in the schema.
2020-09-06 05:38:31 +00:00
///
2022-04-19 04:25:11 +00:00
/// You can use this function to register schema types that are not directly
/// referenced.
#[must_use]
pub fn register_input_type<T: InputType>(mut self) -> Self {
T::create_type_info(&mut self.registry);
self
}
/// Manually register a output type in the schema.
///
2022-04-19 04:25:11 +00:00
/// You can use this function to register schema types that are not directly
/// referenced.
#[must_use]
pub fn register_output_type<T: OutputType>(mut self) -> Self {
T::create_type_info(&mut self.registry);
self
}
2020-09-06 05:38:31 +00:00
/// Disable introspection queries.
#[must_use]
2020-03-29 12:02:52 +00:00
pub fn disable_introspection(mut self) -> Self {
2022-04-13 03:00:24 +00:00
self.registry.introspection_mode = IntrospectionMode::Disabled;
self
}
2022-04-19 04:25:11 +00:00
/// Only process introspection queries, everything else is processed as an
/// error.
2022-04-13 03:00:24 +00:00
#[must_use]
pub fn introspection_only(mut self) -> Self {
self.registry.introspection_mode = IntrospectionMode::IntrospectionOnly;
2020-03-29 12:02:52 +00:00
self
}
2022-04-19 04:25:11 +00:00
/// Set the maximum complexity a query can have. By default, there is no
/// limit.
#[must_use]
2020-03-29 12:02:52 +00:00
pub fn limit_complexity(mut self, complexity: usize) -> Self {
self.complexity = Some(complexity);
2020-03-29 12:02:52 +00:00
self
}
2020-12-20 13:15:56 +00:00
/// Set the maximum depth a query can have. By default, there is no limit.
#[must_use]
2020-03-29 12:02:52 +00:00
pub fn limit_depth(mut self, depth: usize) -> Self {
self.depth = Some(depth);
2020-03-29 12:02:52 +00:00
self
}
/// Set the maximum recursive depth a query can have. (default: 32)
///
/// If the value is too large, stack overflow may occur, usually `32` is
/// enough.
#[must_use]
pub fn limit_recursive_depth(mut self, depth: usize) -> Self {
self.recursive_depth = depth;
self
}
2020-09-06 05:38:31 +00:00
/// Add an extension to the schema.
2020-09-29 12:47:37 +00:00
///
/// # Examples
///
/// ```rust
/// use async_graphql::*;
///
/// struct Query;
///
/// #[Object]
/// impl Query {
/// async fn value(&self) -> i32 {
/// 100
/// }
/// }
///
2022-04-19 04:25:11 +00:00
/// let schema = Schema::build(Query, EmptyMutation, EmptySubscription)
2020-09-29 12:47:37 +00:00
/// .extension(extensions::Logger)
/// .finish();
/// ```
#[must_use]
2020-09-29 12:47:37 +00:00
pub fn extension(mut self, extension: impl ExtensionFactory) -> Self {
self.extensions.push(Box::new(extension));
2020-03-29 12:02:52 +00:00
self
}
2022-04-19 04:25:11 +00:00
/// Add a global data that can be accessed in the `Schema`. You access it
/// with `Context::data`.
#[must_use]
2020-03-29 12:02:52 +00:00
pub fn data<D: Any + Send + Sync>(mut self, data: D) -> Self {
self.data.insert(data);
2020-03-29 12:02:52 +00:00
self
}
2020-04-06 11:57:21 +00:00
/// Set the validation mode, default is `ValidationMode::Strict`.
#[must_use]
2020-04-06 11:57:21 +00:00
pub fn validation_mode(mut self, validation_mode: ValidationMode) -> Self {
self.validation_mode = validation_mode;
2020-04-06 11:57:21 +00:00
self
}
2022-04-19 04:25:11 +00:00
/// Enable federation, which is automatically enabled if the Query has least
/// one entity definition.
#[must_use]
pub fn enable_federation(mut self) -> Self {
self.registry.enable_federation = true;
self
}
/// Make the Federation SDL include subscriptions.
///
2022-04-19 04:25:11 +00:00
/// Note: Not included by default, in order to be compatible with Apollo
/// Server.
#[must_use]
pub fn enable_subscription_in_federation(mut self) -> Self {
self.registry.federation_subscription = true;
self
}
/// Override the name of the specified input type.
#[must_use]
pub fn override_input_type_description<T: InputType>(mut self, desc: &'static str) -> Self {
self.registry.set_description(&*T::type_name(), desc);
self
}
/// Override the name of the specified output type.
#[must_use]
pub fn override_output_type_description<T: OutputType>(mut self, desc: &'static str) -> Self {
self.registry.set_description(&*T::type_name(), desc);
self
}
2021-11-19 10:49:37 +00:00
/// Register a custom directive.
///
/// # Panics
///
/// Panics if the directive with the same name is already registered.
#[must_use]
2021-11-19 10:49:37 +00:00
pub fn directive<T: CustomDirectiveFactory>(mut self, directive: T) -> Self {
let name = directive.name();
let instance = Box::new(directive);
instance.register(&mut self.registry);
if name == "skip"
|| name == "include"
|| self.custom_directives.insert(name, instance).is_some()
{
panic!("Directive `{}` already exists", name);
}
self
}
/// Disable field suggestions.
#[must_use]
pub fn disable_suggestions(mut self) -> Self {
self.registry.enable_suggestions = false;
self
}
2020-03-29 12:02:52 +00:00
/// Build schema.
pub fn finish(mut self) -> Schema<Query, Mutation, Subscription> {
// federation
if self.registry.enable_federation || self.registry.has_entities() {
self.registry.create_federation_types();
}
Schema(Arc::new(SchemaInner {
validation_mode: self.validation_mode,
query: self.query,
mutation: self.mutation,
subscription: self.subscription,
complexity: self.complexity,
depth: self.depth,
recursive_depth: self.recursive_depth,
extensions: self.extensions,
env: SchemaEnv(Arc::new(SchemaEnvInner {
registry: self.registry,
data: self.data,
2021-11-19 10:49:37 +00:00
custom_directives: self.custom_directives,
})),
}))
2020-03-29 12:02:52 +00:00
}
}
#[doc(hidden)]
pub struct SchemaEnvInner {
pub registry: Registry,
pub data: Data,
2021-11-19 10:49:37 +00:00
pub custom_directives: HashMap<&'static str, Box<dyn CustomDirectiveFactory>>,
}
#[doc(hidden)]
#[derive(Clone)]
pub struct SchemaEnv(Arc<SchemaEnvInner>);
impl Deref for SchemaEnv {
type Target = SchemaEnvInner;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc(hidden)]
pub struct SchemaInner<Query, Mutation, Subscription> {
pub(crate) validation_mode: ValidationMode,
pub(crate) query: QueryRoot<Query>,
pub(crate) mutation: Mutation,
pub(crate) subscription: Subscription,
pub(crate) complexity: Option<usize>,
pub(crate) depth: Option<usize>,
pub(crate) recursive_depth: usize,
2020-09-29 12:47:37 +00:00
pub(crate) extensions: Vec<Box<dyn ExtensionFactory>>,
pub(crate) env: SchemaEnv,
}
2020-09-06 05:38:31 +00:00
/// GraphQL schema.
///
/// Cloning a schema is cheap, so it can be easily shared.
pub struct Schema<Query, Mutation, Subscription>(Arc<SchemaInner<Query, Mutation, Subscription>>);
2020-03-29 12:02:52 +00:00
impl<Query, Mutation, Subscription> Clone for Schema<Query, Mutation, Subscription> {
fn clone(&self) -> Self {
Schema(self.0.clone())
}
}
2020-08-28 06:19:35 +00:00
impl<Query, Mutation, Subscription> Default for Schema<Query, Mutation, Subscription>
where
Query: Default + ObjectType + 'static,
Mutation: Default + ObjectType + 'static,
Subscription: Default + SubscriptionType + 'static,
2020-08-28 06:19:35 +00:00
{
fn default() -> Self {
Schema::new(
Query::default(),
Mutation::default(),
Subscription::default(),
)
}
}
2020-09-12 09:29:52 +00:00
impl<Query, Mutation, Subscription> Deref for Schema<Query, Mutation, Subscription> {
type Target = SchemaInner<Query, Mutation, Subscription>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
2020-03-29 12:02:52 +00:00
impl<Query, Mutation, Subscription> Schema<Query, Mutation, Subscription>
where
Query: ObjectType + 'static,
Mutation: ObjectType + 'static,
Subscription: SubscriptionType + 'static,
2020-03-29 12:02:52 +00:00
{
/// Create a schema builder
2020-03-09 10:05:52 +00:00
///
/// The root object for the query and Mutation needs to be specified.
2020-03-19 09:20:12 +00:00
/// If there is no mutation, you can use `EmptyMutation`.
/// If there is no subscription, you can use `EmptySubscription`.
2020-03-29 12:02:52 +00:00
pub fn build(
query: Query,
mutation: Mutation,
subscription: Subscription,
) -> SchemaBuilder<Query, Mutation, Subscription> {
Self::build_with_ignore_name_conflicts(query, mutation, subscription, [] as [&str; 0])
}
/// Create a schema builder and specifies a list to ignore type conflict
/// detection.
///
/// NOTE: It is not recommended to use it unless you know what it does.
#[must_use]
pub fn build_with_ignore_name_conflicts<I, T>(
query: Query,
mutation: Mutation,
subscription: Subscription,
ignore_name_conflicts: I,
) -> SchemaBuilder<Query, Mutation, Subscription>
where
I: IntoIterator<Item = T>,
T: Into<String>,
{
2020-09-23 00:04:00 +00:00
SchemaBuilder {
validation_mode: ValidationMode::Strict,
query: QueryRoot { inner: query },
2020-09-23 00:04:00 +00:00
mutation,
subscription,
registry: Self::create_registry(
ignore_name_conflicts.into_iter().map(Into::into).collect(),
),
2020-09-23 00:04:00 +00:00
data: Default::default(),
complexity: None,
depth: None,
recursive_depth: 32,
2020-09-23 00:04:00 +00:00
extensions: Default::default(),
2021-11-19 10:49:37 +00:00
custom_directives: Default::default(),
2020-09-23 00:04:00 +00:00
}
}
pub(crate) fn create_registry(ignore_name_conflicts: HashSet<String>) -> Registry {
2020-03-08 12:35:36 +00:00
let mut registry = Registry {
types: Default::default(),
directives: Default::default(),
implements: Default::default(),
query_type: Query::type_name().to_string(),
mutation_type: if Mutation::is_empty() {
None
} else {
Some(Mutation::type_name().to_string())
},
2020-03-17 09:26:59 +00:00
subscription_type: if Subscription::is_empty() {
None
} else {
Some(Subscription::type_name().to_string())
},
2022-04-13 03:00:24 +00:00
introspection_mode: IntrospectionMode::Enabled,
enable_federation: false,
federation_subscription: false,
ignore_name_conflicts,
enable_suggestions: true,
2020-03-08 12:35:36 +00:00
};
registry.add_directive(MetaDirective {
name: "include",
description: Some("Directs the executor to include this field or fragment only when the `if` argument is true."),
2020-03-05 13:34:31 +00:00
locations: vec![
__DirectiveLocation::FIELD,
__DirectiveLocation::FRAGMENT_SPREAD,
__DirectiveLocation::INLINE_FRAGMENT
],
2020-03-08 12:35:36 +00:00
args: {
let mut args = IndexMap::new();
args.insert("if".to_string(), MetaInputValue {
2020-03-08 12:35:36 +00:00
name: "if",
description: Some("Included when true."),
ty: "Boolean!".to_string(),
2020-03-21 01:32:13 +00:00
default_value: None,
visible: None,
2022-08-18 09:40:04 +00:00
inaccessible: false,
2022-08-22 09:44:02 +00:00
tags: Default::default(),
is_secret: false,
2020-03-08 12:35:36 +00:00
});
args
2021-11-18 12:14:56 +00:00
},
is_repeatable: false,
2021-11-19 10:49:37 +00:00
visible: None,
});
registry.add_directive(MetaDirective {
name: "skip",
description: Some("Directs the executor to skip this field or fragment when the `if` argument is true."),
2020-03-05 13:34:31 +00:00
locations: vec![
__DirectiveLocation::FIELD,
__DirectiveLocation::FRAGMENT_SPREAD,
__DirectiveLocation::INLINE_FRAGMENT
],
2020-03-08 12:35:36 +00:00
args: {
let mut args = IndexMap::new();
args.insert("if".to_string(), MetaInputValue {
2020-03-08 12:35:36 +00:00
name: "if",
description: Some("Skipped when true."),
ty: "Boolean!".to_string(),
2020-03-21 01:32:13 +00:00
default_value: None,
visible: None,
2022-08-18 09:40:04 +00:00
inaccessible: false,
2022-08-22 09:44:02 +00:00
tags: Default::default(),
is_secret: false,
2020-03-08 12:35:36 +00:00
});
args
2021-11-18 12:14:56 +00:00
},
is_repeatable: false,
2021-11-19 10:49:37 +00:00
visible: None,
});
// register scalars
<bool as InputType>::create_type_info(&mut registry);
<i32 as InputType>::create_type_info(&mut registry);
<f32 as InputType>::create_type_info(&mut registry);
<String as InputType>::create_type_info(&mut registry);
<ID as InputType>::create_type_info(&mut registry);
2020-03-08 12:35:36 +00:00
QueryRoot::<Query>::create_type_info(&mut registry);
2020-03-05 09:06:14 +00:00
if !Mutation::is_empty() {
Mutation::create_type_info(&mut registry);
}
2020-03-17 09:26:59 +00:00
if !Subscription::is_empty() {
Subscription::create_type_info(&mut registry);
}
registry.remove_unused_types();
2020-09-23 00:04:00 +00:00
registry
2020-03-25 07:07:16 +00:00
}
2020-03-29 12:02:52 +00:00
/// Create a schema
pub fn new(
query: Query,
mutation: Mutation,
subscription: Subscription,
) -> Schema<Query, Mutation, Subscription> {
Self::build(query, mutation, subscription).finish()
2020-03-05 00:39:56 +00:00
}
#[inline]
#[allow(unused)]
pub(crate) fn registry(&self) -> &Registry {
&self.env.registry
}
2020-09-23 00:04:00 +00:00
/// Returns SDL(Schema Definition Language) of this schema.
2020-10-28 01:39:19 +00:00
pub fn sdl(&self) -> String {
self.0.env.registry.export_sdl(Default::default())
2020-09-23 00:04:00 +00:00
}
/// Returns SDL(Schema Definition Language) of this schema with options.
pub fn sdl_with_options(&self, options: SDLExportOptions) -> String {
self.0.env.registry.export_sdl(options)
}
2020-10-15 11:36:54 +00:00
/// Get all names in this schema
///
2022-04-19 04:25:11 +00:00
/// Maybe you want to serialize a custom binary protocol. In order to
/// minimize message size, a dictionary is usually used to compress type
/// names, field names, directive names, and parameter names. This function
/// gets all the names, so you can create this dictionary.
2020-10-15 11:36:54 +00:00
pub fn names(&self) -> Vec<String> {
self.0.env.registry.names()
}
fn create_extensions(&self, session_data: Arc<Data>) -> Extensions {
2021-04-04 04:05:54 +00:00
Extensions::new(
self.extensions.iter().map(|f| f.create()),
self.env.clone(),
session_data,
2021-04-04 04:05:54 +00:00
)
}
async fn prepare_request(
2020-05-22 03:58:49 +00:00
&self,
mut extensions: Extensions,
2020-09-30 17:24:24 +00:00
request: Request,
session_data: Arc<Data>,
) -> Result<(QueryEnv, CacheControl), Vec<ServerError>> {
let mut request = request;
let query_data = Arc::new(std::mem::take(&mut request.data));
extensions.attach_query_data(query_data.clone());
let mut request = extensions.prepare_request(request).await?;
let mut document = {
2021-04-04 04:05:54 +00:00
let query = &request.query;
2022-04-15 07:31:07 +00:00
let parsed_doc = request.parsed_query.take();
let recursive_depth = self.recursive_depth;
2022-04-15 07:31:07 +00:00
let fut_parse = async move {
let doc = match parsed_doc {
Some(parsed_doc) => parsed_doc,
None => parse_query(query)?,
};
check_recursive_depth(&doc, recursive_depth)?;
Ok(doc)
};
2021-04-04 04:05:54 +00:00
futures_util::pin_mut!(fut_parse);
extensions
2022-04-15 07:31:07 +00:00
.parse_query(query, &request.variables, &mut fut_parse)
2021-04-04 04:05:54 +00:00
.await?
};
2020-05-22 03:58:49 +00:00
// check rules
2021-04-04 04:05:54 +00:00
let validation_result = {
let validation_fut = async {
check_rules(
&self.env.registry,
&document,
Some(&request.variables),
self.validation_mode,
)
};
futures_util::pin_mut!(validation_fut);
extensions.validation(&mut validation_fut).await?
};
2020-05-22 03:58:49 +00:00
// check limit
if let Some(limit_complexity) = self.complexity {
2020-12-18 15:58:03 +00:00
if validation_result.complexity > limit_complexity {
return Err(vec![ServerError::new("Query is too complex.", None)]);
2020-05-22 03:58:49 +00:00
}
}
if let Some(limit_depth) = self.depth {
2020-12-18 15:58:03 +00:00
if validation_result.depth > limit_depth {
return Err(vec![ServerError::new("Query is nested too deep.", None)]);
2020-05-22 03:58:49 +00:00
}
}
let operation = if let Some(operation_name) = &request.operation_name {
match document.operations {
DocumentOperations::Single(_) => None,
DocumentOperations::Multiple(mut operations) => operations
.remove(operation_name.as_str())
.map(|operation| (Some(operation_name.clone()), operation)),
}
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
.ok_or_else(|| {
ServerError::new(
format!(r#"Unknown operation named "{}""#, operation_name),
None,
)
})
} else {
match document.operations {
DocumentOperations::Single(operation) => Ok((None, operation)),
DocumentOperations::Multiple(map) if map.len() == 1 => {
let (operation_name, operation) = map.into_iter().next().unwrap();
Ok((Some(operation_name.to_string()), operation))
}
DocumentOperations::Multiple(_) => Err(ServerError::new(
"Operation name required in request.",
None,
)),
}
};
let (operation_name, mut operation) = operation.map_err(|err| vec![err])?;
// remove skipped fields
for fragment in document.fragments.values_mut() {
remove_skipped_selection(&mut fragment.node.selection_set.node, &request.variables);
}
remove_skipped_selection(&mut operation.node.selection_set.node, &request.variables);
2020-09-10 04:49:08 +00:00
2020-09-29 12:47:37 +00:00
let env = QueryEnvInner {
extensions,
variables: request.variables,
operation_name,
2020-09-29 12:47:37 +00:00
operation,
fragments: document.fragments,
2020-10-10 02:32:43 +00:00
uploads: request.uploads,
session_data,
ctx_data: query_data,
extension_data: Arc::new(request.data),
http_headers: Default::default(),
introspection_mode: request.introspection_mode,
errors: Default::default(),
2020-09-29 12:47:37 +00:00
};
Ok((QueryEnv::new(env), validation_result.cache_control))
2020-09-11 07:54:56 +00:00
}
2020-09-29 12:47:37 +00:00
async fn execute_once(&self, env: QueryEnv) -> Response {
2020-09-11 07:54:56 +00:00
// execute
2020-09-10 04:49:08 +00:00
let ctx = ContextBase {
path_node: None,
is_for_introspection: false,
item: &env.operation.node.selection_set,
2020-09-10 08:39:43 +00:00
schema_env: &self.env,
2020-09-10 04:49:08 +00:00
query_env: &env,
};
2021-06-07 12:51:20 +00:00
let res = match &env.operation.node.ty {
2020-09-29 23:45:48 +00:00
OperationType::Query => resolve_container(&ctx, &self.query).await,
2022-04-13 03:00:24 +00:00
OperationType::Mutation => {
if self.env.registry.introspection_mode == IntrospectionMode::IntrospectionOnly
|| env.introspection_mode == IntrospectionMode::IntrospectionOnly
{
resolve_container_serial(&ctx, &EmptyMutation).await
} else {
resolve_container_serial(&ctx, &self.mutation).await
}
}
2021-06-07 12:51:20 +00:00
OperationType::Subscription => Err(ServerError::new(
"Subscriptions are not supported on this transport.",
None,
)),
};
let mut resp = match res {
Ok(value) => Response::new(value),
2021-06-07 12:51:20 +00:00
Err(err) => Response::from_errors(vec![err]),
}
.http_headers(std::mem::take(&mut *env.http_headers.lock().unwrap()));
2020-09-10 04:49:08 +00:00
2021-06-07 12:51:20 +00:00
resp.errors
.extend(std::mem::take(&mut *env.errors.lock().unwrap()));
resp
2020-09-10 04:49:08 +00:00
}
2020-10-22 02:11:47 +00:00
/// Execute a GraphQL query.
2020-09-11 07:54:56 +00:00
pub async fn execute(&self, request: impl Into<Request>) -> Response {
let request = request.into();
let extensions = self.create_extensions(Default::default());
2021-04-04 04:05:54 +00:00
let request_fut = {
let extensions = extensions.clone();
async move {
match self
.prepare_request(extensions, request, Default::default())
.await
{
Ok((env, cache_control)) => {
let fut = async {
self.execute_once(env.clone())
.await
.cache_control(cache_control)
};
futures_util::pin_mut!(fut);
env.extensions
.execute(env.operation_name.as_deref(), &mut fut)
.await
2021-04-04 04:05:54 +00:00
}
Err(errors) => Response::from_errors(errors),
}
}
};
futures_util::pin_mut!(request_fut);
extensions.request(&mut request_fut).await
2020-09-11 07:54:56 +00:00
}
2020-10-22 02:11:47 +00:00
/// Execute a GraphQL batch query.
2020-09-17 08:39:55 +00:00
pub async fn execute_batch(&self, batch_request: BatchRequest) -> BatchResponse {
match batch_request {
BatchRequest::Single(request) => BatchResponse::Single(self.execute(request).await),
BatchRequest::Batch(requests) => BatchResponse::Batch(
2020-10-16 06:49:22 +00:00
futures_util::stream::iter(requests.into_iter())
2020-09-17 08:39:55 +00:00
.then(|request| self.execute(request))
.collect()
.await,
),
}
}
/// Execute a GraphQL subscription with session data.
#[doc(hidden)]
pub fn execute_stream_with_session_data(
2020-09-11 08:41:56 +00:00
&self,
2020-09-17 18:22:54 +00:00
request: impl Into<Request> + Send,
session_data: Arc<Data>,
2021-04-04 04:05:54 +00:00
) -> impl Stream<Item = Response> + Send + Unpin {
let schema = self.clone();
let request = request.into();
let extensions = self.create_extensions(session_data.clone());
2021-04-04 04:05:54 +00:00
let stream = futures_util::stream::StreamExt::boxed({
let extensions = extensions.clone();
async_stream::stream! {
let (env, cache_control) = match schema.prepare_request(extensions, request, session_data).await {
Ok(res) => res,
Err(errors) => {
yield Response::from_errors(errors);
return;
}
};
if env.operation.node.ty != OperationType::Subscription {
yield schema.execute_once(env).await.cache_control(cache_control);
return;
}
2021-04-04 04:05:54 +00:00
let ctx = env.create_context(
&schema.env,
None,
&env.operation.node.selection_set,
);
2020-03-29 12:02:52 +00:00
2021-04-04 04:05:54 +00:00
let mut streams = Vec::new();
2022-04-13 03:00:24 +00:00
let collect_result = if schema.env.registry.introspection_mode
== IntrospectionMode::IntrospectionOnly
|| env.introspection_mode == IntrospectionMode::IntrospectionOnly
{
collect_subscription_streams(&ctx, &EmptySubscription, &mut streams)
} else {
collect_subscription_streams(&ctx, &schema.subscription, &mut streams)
};
if let Err(err) = collect_result {
2021-04-04 04:05:54 +00:00
yield Response::from_errors(vec![err]);
}
2020-05-18 16:03:15 +00:00
2021-04-04 04:05:54 +00:00
let mut stream = stream::select_all(streams);
while let Some(resp) = stream.next().await {
yield resp;
}
2020-09-10 08:39:43 +00:00
}
2021-04-04 04:05:54 +00:00
});
extensions.subscribe(stream)
2020-03-29 12:02:52 +00:00
}
2020-09-11 08:41:56 +00:00
2020-10-22 02:11:47 +00:00
/// Execute a GraphQL subscription.
2020-09-17 18:22:54 +00:00
pub fn execute_stream(
&self,
request: impl Into<Request>,
2021-04-04 04:05:54 +00:00
) -> impl Stream<Item = Response> + Send + Unpin {
self.execute_stream_with_session_data(request.into(), Default::default())
2020-09-11 08:41:56 +00:00
}
2020-03-01 10:54:34 +00:00
}
fn remove_skipped_selection(selection_set: &mut SelectionSet, variables: &Variables) {
fn is_skipped(directives: &[Positioned<Directive>], variables: &Variables) -> bool {
for directive in directives {
let include = match &*directive.node.name.node {
"skip" => false,
"include" => true,
_ => continue,
};
if let Some(condition_input) = directive.node.get_argument("if") {
let value = condition_input
.node
.clone()
.into_const_with(|name| variables.get(&name).cloned().ok_or(()))
.unwrap_or_default();
let value: bool = InputType::parse(Some(value)).unwrap_or_default();
if include != value {
return true;
}
}
}
false
}
selection_set
.items
.retain(|selection| !is_skipped(selection.node.directives(), variables));
for selection in &mut selection_set.items {
selection.node.directives_mut().retain(|directive| {
directive.node.name.node != "skip" && directive.node.name.node != "include"
});
}
for selection in &mut selection_set.items {
match &mut selection.node {
Selection::Field(field) => {
remove_skipped_selection(&mut field.node.selection_set.node, variables);
}
Selection::FragmentSpread(_) => {}
Selection::InlineFragment(inline_fragment) => {
remove_skipped_selection(&mut inline_fragment.node.selection_set.node, variables);
}
}
}
}
fn check_recursive_depth(doc: &ExecutableDocument, max_depth: usize) -> ServerResult<()> {
fn check_selection_set(
doc: &ExecutableDocument,
selection_set: &Positioned<SelectionSet>,
current_depth: usize,
max_depth: usize,
) -> ServerResult<()> {
if current_depth > max_depth {
return Err(ServerError::new(
format!(
"The recursion depth of the query cannot be greater than `{}`",
max_depth
),
Some(selection_set.pos),
));
}
for selection in &selection_set.node.items {
match &selection.node {
Selection::Field(field) => {
if !field.node.selection_set.node.items.is_empty() {
check_selection_set(
doc,
&field.node.selection_set,
current_depth + 1,
max_depth,
)?;
}
}
Selection::FragmentSpread(fragment_spread) => {
if let Some(fragment) =
doc.fragments.get(&fragment_spread.node.fragment_name.node)
{
check_selection_set(
doc,
&fragment.node.selection_set,
current_depth + 1,
max_depth,
)?;
}
}
Selection::InlineFragment(inline_fragment) => {
check_selection_set(
doc,
&inline_fragment.node.selection_set,
current_depth + 1,
max_depth,
)?;
}
}
}
Ok(())
}
for (_, operation) in doc.operations.iter() {
check_selection_set(doc, &operation.node.selection_set, 0, max_depth)?;
}
Ok(())
}