async-graphql/src/validation/mod.rs

106 lines
3.4 KiB
Rust
Raw Normal View History

2020-09-06 05:38:31 +00:00
#[cfg(test)]
#[macro_use]
mod test_harness;
2020-03-25 03:39:28 +00:00
mod rules;
mod suggestion;
2020-03-25 03:39:28 +00:00
mod utils;
mod visitor;
2020-03-25 07:07:16 +00:00
mod visitors;
2020-03-25 03:39:28 +00:00
use crate::parser::types::ExecutableDocument;
2020-03-08 12:35:36 +00:00
use crate::registry::Registry;
Rework errors This completely overhauls the error system used in async-graphql. - `Error` has been renamed to `ServerError` and `FieldError` has been renamed to just `Error`. This is because `FieldError` is by far the most common error that users will have to use so it makes sense to use the most obvious error name. Also, the current name didn't make sense as it was used for things other than field errors, such as the data callback for websockets. - `ServerError` has been made completely opaque. Before it was an enum of all the possible errors, but now it just contains an error message, the locations, the path and extensions. It is a shame that we lose information, it makes more sense as _conceptually_ GraphQL does not provide that information. It also frees us to change the internals of async-graphql a lot more. - The path of errors is no longer an opaque JSON value but a regular type, `Vec<PathSegment>`. The type duplication of `PathSegment` and `QueryPathSegment` is unfortunate, I plan to work on this in the future. - Now that `ServerError` is opaque, `RuleError` has been removed from the public API, making it simpler. - Additionally `QueryError` has been completely removed. Instead the error messages are constructed ad-hoc; I took care to never repeat an error message. - Instead of constructing field-not-found errors inside the implementations of field resolvers they now return `Option`s, where a `None` value is representative of the field not being found. - As an unfortunate consequence of the last change, self-referential types based on the output of a subscription resolver can no longer be created. This does not mean anything for users, but causes lifetime issues in the implementation of merged objects. I fixed it with a bit of a hack, but this'll have to be looked into further. - `InputValueError` now has a generic parameter - it's kind of weird but it's necessary for ergonomics. It also improves error messages. - The `ErrorExtensions` trait has been removed. I didn't think the `extend` method was necessary since `From` impls exist. But the ergonomics are still there with a new trait `ExtendError`, which is implemented for both errors and results. - `Response` now supports serializing multiple errors. This allows for nice things like having multiple validation errors not be awkwardly shoved into a single error. - When an error occurs in execution, data is sent as `null`. This is slightly more compliant with the spec but the algorithm described in <https://spec.graphql.org/June2018/#sec-Errors-and-Non-Nullability> has yet to be implemented.
2020-09-29 19:06:44 +00:00
use crate::{CacheControl, ServerError, Variables};
2020-12-18 06:59:37 +00:00
pub use visitor::VisitorContext;
2020-12-18 15:58:03 +00:00
use visitor::{visit, VisitorNil};
2020-03-08 12:35:36 +00:00
2020-12-18 15:58:03 +00:00
/// Validation results.
2021-04-04 04:05:54 +00:00
#[derive(Debug, Copy, Clone)]
2020-12-18 15:58:03 +00:00
pub struct ValidationResult {
/// Cache control
2020-03-25 07:07:16 +00:00
pub cache_control: CacheControl,
2020-12-18 15:58:03 +00:00
/// Query complexity
2020-03-25 07:07:16 +00:00
pub complexity: usize,
2020-12-18 15:58:03 +00:00
/// Query depth
2020-03-25 07:07:16 +00:00
pub depth: usize,
}
2020-04-06 11:57:21 +00:00
/// Validation mode
#[derive(Copy, Clone, Debug)]
pub enum ValidationMode {
/// Execute all validation rules.
Strict,
/// The executor itself also has error handling, so it can improve performance, but it can lose some error messages.
Fast,
}
pub fn check_rules(
registry: &Registry,
doc: &ExecutableDocument,
variables: Option<&Variables>,
2020-04-06 11:57:21 +00:00
mode: ValidationMode,
2020-12-18 15:58:03 +00:00
) -> Result<ValidationResult, Vec<ServerError>> {
let mut ctx = VisitorContext::new(registry, doc, variables);
2020-03-24 10:54:22 +00:00
let mut cache_control = CacheControl::default();
2020-03-25 07:07:16 +00:00
let mut complexity = 0;
let mut depth = 0;
2020-04-06 11:57:21 +00:00
match mode {
ValidationMode::Strict => {
let mut visitor = VisitorNil
.with(rules::ArgumentsOfCorrectType::default())
.with(rules::DefaultValuesOfCorrectType)
.with(rules::FieldsOnCorrectType)
.with(rules::FragmentsOnCompositeTypes)
.with(rules::KnownArgumentNames::default())
.with(rules::NoFragmentCycles::default())
.with(rules::KnownFragmentNames)
.with(rules::KnownTypeNames)
.with(rules::NoUndefinedVariables::default())
.with(rules::NoUnusedFragments::default())
.with(rules::NoUnusedVariables::default())
.with(rules::UniqueArgumentNames::default())
.with(rules::UniqueVariableNames::default())
.with(rules::VariablesAreInputTypes)
.with(rules::VariableInAllowedPosition::default())
.with(rules::ScalarLeafs)
.with(rules::PossibleFragmentSpreads::default())
.with(rules::ProvidedNonNullArguments)
.with(rules::KnownDirectives::default())
.with(rules::OverlappingFieldsCanBeMerged)
.with(rules::UploadFile)
.with(visitors::CacheControlCalculate {
cache_control: &mut cache_control,
})
2020-12-18 06:59:37 +00:00
.with(visitors::ComplexityCalculate::new(&mut complexity))
2020-04-06 11:57:21 +00:00
.with(visitors::DepthCalculate::new(&mut depth));
visit(&mut visitor, &mut ctx, doc);
}
ValidationMode::Fast => {
let mut visitor = VisitorNil
.with(rules::NoFragmentCycles::default())
.with(rules::UploadFile)
.with(visitors::CacheControlCalculate {
cache_control: &mut cache_control,
})
2020-12-18 06:59:37 +00:00
.with(visitors::ComplexityCalculate::new(&mut complexity))
2020-04-06 11:57:21 +00:00
.with(visitors::DepthCalculate::new(&mut depth));
visit(&mut visitor, &mut ctx, doc);
}
}
2020-03-08 12:35:36 +00:00
if !ctx.errors.is_empty() {
Rework errors This completely overhauls the error system used in async-graphql. - `Error` has been renamed to `ServerError` and `FieldError` has been renamed to just `Error`. This is because `FieldError` is by far the most common error that users will have to use so it makes sense to use the most obvious error name. Also, the current name didn't make sense as it was used for things other than field errors, such as the data callback for websockets. - `ServerError` has been made completely opaque. Before it was an enum of all the possible errors, but now it just contains an error message, the locations, the path and extensions. It is a shame that we lose information, it makes more sense as _conceptually_ GraphQL does not provide that information. It also frees us to change the internals of async-graphql a lot more. - The path of errors is no longer an opaque JSON value but a regular type, `Vec<PathSegment>`. The type duplication of `PathSegment` and `QueryPathSegment` is unfortunate, I plan to work on this in the future. - Now that `ServerError` is opaque, `RuleError` has been removed from the public API, making it simpler. - Additionally `QueryError` has been completely removed. Instead the error messages are constructed ad-hoc; I took care to never repeat an error message. - Instead of constructing field-not-found errors inside the implementations of field resolvers they now return `Option`s, where a `None` value is representative of the field not being found. - As an unfortunate consequence of the last change, self-referential types based on the output of a subscription resolver can no longer be created. This does not mean anything for users, but causes lifetime issues in the implementation of merged objects. I fixed it with a bit of a hack, but this'll have to be looked into further. - `InputValueError` now has a generic parameter - it's kind of weird but it's necessary for ergonomics. It also improves error messages. - The `ErrorExtensions` trait has been removed. I didn't think the `extend` method was necessary since `From` impls exist. But the ergonomics are still there with a new trait `ExtendError`, which is implemented for both errors and results. - `Response` now supports serializing multiple errors. This allows for nice things like having multiple validation errors not be awkwardly shoved into a single error. - When an error occurs in execution, data is sent as `null`. This is slightly more compliant with the spec but the algorithm described in <https://spec.graphql.org/June2018/#sec-Errors-and-Non-Nullability> has yet to be implemented.
2020-09-29 19:06:44 +00:00
return Err(ctx.errors.into_iter().map(Into::into).collect());
2020-03-08 12:35:36 +00:00
}
Rework errors This completely overhauls the error system used in async-graphql. - `Error` has been renamed to `ServerError` and `FieldError` has been renamed to just `Error`. This is because `FieldError` is by far the most common error that users will have to use so it makes sense to use the most obvious error name. Also, the current name didn't make sense as it was used for things other than field errors, such as the data callback for websockets. - `ServerError` has been made completely opaque. Before it was an enum of all the possible errors, but now it just contains an error message, the locations, the path and extensions. It is a shame that we lose information, it makes more sense as _conceptually_ GraphQL does not provide that information. It also frees us to change the internals of async-graphql a lot more. - The path of errors is no longer an opaque JSON value but a regular type, `Vec<PathSegment>`. The type duplication of `PathSegment` and `QueryPathSegment` is unfortunate, I plan to work on this in the future. - Now that `ServerError` is opaque, `RuleError` has been removed from the public API, making it simpler. - Additionally `QueryError` has been completely removed. Instead the error messages are constructed ad-hoc; I took care to never repeat an error message. - Instead of constructing field-not-found errors inside the implementations of field resolvers they now return `Option`s, where a `None` value is representative of the field not being found. - As an unfortunate consequence of the last change, self-referential types based on the output of a subscription resolver can no longer be created. This does not mean anything for users, but causes lifetime issues in the implementation of merged objects. I fixed it with a bit of a hack, but this'll have to be looked into further. - `InputValueError` now has a generic parameter - it's kind of weird but it's necessary for ergonomics. It also improves error messages. - The `ErrorExtensions` trait has been removed. I didn't think the `extend` method was necessary since `From` impls exist. But the ergonomics are still there with a new trait `ExtendError`, which is implemented for both errors and results. - `Response` now supports serializing multiple errors. This allows for nice things like having multiple validation errors not be awkwardly shoved into a single error. - When an error occurs in execution, data is sent as `null`. This is slightly more compliant with the spec but the algorithm described in <https://spec.graphql.org/June2018/#sec-Errors-and-Non-Nullability> has yet to be implemented.
2020-09-29 19:06:44 +00:00
2020-12-18 15:58:03 +00:00
Ok(ValidationResult {
2020-03-25 07:07:16 +00:00
cache_control,
complexity,
2020-12-18 06:59:37 +00:00
depth,
2020-03-25 07:07:16 +00:00
})
2020-03-08 12:35:36 +00:00
}