async-graphql/src/schema.rs

504 lines
16 KiB
Rust
Raw Normal View History

2020-09-10 04:49:08 +00:00
use crate::context::{Data, ResolveId};
use crate::extensions::{BoxExtension, ErrorLogger, Extension, Extensions};
use crate::model::__DirectiveLocation;
use crate::parser::parse_query;
2020-09-11 07:54:56 +00:00
use crate::parser::types::OperationType;
use crate::registry::{MetaDirective, MetaInputValue, Registry};
2020-09-12 09:29:52 +00:00
use crate::resolver_utils::{resolve_object, resolve_object_serial, ObjectType};
use crate::subscription::collect_subscription_streams;
2020-03-03 11:15:18 +00:00
use crate::types::QueryRoot;
2020-05-22 03:58:49 +00:00
use crate::validation::{check_rules, CheckResult, ValidationMode};
2020-03-29 12:02:52 +00:00
use crate::{
2020-09-12 09:29:52 +00:00
CacheControl, ContextBase, Error, Pos, QueryEnv, QueryError, Request, Response, Result,
SubscriptionType, Type, Variables, ID,
2020-03-29 12:02:52 +00:00
};
2020-09-11 07:54:56 +00:00
use async_graphql_parser::types::ExecutableDocumentData;
use futures::stream::{self, Stream, StreamExt};
use indexmap::map::IndexMap;
2020-05-22 03:58:49 +00:00
use itertools::Itertools;
use std::any::Any;
use std::ops::Deref;
2020-03-29 12:02:52 +00:00
use std::sync::atomic::AtomicUsize;
use std::sync::Arc;
2020-03-01 10:54:34 +00:00
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>,
extensions: Vec<Box<dyn Fn() -> BoxExtension + Send + Sync>>,
enable_federation: bool,
}
2020-03-29 12:02:52 +00:00
2020-03-19 09:20:12 +00:00
impl<Query: ObjectType, Mutation: ObjectType, Subscription: SubscriptionType>
2020-03-29 12:02:52 +00:00
SchemaBuilder<Query, Mutation, Subscription>
2020-03-17 09:26:59 +00:00
{
2020-09-06 05:38:31 +00:00
/// Manually register a type in the schema.
///
/// You can use this function to register schema types that are not directly referenced.
pub fn register_type<T: Type>(mut self) -> Self {
T::create_type_info(&mut self.registry);
self
}
2020-09-06 05:38:31 +00:00
/// Disable introspection queries.
2020-03-29 12:02:52 +00:00
pub fn disable_introspection(mut self) -> Self {
self.query.disable_introspection = true;
2020-03-29 12:02:52 +00:00
self
}
2020-09-06 05:38:31 +00:00
/// Set the maximum complexity a query can have. By default there is no limit.
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-09-06 05:38:31 +00:00
/// Set the maximum depth a query can have. By default there is no limit.
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
}
2020-09-06 05:38:31 +00:00
/// Add an extension to the schema.
2020-03-29 12:02:52 +00:00
pub fn extension<F: Fn() -> E + Send + Sync + 'static, E: Extension>(
mut self,
extension_factory: F,
) -> Self {
self.extensions
2020-03-29 12:02:52 +00:00
.push(Box::new(move || Box::new(extension_factory())));
self
}
2020-09-06 05:38:31 +00:00
/// Add a global data that can be accessed in the `Schema`. You access it with `Context::data`.
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`.
pub fn validation_mode(mut self, validation_mode: ValidationMode) -> Self {
self.validation_mode = validation_mode;
2020-04-06 11:57:21 +00:00
self
}
/// Enable federation, which is automatically enabled if the Query has least one entity definition.
pub fn enable_federation(mut self) -> Self {
self.enable_federation = true;
self
}
2020-03-29 12:02:52 +00:00
/// Build schema.
pub fn finish(mut self) -> Schema<Query, Mutation, Subscription> {
// federation
if self.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,
extensions: self.extensions,
env: SchemaEnv(Arc::new(SchemaEnvInner {
registry: self.registry,
data: self.data,
})),
}))
2020-03-29 12:02:52 +00:00
}
}
#[doc(hidden)]
pub struct SchemaEnvInner {
pub registry: Registry,
pub data: Data,
}
#[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) extensions: Vec<Box<dyn Fn() -> BoxExtension + Send + Sync>>,
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 + Send + Sync + 'static,
Mutation: Default + ObjectType + Send + Sync + 'static,
Subscription: Default + SubscriptionType + Send + Sync + 'static,
{
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 + Send + Sync + 'static,
Mutation: ObjectType + Send + Sync + 'static,
Subscription: SubscriptionType + Send + Sync + 'static,
{
/// 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> {
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())
},
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", 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,
2020-03-22 01:34:32 +00:00
validator: None,
2020-03-08 12:35:36 +00:00
});
args
}
});
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", 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,
2020-03-22 01:34:32 +00:00
validator: None,
2020-03-08 12:35:36 +00:00
});
args
}
});
2020-08-06 06:52:54 +00:00
registry.add_directive(MetaDirective {
name: "ifdef",
description: Some("Directs the executor to query only when the field exists."),
locations: vec![__DirectiveLocation::FIELD],
args: Default::default(),
});
// register scalars
bool::create_type_info(&mut registry);
i32::create_type_info(&mut registry);
f32::create_type_info(&mut registry);
String::create_type_info(&mut registry);
ID::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);
}
SchemaBuilder {
2020-04-06 11:57:21 +00:00
validation_mode: ValidationMode::Strict,
2020-03-25 07:07:16 +00:00
query: QueryRoot {
inner: query,
disable_introspection: false,
},
2020-03-01 10:54:34 +00:00
mutation,
2020-03-17 09:26:59 +00:00
subscription,
2020-03-05 00:39:56 +00:00
registry,
data: Default::default(),
2020-03-25 07:07:16 +00:00
complexity: None,
depth: None,
2020-03-26 03:34:28 +00:00
extensions: Default::default(),
enable_federation: false,
}
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
}
2020-09-11 07:54:56 +00:00
fn prepare_request(
2020-05-22 03:58:49 +00:00
&self,
2020-09-11 07:54:56 +00:00
request: &Request,
) -> Result<(
ExecutableDocumentData,
CacheControl,
spin::Mutex<Extensions>,
)> {
2020-05-22 03:58:49 +00:00
// create extension instances
let extensions = spin::Mutex::new(Extensions(
self.0
.extensions
.iter()
.map(|factory| factory())
.collect_vec(),
));
2020-05-22 03:58:49 +00:00
2020-09-11 07:54:56 +00:00
extensions
.lock()
.parse_start(&request.query, &request.variables);
let document = parse_query(&request.query)
.map_err(Into::<Error>::into)
.log_error(&extensions)?;
extensions.lock().parse_end(&document);
2020-05-22 03:58:49 +00:00
// check rules
extensions.lock().validation_start();
2020-05-22 03:58:49 +00:00
let CheckResult {
cache_control,
complexity,
depth,
} = check_rules(
&self.env.registry,
&document,
2020-09-11 07:54:56 +00:00
Some(&request.variables),
self.validation_mode,
)
.log_error(&extensions)?;
extensions.lock().validation_end();
2020-05-22 03:58:49 +00:00
// check limit
if let Some(limit_complexity) = self.complexity {
if complexity > limit_complexity {
return Err(QueryError::TooComplex.into_error(Pos::default()))
.log_error(&extensions);
2020-05-22 03:58:49 +00:00
}
}
if let Some(limit_depth) = self.depth {
if depth > limit_depth {
return Err(QueryError::TooDeep.into_error(Pos::default())).log_error(&extensions);
2020-05-22 03:58:49 +00:00
}
}
2020-09-10 11:35:48 +00:00
let document = match document.into_data(request.operation_name.as_deref()) {
2020-09-10 04:49:08 +00:00
Some(document) => document,
None => {
2020-09-11 07:54:56 +00:00
let err = if let Some(operation_name) = &request.operation_name {
2020-09-10 08:39:43 +00:00
Error::Query {
2020-09-10 04:49:08 +00:00
pos: Pos::default(),
path: None,
err: QueryError::UnknownOperationNamed {
2020-09-11 07:54:56 +00:00
name: operation_name.to_string(),
2020-09-10 04:49:08 +00:00
},
2020-09-10 08:39:43 +00:00
}
2020-09-10 04:49:08 +00:00
} else {
2020-09-10 08:39:43 +00:00
Error::Query {
2020-09-10 04:49:08 +00:00
pos: Pos::default(),
path: None,
err: QueryError::MissingOperation,
2020-09-10 08:39:43 +00:00
}
};
extensions.lock().error(&err);
2020-09-11 07:54:56 +00:00
return Err(err);
2020-09-10 04:49:08 +00:00
}
};
2020-09-11 07:54:56 +00:00
Ok((document, cache_control, extensions))
}
async fn execute_once(
&self,
document: ExecutableDocumentData,
extensions: spin::Mutex<Extensions>,
variables: Variables,
ctx_data: Data,
) -> Response {
// execute
let inc_resolve_id = AtomicUsize::default();
let env = QueryEnv::new(extensions, variables, document, Arc::new(ctx_data));
2020-09-10 04:49:08 +00:00
let ctx = ContextBase {
path_node: None,
resolve_id: ResolveId::root(),
inc_resolve_id: &inc_resolve_id,
item: &env.document.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,
};
env.extensions.lock().execution_start();
2020-09-10 04:49:08 +00:00
let data = match &env.document.operation.node.ty {
OperationType::Query => resolve_object(&ctx, &self.query).await,
2020-09-14 01:46:22 +00:00
OperationType::Mutation => resolve_object_serial(&ctx, &self.mutation).await,
2020-09-10 04:49:08 +00:00
OperationType::Subscription => {
2020-09-10 08:39:43 +00:00
return Error::Query {
2020-09-10 04:49:08 +00:00
pos: Pos::default(),
path: None,
err: QueryError::NotSupported,
2020-09-10 08:39:43 +00:00
}
2020-09-10 04:49:08 +00:00
.into()
}
};
env.extensions.lock().execution_end();
2020-09-10 08:39:43 +00:00
let extensions = env.extensions.lock().result();
2020-09-14 01:46:22 +00:00
Response::from_result(data).extensions(extensions)
2020-09-10 04:49:08 +00:00
}
2020-09-11 07:54:56 +00:00
/// Execute an GraphQL query.
pub async fn execute(&self, request: impl Into<Request>) -> Response {
let request = request.into();
match self.prepare_request(&request) {
Ok((document, cache_control, extensions)) => self
.execute_once(document, extensions, request.variables, request.data)
.await
.cache_control(cache_control),
Err(e) => Response::from_error(e),
}
2020-09-11 07:54:56 +00:00
}
2020-09-11 08:41:56 +00:00
pub(crate) fn execute_stream_with_ctx_data(
&self,
request: impl Into<Request>,
ctx_data: Arc<Data>,
) -> impl Stream<Item = Response> {
let schema = self.clone();
2020-09-11 07:54:56 +00:00
async_stream::stream! {
let request = request.into();
let (document, cache_control, extensions) = match schema.prepare_request(&request) {
2020-09-11 07:54:56 +00:00
Ok(res) => res,
Err(err) => {
yield Response::from(err);
return;
}
};
if document.operation.node.ty != OperationType::Subscription {
yield schema
2020-09-12 16:07:46 +00:00
.execute_once(document, extensions, request.variables, request.data)
.await
.cache_control(cache_control);
return;
}
2020-03-29 12:02:52 +00:00
let resolve_id = AtomicUsize::default();
let env = QueryEnv::new(
extensions,
request.variables,
document,
2020-09-11 08:41:56 +00:00
ctx_data,
);
let ctx = env.create_context(
&schema.env,
None,
&env.document.operation.node.selection_set,
&resolve_id,
);
// TODO: Invoke extensions
let mut streams = Vec::new();
if let Err(e) = collect_subscription_streams(&ctx, &schema.subscription, &mut streams) {
yield Response::from(e);
return;
}
2020-05-18 16:03:15 +00:00
let mut stream = stream::select_all(streams);
while let Some(data) = stream.next().await {
let is_err = data.is_err();
let extensions = env.extensions.lock().result();
yield Response::from_result(data).extensions(extensions);
if is_err {
break;
}
2020-09-10 08:39:43 +00:00
}
2020-09-11 07:54:56 +00:00
}
2020-03-29 12:02:52 +00:00
}
2020-09-11 08:41:56 +00:00
/// Execute an GraphQL subscription.
pub fn execute_stream(&self, request: impl Into<Request>) -> impl Stream<Item = Response> {
let mut request = request.into();
2020-09-12 16:07:46 +00:00
let ctx_data = std::mem::take(&mut request.data);
2020-09-11 08:41:56 +00:00
self.execute_stream_with_ctx_data(request, Arc::new(ctx_data))
}
2020-03-01 10:54:34 +00:00
}