use std::{fmt, sync::Arc, time::Duration};
use futures::FutureExt as _;
use rustc_hash::FxHashMap;
use self_cell::self_cell;
use crate::{
Object,
ast::OperationKind,
error::{GraphQLError, Response},
execution::{self, ExecutionContext, ExecutionOptions, PreparedDocument, SubscriptionResponse},
schema::Schema,
types::ObjectType,
};
self_cell!(
struct PreparedQueryCell {
owner: Arc<str>,
#[covariant]
dependent: PreparedDocument,
}
);
#[derive(Clone, Debug, PartialEq)]
pub enum PreparedQueryError {
Parse(GraphQLError),
Validation(Vec<GraphQLError>),
Operation(GraphQLError),
}
impl PreparedQueryError {
#[must_use]
pub fn errors(&self) -> Vec<GraphQLError> {
match self {
Self::Parse(error) | Self::Operation(error) => vec![error.clone()],
Self::Validation(errors) => errors.clone(),
}
}
}
impl fmt::Display for PreparedQueryError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Parse(error) => write!(f, "failed to parse query: {error}"),
Self::Operation(error) => write!(f, "invalid operation: {error}"),
Self::Validation(errors) => {
f.write_str("query failed validation")?;
for error in errors {
write!(f, ": {error}")?;
}
Ok(())
}
}
}
}
impl std::error::Error for PreparedQueryError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Parse(error) | Self::Operation(error) => Some(error),
Self::Validation(_) => None,
}
}
}
impl From<GraphQLError> for PreparedQueryError {
fn from(value: GraphQLError) -> Self {
Self::Operation(value)
}
}
struct PreparedQueryInner {
id: Arc<str>,
schema: Schema,
operation_name: Option<Arc<str>>,
kind: OperationKind,
root_type: Arc<ObjectType>,
cell: PreparedQueryCell,
}
#[derive(Clone)]
pub struct PreparedQuery {
inner: Arc<PreparedQueryInner>,
}
impl fmt::Debug for PreparedQuery {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PreparedQuery")
.field("id", &self.inner.id)
.field("operation_name", &self.inner.operation_name)
.field("kind", &self.inner.kind)
.field("root_type", &self.inner.root_type.name)
.field("source_len", &self.inner.cell.borrow_owner().len())
.finish()
}
}
impl PreparedQuery {
pub fn new(
schema: &Schema,
id: impl Into<Arc<str>>,
source: &str,
operation_name: Option<&str>,
) -> Result<Self, PreparedQueryError> {
Self::prepare(schema, id, source, operation_name)
}
pub fn prepare(
schema: &Schema,
id: impl Into<Arc<str>>,
source: &str,
operation_name: Option<&str>,
) -> Result<Self, PreparedQueryError> {
let owner: Arc<str> = Arc::from(source);
let cell = PreparedQueryCell::try_new(owner, |owner| {
execution::build_prepared(schema, owner.as_ref(), operation_name).map_err(|error| {
match error {
execution::BuildPreparedError::Parse(error) => PreparedQueryError::Parse(error),
execution::BuildPreparedError::Validation(errors) => {
PreparedQueryError::Validation(errors)
}
execution::BuildPreparedError::Operation(error) => {
PreparedQueryError::Operation(error)
}
}
})
})?;
let (operation_name, kind) = cell.with_dependent(|_, prepared| {
let Some(operation) = prepared.operation() else {
return Err(PreparedQueryError::Operation(GraphQLError::new(
"Must provide an operation.",
)));
};
Ok((operation.name.map(Arc::from), operation.kind))
})?;
let root_type =
execution::prepared_root_type(schema, kind).map_err(PreparedQueryError::from)?;
Ok(Self {
inner: Arc::new(PreparedQueryInner {
id: id.into(),
schema: schema.clone(),
operation_name,
kind,
root_type,
cell,
}),
})
}
#[must_use]
pub fn id(&self) -> &str {
&self.inner.id
}
#[must_use]
pub fn source(&self) -> &str {
self.inner.cell.borrow_owner()
}
#[must_use]
pub fn operation_name(&self) -> Option<&str> {
self.inner.operation_name.as_deref()
}
#[must_use]
pub fn kind(&self) -> OperationKind {
self.inner.kind
}
#[must_use]
pub fn root_type(&self) -> &ObjectType {
&self.inner.root_type
}
#[must_use]
pub fn schema(&self) -> &Schema {
&self.inner.schema
}
#[cfg_attr(
feature = "tracing",
tracing::instrument(
skip_all,
level = "info",
name = "gql.execute_prepared",
fields(
prepared_id = self.inner.id.chars().take(8).collect::<String>(),
kind = ?self.inner.kind,
operation = self.inner.operation_name.as_deref().unwrap_or("<anonymous>"),
variable_count = variables.map_or(0, Object::len),
)
)
)]
pub async fn execute(
&self,
variables: Option<&Object>,
options: &ExecutionOptions,
) -> Response {
let prepared = self.inner.cell.borrow_dependent();
execution::execute_prepared(
&self.inner.schema,
prepared,
self.inner.operation_name.clone(),
&self.inner.root_type,
variables,
options,
)
.await
}
#[allow(clippy::result_large_err)]
#[cfg_attr(
feature = "tracing",
tracing::instrument(
skip_all,
level = "info",
name = "gql.subscribe_prepared",
fields(
prepared_id = self.inner.id.chars().take(8).collect::<String>(),
variable_count = variables.map_or(0, Object::len),
)
)
)]
pub async fn subscribe(
&self,
variables: Option<&Object>,
options: &ExecutionOptions,
) -> Result<SubscriptionResponse, Response> {
let inner = Arc::clone(&self.inner);
let prepared = self.inner.cell.borrow_dependent();
execution::subscribe_prepared(
&self.inner.schema,
prepared,
self.inner.operation_name.clone(),
variables,
options,
move |_context, timeout| prepared_event_handler(inner, timeout),
)
.await
}
}
fn prepared_event_handler(
inner: Arc<PreparedQueryInner>,
timeout: Option<Duration>,
) -> execution::subscription::EventHandler {
Arc::new(move |context: Arc<ExecutionContext>, event: crate::Value| {
let inner = Arc::clone(&inner);
async move {
let deadline = timeout.map(|timeout| std::time::Instant::now() + timeout);
let prepared = inner.cell.borrow_dependent();
execution::execute_prepared_event(&context, prepared, event, deadline).await
}
.boxed()
})
}
pub async fn execute_prepared(
query: &PreparedQuery,
variables: Option<&Object>,
options: &ExecutionOptions,
) -> Response {
query.execute(variables, options).await
}
#[derive(Clone, Debug, PartialEq)]
pub enum PreparedQueryRegistryError {
EmptyId,
DuplicateId {
id: Arc<str>,
},
Query {
id: Arc<str>,
error: PreparedQueryError,
},
}
impl fmt::Display for PreparedQueryRegistryError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::EmptyId => f.write_str("a prepared query must have a non-empty id"),
Self::DuplicateId { id } => write!(f, "duplicate prepared query id \"{id}\""),
Self::Query { id, error } => write!(f, "prepared query \"{id}\" is invalid: {error}"),
}
}
}
impl std::error::Error for PreparedQueryRegistryError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Query { error, .. } => Some(error),
Self::EmptyId | Self::DuplicateId { .. } => None,
}
}
}
struct PreparedQueryRegistryInner {
queries: FxHashMap<Arc<str>, PreparedQuery>,
ids: Vec<Arc<str>>,
}
impl Clone for PreparedQueryRegistryInner {
fn clone(&self) -> Self {
Self {
queries: self.queries.clone(),
ids: self.ids.clone(),
}
}
}
#[derive(Clone)]
pub struct PreparedQueryRegistry {
inner: Arc<PreparedQueryRegistryInner>,
}
impl fmt::Debug for PreparedQueryRegistry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PreparedQueryRegistry")
.field("len", &self.inner.queries.len())
.finish()
}
}
impl Default for PreparedQueryRegistry {
fn default() -> Self {
Self::empty()
}
}
impl PreparedQueryRegistry {
pub fn new<I, Id, S>(schema: &Schema, queries: I) -> Result<Self, PreparedQueryRegistryError>
where
I: IntoIterator<Item = (Id, S, Option<S>)>,
Id: AsRef<str>,
S: AsRef<str>,
{
let mut inner = PreparedQueryRegistryInner {
queries: FxHashMap::default(),
ids: Vec::new(),
};
for (id, source, operation_name) in queries {
let id: Arc<str> = Arc::from(id.as_ref());
if id.is_empty() {
return Err(PreparedQueryRegistryError::EmptyId);
}
if inner.queries.contains_key(&id) {
return Err(PreparedQueryRegistryError::DuplicateId { id });
}
let query = PreparedQuery::new(
schema,
Arc::clone(&id),
source.as_ref(),
operation_name.as_ref().map(AsRef::as_ref),
)
.map_err(|error| PreparedQueryRegistryError::Query {
id: Arc::clone(&id),
error,
})?;
inner.ids.push(Arc::clone(&id));
inner.queries.insert(id, query);
}
Ok(Self {
inner: Arc::new(inner),
})
}
#[must_use]
pub fn empty() -> Self {
Self {
inner: Arc::new(PreparedQueryRegistryInner {
queries: FxHashMap::default(),
ids: Vec::new(),
}),
}
}
pub fn insert(&mut self, query: PreparedQuery) -> Result<(), PreparedQueryRegistryError> {
if query.id().is_empty() {
return Err(PreparedQueryRegistryError::EmptyId);
}
let inner = Arc::make_mut(&mut self.inner);
let id = Arc::from(query.id());
if inner.queries.contains_key(&id) {
return Err(PreparedQueryRegistryError::DuplicateId { id });
}
inner.ids.push(Arc::clone(&id));
inner.queries.insert(id, query);
Ok(())
}
#[must_use]
pub fn get(&self, id: &str) -> Option<&PreparedQuery> {
self.inner.queries.get(id)
}
#[must_use]
pub fn contains(&self, id: &str) -> bool {
self.inner.queries.contains_key(id)
}
#[must_use]
pub fn len(&self) -> usize {
self.inner.queries.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.inner.queries.is_empty()
}
pub fn ids(&self) -> impl ExactSizeIterator<Item = &str> {
self.inner.ids.iter().map(AsRef::as_ref)
}
pub fn iter(&self) -> impl Iterator<Item = (&str, &PreparedQuery)> {
self.inner
.ids
.iter()
.filter_map(|id| self.inner.queries.get(id).map(|query| (id.as_ref(), query)))
}
pub async fn execute(
&self,
id: &str,
variables: Option<&Object>,
options: &ExecutionOptions,
) -> Option<Response> {
let query = self.get(id)?;
Some(query.execute(variables, options).await)
}
}