Skip to content

graphql: added caching for validation phase #3188

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 21 additions & 7 deletions graphql/src/execution/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ use graph::data::graphql::DocumentExt as _;
use graph::data::value::Object;
use graphql_parser::Pos;
use graphql_tools::validation::rules::*;
use graphql_tools::validation::utils::ValidationError;
use graphql_tools::validation::validate::{validate, ValidationPlan};
use lazy_static::lazy_static;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::hash::{Hash, Hasher};
use std::iter::FromIterator;
use std::sync::Arc;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Instant;
use std::{collections::hash_map::DefaultHasher, convert::TryFrom};

Expand All @@ -23,6 +24,11 @@ use crate::schema::ast::{self as sast};
use crate::values::coercion;
use crate::{execution::get_field, schema::api::ErrorPolicy};

lazy_static! {
static ref GRAPHQL_VALIDATION_CACHE: Mutex<HashMap<u64, Vec<ValidationError>>> =
Mutex::new(HashMap::<u64, Vec<ValidationError>>::new());
}

lazy_static! {
static ref GRAPHQL_VALIDATION_PLAN: ValidationPlan = ValidationPlan::from(
if std::env::var("ENABLE_GRAPHQL_VALIDATIONS").ok().is_none() {
Expand Down Expand Up @@ -145,17 +151,25 @@ impl Query {
max_complexity: Option<u64>,
max_depth: u8,
) -> Result<Arc<Self>, Vec<QueryExecutionError>> {
let validation_errors = validate(
&schema.document(),
&query.document,
&GRAPHQL_VALIDATION_PLAN,
);
let mut validation_cache = GRAPHQL_VALIDATION_CACHE
.lock()
.unwrap_or_else(PoisonError::into_inner);
let validation_errors = validation_cache.entry(query.shape_hash).or_insert_with(|| {
validate(
&schema.document(),
&query.document,
&GRAPHQL_VALIDATION_PLAN,
)
});

if validation_errors.len() > 0 {
return Err(validation_errors
.into_iter()
.map(|e| {
QueryExecutionError::ValidationError(e.locations.first().cloned(), e.message)
QueryExecutionError::ValidationError(
e.locations.first().cloned(),
e.message.clone(),
)
})
.collect());
}
Expand Down