Skip to content
Open
Show file tree
Hide file tree
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
50 changes: 50 additions & 0 deletions src/jmh/java/benchmark/SchemaValidatorBenchmark.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package benchmark;

import graphql.schema.GraphQLSchema;
import graphql.schema.idl.FastSchemaGenerator;
import graphql.schema.idl.RuntimeWiring;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import graphql.schema.validation.SchemaValidator;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;

import java.util.concurrent.TimeUnit;

@Warmup(iterations = 2, time = 5)
@Measurement(iterations = 3)
@Fork(2)
@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class SchemaValidatorBenchmark {

@Param({"large-schema-4.graphqls", "large-schema-federated-1.graphqls"})
public String schemaFile;

private GraphQLSchema schema;

@Setup
public void setup() {
String sdl = BenchmarkUtils.loadResource(schemaFile);
schema = new FastSchemaGenerator().makeExecutableSchema(
SchemaGenerator.Options.defaultOptions().withValidation(false),
new SchemaParser().parse(sdl),
RuntimeWiring.MOCKED_WIRING);
}

@Benchmark
public void validateSchema(Blackhole blackhole) {
blackhole.consume(new SchemaValidator().validateSchema(schema));
}
}
Original file line number Diff line number Diff line change
@@ -1,100 +1,53 @@
package graphql.schema.validation;

import graphql.GraphQLContext;
import graphql.Internal;
import graphql.execution.NonNullableValueCoercedAsNullException;
import graphql.execution.ValuesResolver;
import graphql.language.Value;
import graphql.schema.CoercingParseValueException;
import graphql.schema.GraphQLAppliedDirective;
import graphql.schema.GraphQLAppliedDirectiveArgument;
import graphql.schema.GraphQLArgument;
import graphql.schema.GraphQLDirective;
import graphql.schema.GraphQLDirectiveContainer;
import graphql.schema.GraphQLInputType;
import graphql.schema.GraphQLSchema;
import graphql.schema.GraphQLSchemaElement;
import graphql.schema.GraphQLTypeUtil;
import graphql.schema.GraphQLTypeVisitorStub;
import graphql.schema.InputValueWithState;
import graphql.util.TraversalControl;
import graphql.util.TraverserContext;
import graphql.validation.ValidationUtil;

import java.util.Locale;
import org.jspecify.annotations.NullMarked;

import static graphql.schema.GraphQLTypeUtil.isNonNull;
import static java.lang.String.format;

