use std::{sync::Arc, time::Instant};
use crate::{
Value,
ast::{self, OperationKind},
complexity::{self, StaticComplexity},
error::{GraphQLError, Response},
fragments::{FragmentIndex, Fragments},
schema::Schema,
types::ObjectType,
};
use super::{
ExecutionContext, ExecutionOptions, coerce, executor,
plan::{self, PreparedPlan},
subscription::{EventHandler, subscribe_document},
};
pub(crate) struct PreparedDocument<'a> {
pub(crate) document: ast::Document<'a>,
pub(crate) operation_index: usize,
pub(crate) introspection_errors: Vec<GraphQLError>,
pub(crate) static_complexity: Option<StaticComplexity>,
pub(crate) variables: Option<coerce::CompiledVariables>,
pub(crate) plan: PreparedPlan<'a>,
pub(crate) fragment_index: FragmentIndex<'a>,
}
impl<'a> PreparedDocument<'a> {
pub(crate) fn operation(&self) -> Option<&ast::OperationDefinition<'a>> {
match self.document.definitions.get(self.operation_index) {
Some(ast::Definition::Operation(operation)) => Some(operation),
_ => None,
}
}
}
pub(crate) async fn execute<'a>(
schema: &'a Schema,
prepared: &'a PreparedDocument<'a>,
operation_name: Option<Arc<str>>,
root_type: &'a ObjectType,
request_variables: Option<&crate::Object>,
options: &ExecutionOptions,
) -> Response {
if !options.introspection && !prepared.introspection_errors.is_empty() {
return introspection_rejection(&prepared.introspection_errors, options.max_errors);
}
let Some(operation) = prepared.operation() else {
return Response::error(GraphQLError::new(
"Internal error: the prepared query has no selected operation.",
));
};
executor::execute_prepared_operation(
schema,
&prepared.document,
operation,
operation_name,
&prepared.plan,
&prepared.fragment_index,
root_type,
prepared.static_complexity.as_ref(),
prepared.variables.as_ref(),
request_variables,
options,
)
.await
}
pub(crate) async fn execute_event<'a>(
context: &'a ExecutionContext,
prepared: &'a PreparedDocument<'a>,
event: Value,
deadline: Option<Instant>,
) -> Response {
let Some(operation) = prepared.operation() else {
return Response::error(GraphQLError::new(
"Internal error: the prepared query has no selected operation.",
));
};
let Some(root_type) = context.schema.subscription_type() else {
return Response::error(GraphQLError::new(
"Schema is not configured for subscriptions.",
));
};
let fragments = Fragments::prepared(&prepared.document, &prepared.fragment_index);
executor::run_operation(
context,
fragments,
Some(&prepared.plan),
root_type,
operation,
event,
deadline,
true,
true,
)
.await
}
pub(crate) enum BuildPreparedError {
Parse(GraphQLError),
Validation(Vec<GraphQLError>),
Operation(GraphQLError),
}
#[cfg_attr(
feature = "tracing",
tracing::instrument(
skip_all,
level = "info",
name = "gql.prepare",
fields(source_bytes = source.len(), operation = operation_name.unwrap_or("<anonymous>"))
)
)]
pub(crate) fn build<'a>(
schema: &Schema,
source: &'a str,
operation_name: Option<&str>,
) -> Result<PreparedDocument<'a>, BuildPreparedError> {
use crate::validation::{self, ValidationOptions};
let document = match crate::parser::parse_query(source) {
Ok(document) => document,
Err(error) => return Err(BuildPreparedError::Parse(error)),
};
let validation_errors = validation::validate(
schema,
&document,
&ValidationOptions {
introspection: true,
max_depth: 0,
max_errors: 100,
},
);
if !validation_errors.is_empty() {
return Err(BuildPreparedError::Validation(validation_errors));
}
let operation_index = match select_operation_index(&document, operation_name) {
Ok(index) => index,
Err(error) => return Err(BuildPreparedError::Operation(error)),
};
let static_complexity = match document.definitions.get(operation_index) {
Some(ast::Definition::Operation(operation)) => {
complexity::static_bound(schema, &document, operation)
}
_ => None,
};
let variables = match document.definitions.get(operation_index) {
Some(ast::Definition::Operation(operation)) => {
coerce::CompiledVariables::compile(schema, operation).ok()
}
_ => None,
};
let plan = match document.definitions.get(operation_index) {
Some(ast::Definition::Operation(operation)) => match root_type(schema, operation.kind) {
Ok(root) => plan::build(schema, &document, operation, &root),
Err(_) => plan::build_empty(),
},
_ => plan::build_empty(),
};
let fragment_index = FragmentIndex::new(&document);
let introspection_errors = if uses_introspection(&document) {
validation::validate(
schema,
&document,
&ValidationOptions {
introspection: false,
max_depth: 0,
max_errors: MAX_STORED_INTROSPECTION_ERRORS,
},
)
} else {
Vec::new()
};
Ok(PreparedDocument {
document,
operation_index,
introspection_errors,
static_complexity,
variables,
plan,
fragment_index,
})
}
const MAX_STORED_INTROSPECTION_ERRORS: usize = 100;
fn introspection_rejection(errors: &[GraphQLError], max_errors: usize) -> Response {
let limit = if max_errors == 0 {
errors.len()
} else {
max_errors.min(errors.len())
};
Response {
data: None,
errors: errors[..limit].to_vec(),
extensions: None,
}
}
fn select_operation_index(
document: &ast::Document<'_>,
operation_name: Option<&str>,
) -> Result<usize, GraphQLError> {
let mut operations = document.definitions.iter().enumerate().filter_map(
|(index, definition)| match definition {
ast::Definition::Operation(operation) => Some((index, operation)),
_ => None,
},
);
let Some((first_index, first)) = operations.next() else {
return Err(GraphQLError::new("Must provide an operation."));
};
match operation_name {
Some(name) => {
if first.name == Some(name) {
return Ok(first_index);
}
operations
.find(|(_, operation)| operation.name == Some(name))
.map(|(index, _)| index)
.ok_or_else(|| GraphQLError::new(format!("Unknown operation named \"{name}\".")))
}
None => {
if operations.next().is_some() {
Err(GraphQLError::new(
"Must provide an operation name if the document contains multiple operations.",
))
} else {
Ok(first_index)
}
}
}
}
fn uses_introspection(document: &ast::Document<'_>) -> bool {
fn selection_set_uses(selection_set: &ast::SelectionSet<'_>) -> bool {
selection_set.items.iter().any(|selection| match selection {
ast::Selection::Field(field) => {
matches!(field.name, "__schema" | "__type")
|| field.selection_set.as_ref().is_some_and(selection_set_uses)
}
ast::Selection::InlineFragment(fragment) => selection_set_uses(&fragment.selection_set),
ast::Selection::FragmentSpread(_) => false,
})
}
document
.definitions
.iter()
.any(|definition| match definition {
ast::Definition::Operation(operation) => selection_set_uses(&operation.selection_set),
ast::Definition::Fragment(fragment) => selection_set_uses(&fragment.selection_set),
ast::Definition::TypeSystem(_) => false,
})
}
pub(crate) fn root_type(
schema: &Schema,
kind: OperationKind,
) -> Result<Arc<ObjectType>, GraphQLError> {
match kind {
OperationKind::Query => Ok(Arc::clone(schema.query_type())),
OperationKind::Mutation => schema
.mutation_name()
.and_then(|name| schema.object_type(name.as_ref()))
.cloned()
.ok_or_else(|| GraphQLError::new("Schema is not configured for mutations.")),
OperationKind::Subscription => schema
.subscription_type()
.cloned()
.ok_or_else(|| GraphQLError::new("Schema is not configured for subscriptions.")),
}
}
pub(crate) struct PreparedExecution<'a> {
pub(crate) operation_name: Option<Arc<str>>,
pub(crate) static_complexity: Option<&'a StaticComplexity>,
pub(crate) variables: Option<&'a coerce::CompiledVariables>,
pub(crate) plan: &'a PreparedPlan<'a>,
pub(crate) fragments: Fragments<'a>,
}
#[allow(clippy::result_large_err)]
pub(crate) async fn subscribe<'a>(
schema: &'a Schema,
prepared: &'a PreparedDocument<'a>,
operation_name: Option<Arc<str>>,
request_variables: Option<&crate::Object>,
options: &ExecutionOptions,
make_event_handler: impl FnOnce(Arc<ExecutionContext>, Option<std::time::Duration>) -> EventHandler,
) -> Result<crate::SubscriptionResponse, Response> {
if !options.introspection && !prepared.introspection_errors.is_empty() {
return Err(introspection_rejection(
&prepared.introspection_errors,
options.max_errors,
));
}
let Some(operation) = prepared.operation() else {
return Err(Response::error(GraphQLError::new(
"Internal error: the prepared query has no selected operation.",
)));
};
let execution = PreparedExecution {
operation_name,
static_complexity: prepared.static_complexity.as_ref(),
variables: prepared.variables.as_ref(),
plan: &prepared.plan,
fragments: Fragments::prepared(&prepared.document, &prepared.fragment_index),
};
subscribe_document(
schema,
&prepared.document,
operation,
request_variables,
options,
Some(execution),
make_event_handler,
)
.await
}