pub(crate) mod coerce;
mod collect;
mod executor;
mod plan;
mod prepared;
mod selection;
pub(crate) mod subscription;
pub(crate) use prepared::{
BuildPreparedError, PreparedDocument, build as build_prepared, execute as execute_prepared,
execute_event as execute_prepared_event, root_type as prepared_root_type,
subscribe as subscribe_prepared,
};
use std::{any::Any, fmt, sync::Arc, time::Duration};
use futures::{FutureExt, future::BoxFuture, stream::BoxStream};
use crate::{
Object, Value,
error::{GraphQLError, PathSegment, Response},
schema::Schema,
types::{ResolveInfo, TypeRef},
};
pub use coerce::{CoercedVariables, coerce_argument_values, coerce_variable_values};
pub use subscription::SubscriptionResponse;
pub struct ExecutionOptions {
pub context: Arc<dyn Any + Send + Sync>,
pub root_value: Value,
pub introspection: bool,
pub authorizer: Option<Arc<dyn Authorizer>>,
pub max_depth: usize,
pub max_complexity: u32,
pub max_breadth: usize,
pub list_complexity: u32,
pub max_errors: usize,
pub max_concurrency: usize,
pub timeout: Option<Duration>,
}
impl fmt::Debug for ExecutionOptions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ExecutionOptions")
.field("root_value", &self.root_value)
.field("introspection", &self.introspection)
.field("authorizer", &self.authorizer.is_some())
.field("max_depth", &self.max_depth)
.field("max_complexity", &self.max_complexity)
.field("max_breadth", &self.max_breadth)
.field("list_complexity", &self.list_complexity)
.field("max_errors", &self.max_errors)
.field("max_concurrency", &self.max_concurrency)
.field("timeout", &self.timeout)
.finish_non_exhaustive()
}
}
impl Default for ExecutionOptions {
fn default() -> Self {
Self {
context: Arc::new(()),
root_value: Value::Null,
introspection: true,
authorizer: None,
max_depth: 0,
max_complexity: 0,
max_breadth: 0,
list_complexity: 10,
max_errors: 100,
max_concurrency: 16,
timeout: None,
}
}
}
impl ExecutionOptions {
#[must_use]
pub fn with_context<T: Any + Send + Sync>(context: T) -> Self {
Self {
context: Arc::new(context),
..Self::default()
}
}
#[must_use]
pub fn context<T: Any + Send + Sync>(mut self, context: T) -> Self {
self.context = Arc::new(context);
self
}
#[must_use]
pub fn root_value(mut self, value: impl Into<Value>) -> Self {
self.root_value = value.into();
self
}
#[must_use]
pub const fn introspection(mut self, enabled: bool) -> Self {
self.introspection = enabled;
self
}
#[must_use]
pub fn authorizer(mut self, authorizer: impl Authorizer + 'static) -> Self {
self.authorizer = Some(Arc::new(authorizer));
self
}
#[must_use]
pub const fn max_depth(mut self, depth: usize) -> Self {
self.max_depth = depth;
self
}
#[must_use]
pub const fn max_complexity(mut self, complexity: u32) -> Self {
self.max_complexity = complexity;
self
}
#[must_use]
pub const fn max_breadth(mut self, breadth: usize) -> Self {
self.max_breadth = breadth;
self
}
#[must_use]
pub const fn max_errors(mut self, max_errors: usize) -> Self {
self.max_errors = max_errors;
self
}
#[must_use]
pub const fn max_concurrency(mut self, max_concurrency: usize) -> Self {
self.max_concurrency = max_concurrency;
self
}
}
pub struct ExecutionContext {
pub schema: Schema,
pub user_data: Arc<dyn Any + Send + Sync>,
pub operation_name: Option<Arc<str>>,
pub variables: Object,
pub introspection: bool,
pub authorizer: Option<Arc<dyn Authorizer>>,
pub max_errors: usize,
pub max_concurrency: usize,
pub extensions: std::sync::Mutex<Option<Object>>,
}
impl fmt::Debug for ExecutionContext {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ExecutionContext")
.field("operation_name", &self.operation_name)
.field("variables", &self.variables)
.field("introspection", &self.introspection)
.finish_non_exhaustive()
}
}
impl ExecutionContext {
#[must_use]
pub fn data<T: Any>(&self) -> Option<&T> {
self.user_data.downcast_ref()
}
pub fn require_data<T: Any>(&self) -> Result<&T, GraphQLError> {
self.data().ok_or_else(|| {
GraphQLError::new("Execution context has an unexpected type; check the server setup.")
})
}
pub fn set_extension(&self, key: impl Into<Arc<str>>, value: impl Into<Value>) {
if let Ok(mut extensions) = self.extensions.lock() {
extensions
.get_or_insert_with(Object::new)
.insert(key, value);
}
}
}
pub struct AuthorizationContext<'a> {
pub context: &'a ExecutionContext,
pub field_name: &'a str,
pub parent_type: &'a str,
pub return_type: &'a TypeRef,
pub path: &'a [PathSegment],
pub args: &'a Object,
pub info: &'a ResolveInfo<'a>,
}
impl fmt::Debug for AuthorizationContext<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AuthorizationContext")
.field("field_name", &self.field_name)
.field("parent_type", &self.parent_type)
.field("path", &self.path)
.finish_non_exhaustive()
}
}
pub trait Authorizer: Send + Sync {
fn authorize(&self, context: &AuthorizationContext<'_>) -> Result<(), GraphQLError> {
let _ = context;
Ok(())
}
fn authorize_async<'a>(
&'a self,
context: &'a AuthorizationContext<'a>,
) -> BoxFuture<'a, Result<(), GraphQLError>> {
futures::future::ready(self.authorize(context)).boxed()
}
}
#[derive(Clone, Copy, Debug)]
pub struct Request<'a> {
pub query: &'a str,
pub operation_name: Option<&'a str>,
pub variables: Option<&'a Object>,
}
impl<'a> Request<'a> {
#[must_use]
pub const fn new(query: &'a str) -> Self {
Self {
query,
operation_name: None,
variables: None,
}
}
#[must_use]
pub const fn operation_name(mut self, name: &'a str) -> Self {
self.operation_name = Some(name);
self
}
#[must_use]
pub const fn variables(mut self, variables: &'a Object) -> Self {
self.variables = Some(variables);
self
}
}
#[cfg_attr(
feature = "tracing",
tracing::instrument(
skip_all,
level = "info",
name = "gql.execute",
fields(
operation = request.operation_name.unwrap_or("<anonymous>"),
document_bytes = request.query.len(),
variable_count = request.variables.map_or(0, Object::len),
kind = tracing::field::Empty,
errors = tracing::field::Empty,
)
)
)]
pub async fn execute(
schema: &Schema,
request: Request<'_>,
options: &ExecutionOptions,
) -> Response {
executor::execute(schema, request, options).await
}
#[cfg_attr(
feature = "tracing",
tracing::instrument(
skip_all,
level = "info",
name = "gql.subscribe",
fields(
operation = request.operation_name.unwrap_or("<anonymous>"),
document_bytes = request.query.len(),
variable_count = request.variables.map_or(0, Object::len),
kind = "subscription",
errors = tracing::field::Empty,
)
)
)]
pub async fn subscribe(
schema: &Schema,
request: Request<'_>,
options: &ExecutionOptions,
) -> Result<SubscriptionResponse, Response> {
subscription::subscribe(schema, request, options).await
}
pub type ResponseStream = BoxStream<'static, Response>;