/**
* Schema validation rule ensuring the argument values of applied directives are valid for their types.
*/
@Internal
public class AppliedDirectiveArgumentsAreValid extends GraphQLTypeVisitorStub {
@NullMarked
public class AppliedDirectiveArgumentsAreValid implements SchemaValidationRule {

private ValidationUtil validationUtil = new ValidationUtil();
private final InputValueValidator inputValueValidator;
private final SchemaValidationErrorCollector errors;

public AppliedDirectiveArgumentsAreValid(InputValueValidator inputValueValidator, SchemaValidationErrorCollector errors) {
this.inputValueValidator = inputValueValidator;
this.errors = errors;
}

@Override
public TraversalControl visitGraphQLDirective(GraphQLDirective directive, TraverserContext<GraphQLSchemaElement> context) {
// if there is no parent it means it is just a directive definition and not an applied directive
if (context.getParentNode() != null) {
for (GraphQLArgument graphQLArgument : directive.getArguments()) {
checkArgument(
directive.getName(),
graphQLArgument.getName(),
graphQLArgument.getArgumentValue(),
graphQLArgument.getType(),
context
);
public void checkDirectiveContainer(GraphQLDirectiveContainer container) {
for (GraphQLDirective directive : container.getDirectives()) {
for (GraphQLArgument argument : directive.getArguments()) {
checkArgument(directive.getName(), argument.getName(), argument.getArgumentValue(), argument.getType());
}
}
return TraversalControl.CONTINUE;
}

@Override
public TraversalControl visitGraphQLAppliedDirective(GraphQLAppliedDirective directive, TraverserContext<GraphQLSchemaElement> context) {
// if there is no parent it means it is just a directive definition and not an applied directive
if (context.getParentNode() != null) {
for (GraphQLAppliedDirectiveArgument graphQLArgument : directive.getArguments()) {
checkArgument(
directive.getName(),
graphQLArgument.getName(),
graphQLArgument.getArgumentValue(),
graphQLArgument.getType(),
context
);
for (GraphQLAppliedDirective directive : container.getAppliedDirectives()) {
for (GraphQLAppliedDirectiveArgument argument : directive.getArguments()) {
checkArgument(directive.getName(), argument.getName(), argument.getArgumentValue(), argument.getType());
}
}
return TraversalControl.CONTINUE;
}

private void checkArgument(
String directiveName,
String argumentName,
InputValueWithState argumentValue,
GraphQLInputType argumentType,
TraverserContext<GraphQLSchemaElement> context
) {
GraphQLSchema schema = context.getVarFromParents(GraphQLSchema.class);
SchemaValidationErrorCollector errorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class);
boolean invalid = false;
if (argumentValue.isLiteral() &&
!validationUtil.isValidLiteralValue((Value<?>) argumentValue.getValue(), argumentType, schema, GraphQLContext.getDefault(), Locale.getDefault())) {
invalid = true;
} else if (argumentValue.isExternal() &&
!isValidExternalValue(schema, argumentValue.getValue(), argumentType, GraphQLContext.getDefault(), Locale.getDefault())) {
invalid = true;
} else if (argumentValue.isNotSet() && GraphQLTypeUtil.isNonNull(argumentType)) {
invalid = true;
}
private void checkArgument(String directiveName, String argumentName, InputValueWithState argumentValue, GraphQLInputType argumentType) {
boolean invalid = !inputValueValidator.isValidValue(argumentValue, argumentType)
|| (argumentValue.isNotSet() && isNonNull(argumentType));
if (invalid) {
String message = format("Invalid argument '%s' for applied directive of name '%s'", argumentName, directiveName);
errorCollector.addError(new SchemaValidationError(SchemaValidationErrorType.InvalidAppliedDirectiveArgument, message));
}
}

private boolean isValidExternalValue(GraphQLSchema schema, Object externalValue, GraphQLInputType type, GraphQLContext graphQLContext, Locale locale) {
try {
ValuesResolver.externalValueToInternalValue(schema.getCodeRegistry().getFieldVisibility(), externalValue, type, graphQLContext, locale);
return true;
} catch (CoercingParseValueException | NonNullableValueCoercedAsNullException e) {
return false;
errors.addError(new SchemaValidationError(SchemaValidationErrorType.InvalidAppliedDirectiveArgument,
format("Invalid argument '%s' for applied directive of name '%s'", argumentName, directiveName)));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,56 +4,48 @@
import graphql.schema.GraphQLDirective;
import graphql.schema.GraphQLDirectiveContainer;
import graphql.schema.GraphQLSchema;
import graphql.schema.GraphQLSchemaElement;
import graphql.schema.GraphQLTypeVisitorStub;
import graphql.util.TraversalControl;
import graphql.util.TraverserContext;
import org.jspecify.annotations.NullMarked;

import java.util.List;
import java.util.Map;

import static graphql.schema.validation.SchemaValidationErrorType.InvalidAppliedDirective;
import static java.lang.String.format;

/**
* Schema validation rule ensuring applied directives are defined in the schema and that non repeatable
* directives are applied at most once.
*/
@Internal
public class AppliedDirectivesAreValid extends GraphQLTypeVisitorStub {
@NullMarked
public class AppliedDirectivesAreValid implements SchemaValidationRule {

@Override
protected TraversalControl visitGraphQLType(GraphQLSchemaElement node, TraverserContext<GraphQLSchemaElement> context) {
SchemaValidationErrorCollector collector = context.getVarFromParents(SchemaValidationErrorCollector.class);
GraphQLSchema schema = context.getVarFromParents(GraphQLSchema.class);
if (node instanceof GraphQLDirectiveContainer) {
GraphQLDirectiveContainer directiveContainer = (GraphQLDirectiveContainer) node;
for (Map.Entry<String, List<GraphQLDirective>> entry : directiveContainer.getAllDirectivesByName().entrySet()) {
String directiveName = entry.getKey();
GraphQLDirective directiveDef = schema.getDirective(directiveName);
if (directiveDef != null) {
checkNonRepeatable(collector, directiveContainer, directiveDef, entry.getValue());
} else {
addError(collector, format("A definition for directive '%s' could not be found", directiveName));
}
}
}
private final GraphQLSchema schema;
private final SchemaValidationErrorCollector errors;

return TraversalControl.CONTINUE;
public AppliedDirectivesAreValid(GraphQLSchema schema, SchemaValidationErrorCollector errors) {
this.schema = schema;
this.errors = errors;
}

private void checkNonRepeatable(SchemaValidationErrorCollector collector, GraphQLDirectiveContainer directiveContainer, GraphQLDirective directiveDef, List<GraphQLDirective> directives) {
if (directiveDef.isNonRepeatable() && directives.size() > 1) {
addNonRepeatableError(collector, directiveContainer, directiveDef.getName(), directives.size());
@Override
public void checkDirectiveContainer(GraphQLDirectiveContainer container) {
Map<String, List<GraphQLDirective>> directivesByName = container.getAllDirectivesByName();
if (directivesByName.isEmpty()) {
return;
}
for (Map.Entry<String, List<GraphQLDirective>> entry : directivesByName.entrySet()) {
GraphQLDirective directiveDef = schema.getDirective(entry.getKey());
if (directiveDef == null) {
addError(SchemaValidationErrorType.InvalidAppliedDirective, format("A definition for directive '%s' could not be found", entry.getKey()));
} else if (directiveDef.isNonRepeatable() && entry.getValue().size() > 1) {
addError(SchemaValidationErrorType.InvalidAppliedDirective,
format("The directive '%s' on the '%s' called '%s' is a non repeatable directive but has been applied %d times",
directiveDef.getName(), container.getClass().getSimpleName(), container.getName(), entry.getValue().size()));
}
}
}

private void addNonRepeatableError(SchemaValidationErrorCollector collector, GraphQLDirectiveContainer directiveContainer, String name, int howMany) {
addError(collector, format("The directive '%s' on the '%s' called '%s' is a non repeatable directive but has been applied %d times",
name,
directiveContainer.getClass().getSimpleName(),
directiveContainer.getName(),
howMany));
}

private void addError(SchemaValidationErrorCollector collector, String message) {
collector.addError(new SchemaValidationError(InvalidAppliedDirective, message));
private void addError(SchemaValidationErrorType errorType, String message) {
errors.addError(new SchemaValidationError(errorType, message));
}

}
88 changes: 24 additions & 64 deletions src/main/java/graphql/schema/validation/DefaultValuesAreValid.java
Original file line number Diff line number Diff line change
@@ -1,91 +1,51 @@
package graphql.schema.validation;

import graphql.GraphQLContext;
import graphql.execution.NonNullableValueCoercedAsNullException;
import graphql.execution.ValuesResolver;
import graphql.language.Value;
import graphql.schema.CoercingParseValueException;
import graphql.Internal;
import graphql.schema.GraphQLArgument;
import graphql.schema.GraphQLInputObjectField;
import graphql.schema.GraphQLInputObjectType;
import graphql.schema.GraphQLInputType;
import graphql.schema.GraphQLSchema;
import graphql.schema.GraphQLSchemaElement;
import graphql.schema.GraphQLTypeVisitorStub;
import graphql.schema.InputValueWithState;
import graphql.util.TraversalControl;
import graphql.util.TraverserContext;
import graphql.validation.ValidationUtil;

import java.util.Locale;
import org.jspecify.annotations.NullMarked;

import static graphql.schema.GraphQLTypeUtil.simplePrint;
import static java.lang.String.format;

public class DefaultValuesAreValid extends GraphQLTypeVisitorStub {

private ValidationUtil validationUtil = new ValidationUtil();
/**
* Schema validation rule ensuring argument and input field default values are valid for their types.
*/
@Internal
@NullMarked
public class DefaultValuesAreValid implements SchemaValidationRule {

private final GraphQLContext graphQLContext = GraphQLContext.getDefault();
private final InputValueValidator inputValueValidator;
private final SchemaValidationErrorCollector errors;


@Override
public TraversalControl visitGraphQLInputObjectType(GraphQLInputObjectType node, TraverserContext<GraphQLSchemaElement> context) {
return super.visitGraphQLInputObjectType(node, context);
public DefaultValuesAreValid(InputValueValidator inputValueValidator, SchemaValidationErrorCollector errors) {
this.inputValueValidator = inputValueValidator;
this.errors = errors;
}

@Override
public TraversalControl visitGraphQLInputObjectField(GraphQLInputObjectField inputObjectField, TraverserContext<GraphQLSchemaElement> context) {
if (!inputObjectField.hasSetDefaultValue()) {
return TraversalControl.CONTINUE;
public void checkInputObjectField(GraphQLInputObjectType inputObjectType, GraphQLInputObjectField inputObjectField) {
if (inputObjectField.hasSetDefaultValue()) {
checkDefaultValue(inputObjectField.getInputFieldDefaultValue(), inputObjectField.getType());
}
SchemaValidationErrorCollector errorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class);
GraphQLSchema schema = context.getVarFromParents(GraphQLSchema.class);
InputValueWithState defaultValue = inputObjectField.getInputFieldDefaultValue();
boolean invalid = false;
if (defaultValue.isLiteral() &&
!validationUtil.isValidLiteralValue((Value<?>) defaultValue.getValue(), inputObjectField.getType(), schema, graphQLContext, Locale.getDefault())) {
invalid = true;
} else if (defaultValue.isExternal() &&
!isValidExternalValue(schema, defaultValue.getValue(), inputObjectField.getType(), graphQLContext)) {
invalid = true;
}
if (invalid) {
String message = format("Invalid default value %s for type %s", defaultValue.getValue(), simplePrint(inputObjectField.getType()));
errorCollector.addError(new SchemaValidationError(SchemaValidationErrorType.InvalidDefaultValue, message));
}
return TraversalControl.CONTINUE;
}

@Override
public TraversalControl visitGraphQLArgument(GraphQLArgument argument, TraverserContext<GraphQLSchemaElement> context) {
if (!argument.hasSetDefaultValue()) {
return TraversalControl.CONTINUE;
}
GraphQLSchema schema = context.getVarFromParents(GraphQLSchema.class);
SchemaValidationErrorCollector errorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class);
InputValueWithState defaultValue = argument.getArgumentDefaultValue();
boolean invalid = false;
if (defaultValue.isLiteral() &&
!validationUtil.isValidLiteralValue((Value<?>) defaultValue.getValue(), argument.getType(), schema, graphQLContext, Locale.getDefault())) {
invalid = true;
} else if (defaultValue.isExternal() &&
!isValidExternalValue(schema, defaultValue.getValue(), argument.getType(), graphQLContext)) {
invalid = true;
}
if (invalid) {
String message = format("Invalid default value %s for type %s", defaultValue.getValue(), simplePrint(argument.getType()));
errorCollector.addError(new SchemaValidationError(SchemaValidationErrorType.InvalidDefaultValue, message));
public void checkArgument(GraphQLSchemaElement fieldOrDirective, GraphQLArgument argument) {
if (argument.hasSetDefaultValue()) {
checkDefaultValue(argument.getArgumentDefaultValue(), argument.getType());
}
return TraversalControl.CONTINUE;
}

private boolean isValidExternalValue(GraphQLSchema schema, Object externalValue, GraphQLInputType type, GraphQLContext graphQLContext) {
try {
ValuesResolver.externalValueToInternalValue(schema.getCodeRegistry().getFieldVisibility(), externalValue, type, graphQLContext, Locale.getDefault());
return true;
} catch (CoercingParseValueException | NonNullableValueCoercedAsNullException e) {
return false;
private void checkDefaultValue(InputValueWithState defaultValue, GraphQLInputType type) {
if (inputValueValidator.isValidValue(defaultValue, type)) {
return;
}
errors.addError(new SchemaValidationError(SchemaValidationErrorType.InvalidDefaultValue,
format("Invalid default value %s for type %s", defaultValue.getValue(), simplePrint(type))));
}
}
Loading
Loading