Skip to content

Cache result of validation #1730

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

Draft
wants to merge 12 commits into
base: master
Choose a base branch
from
Draft
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
2 changes: 2 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,11 @@
"phpstan/phpstan-strict-rules": "2.0.4",
"phpunit/phpunit": "^9.5 || ^10.5.21 || ^11",
"psr/http-message": "^1 || ^2",
"psr/simple-cache": "^1.0",
"react/http": "^1.6",
"react/promise": "^2.0 || ^3.0",
"rector/rector": "^2.0",
"symfony/cache": "^5.4",
"symfony/polyfill-php81": "^1.23",
"symfony/var-exporter": "^5 || ^6 || ^7",
"thecodingmachine/safe": "^1.3 || ^2 || ^3"
Expand Down
9 changes: 6 additions & 3 deletions docs/class-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,8 @@ static function executeQuery(
?array $variableValues = null,
?string $operationName = null,
?callable $fieldResolver = null,
?array $validationRules = null
?array $validationRules = null,
?GraphQL\Validator\ValidationCache $cache = null
): GraphQL\Executor\ExecutionResult
```

Expand Down Expand Up @@ -98,7 +99,8 @@ static function promiseToExecute(
?array $variableValues = null,
?string $operationName = null,
?callable $fieldResolver = null,
?array $validationRules = null
?array $validationRules = null,
?GraphQL\Validator\ValidationCache $cache = null
): GraphQL\Executor\Promise\Promise
```

Expand Down Expand Up @@ -1811,7 +1813,8 @@ static function validate(
GraphQL\Type\Schema $schema,
GraphQL\Language\AST\DocumentNode $ast,
?array $rules = null,
?GraphQL\Utils\TypeInfo $typeInfo = null
?GraphQL\Utils\TypeInfo $typeInfo = null,
?GraphQL\Validator\ValidationCache $cache = null
): array
```

Expand Down
12 changes: 8 additions & 4 deletions src/GraphQL.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use GraphQL\Validator\DocumentValidator;
use GraphQL\Validator\Rules\QueryComplexity;
use GraphQL\Validator\Rules\ValidationRule;
use GraphQL\Validator\ValidationCache;

/**
* This is the primary facade for fulfilling GraphQL operations.
Expand Down Expand Up @@ -90,7 +91,8 @@ public static function executeQuery(
?array $variableValues = null,
?string $operationName = null,
?callable $fieldResolver = null,
?array $validationRules = null
?array $validationRules = null,
?ValidationCache $cache = null
): ExecutionResult {
$promiseAdapter = new SyncPromiseAdapter();

Expand All @@ -103,7 +105,8 @@ public static function executeQuery(
$variableValues,
$operationName,
$fieldResolver,
$validationRules
$validationRules,
$cache
);

return $promiseAdapter->wait($promise);
Expand Down Expand Up @@ -132,7 +135,8 @@ public static function promiseToExecute(
?array $variableValues = null,
?string $operationName = null,
?callable $fieldResolver = null,
?array $validationRules = null
?array $validationRules = null,
?ValidationCache $cache = null
): Promise {
try {
$documentNode = $source instanceof DocumentNode
Expand All @@ -152,7 +156,7 @@ public static function promiseToExecute(
}
}

$validationErrors = DocumentValidator::validate($schema, $documentNode, $validationRules);
$validationErrors = DocumentValidator::validate($schema, $documentNode, $validationRules, null, $cache);

if ($validationErrors !== []) {
return $promiseAdapter->createFulfilled(
Expand Down
21 changes: 17 additions & 4 deletions src/Validator/DocumentValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,16 +99,22 @@ public static function validate(
Schema $schema,
DocumentNode $ast,
?array $rules = null,
?TypeInfo $typeInfo = null
?TypeInfo $typeInfo = null,
?ValidationCache $cache = null
): array {
$rules ??= static::allRules();
if (isset($cache)) {
$cached = $cache->isValidated($schema, $ast);
if ($cached) {
return [];
}
}

$rules ??= static::allRules();
if ($rules === []) {
return [];
}

$typeInfo ??= new TypeInfo($schema);

$context = new QueryValidationContext($schema, $ast, $typeInfo);

$visitors = [];
Expand All @@ -124,7 +130,14 @@ public static function validate(
)
);

return $context->getErrors();
$errors = $context->getErrors();

// Only cache clean results
if (isset($cache) && count($errors) === 0) {
$cache->markValidated($schema, $ast);
}

return $errors;
}

/**
Expand Down
23 changes: 23 additions & 0 deletions src/Validator/ValidationCache.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php declare(strict_types=1);

namespace GraphQL\Validator;

use GraphQL\GraphQL;
use GraphQL\Language\AST\DocumentNode;
use GraphQL\Type\Schema;

/**
* Implement this interface and pass an instance to GraphQL::executeQuery to cache validation of ASTs. The details
* of how to compute any keys (or whether to validate at all) are left up to you.
*/
interface ValidationCache
{
/**
* Return true if the given schema + AST pair has previously been validated successfully.
* Only successful validations are cached. A return value of false means the pair is either unknown or has not been validated yet.
*/
public function isValidated(Schema $schema, DocumentNode $ast): bool;

/** Cache validation status for this schema/query. */
public function markValidated(Schema $schema, DocumentNode $ast): void;
}
121 changes: 121 additions & 0 deletions tests/Executor/ValidationWithCacheTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
<?php declare(strict_types=1);

namespace GraphQL\Tests\Executor;

use DMS\PHPUnitExtensions\ArraySubset\ArraySubsetAsserts;
use GraphQL\Deferred;
use GraphQL\GraphQL;
use GraphQL\Language\AST\DocumentNode;
use GraphQL\Tests\Executor\TestClasses\Cat;
use GraphQL\Tests\Executor\TestClasses\Dog;
use GraphQL\Tests\PsrValidationCacheAdapter;
use GraphQL\Type\Definition\InterfaceType;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Schema;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\Cache\Psr16Cache;

final class SpyValidationCacheAdapter extends PsrValidationCacheAdapter
{
public int $isValidatedCalls = 0;

public int $markValidatedCalls = 0;

public function isValidated(Schema $schema, DocumentNode $ast): bool
{
++$this->isValidatedCalls;

return parent::isValidated($schema, $ast);
}

public function markValidated(Schema $schema, DocumentNode $ast): void
{
++$this->markValidatedCalls;
parent::markValidated($schema, $ast);
}
}

final class ValidationWithCacheTest extends TestCase
{
use ArraySubsetAsserts;

public function testIsValidationCachedWithAdapter(): void
{
$cache = new SpyValidationCacheAdapter(new Psr16Cache(new ArrayAdapter()));
$petType = new InterfaceType([
'name' => 'Pet',
'fields' => [
'name' => ['type' => Type::string()],
],
]);

$DogType = new ObjectType([
'name' => 'Dog',
'interfaces' => [$petType],
'isTypeOf' => static fn ($obj): Deferred => new Deferred(static fn (): bool => $obj instanceof Dog),
'fields' => [
'name' => ['type' => Type::string()],
'woofs' => ['type' => Type::boolean()],
],
]);

$CatType = new ObjectType([
'name' => 'Cat',
'interfaces' => [$petType],
'isTypeOf' => static fn ($obj): Deferred => new Deferred(static fn (): bool => $obj instanceof Cat),
'fields' => [
'name' => ['type' => Type::string()],
'meows' => ['type' => Type::boolean()],
],
]);

$schema = new Schema([
'query' => new ObjectType([
'name' => 'Query',
'fields' => [
'pets' => [
'type' => Type::listOf($petType),
'resolve' => static fn (): array => [
new Dog('Odie', true),
new Cat('Garfield', false),
],
],
],
]),
'types' => [$CatType, $DogType],
]);

$query = '{
pets {
name
... on Dog {
woofs
}
... on Cat {
meows
}
}
}';

// make the same call twice in a row. We'll then inspect the cache object to count calls
GraphQL::executeQuery($schema, $query, null, null, null, null, null, null, $cache)->toArray();
$result = GraphQL::executeQuery($schema, $query, null, null, null, null, null, null, $cache)->toArray();

// ✅ Assert that validation only happened once
self::assertEquals(2, $cache->isValidatedCalls, 'Should check cache twice');
self::assertEquals(1, $cache->markValidatedCalls, 'Should mark as validated once');

$expected = [
'data' => [
'pets' => [
['name' => 'Odie', 'woofs' => true],
['name' => 'Garfield', 'meows' => false],
],
],
];

self::assertEquals($expected, $result);
}
}
67 changes: 67 additions & 0 deletions tests/PsrValidationCacheAdapter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php declare(strict_types=1);

namespace GraphQL\Tests;

use GraphQL\Language\AST\DocumentNode;
use GraphQL\Type\Schema;
use GraphQL\Utils\SchemaPrinter;
use GraphQL\Validator\ValidationCache;
use Psr\SimpleCache\CacheInterface;
use Symfony\Component\String\Exception\InvalidArgumentException;

class PsrValidationCacheAdapter implements ValidationCache
{
private const KEY_PREFIX = 'gql_validation_';

private int $ttl;

private CacheInterface $cache;

public function __construct(
CacheInterface $cache,
int $ttlSeconds = 300
) {
$this->ttl = $ttlSeconds;
$this->cache = $cache;
}

/** @throws InvalidArgumentException */
public function isValidated(Schema $schema, DocumentNode $ast): bool
{
try {
$key = $this->buildKey($schema, $ast);

/** @phpstan-ignore-next-line */
return $this->cache->has($key);
} catch (\Throwable $e) {
return false;
}
}

/** @throws InvalidArgumentException */
public function markValidated(Schema $schema, DocumentNode $ast): void
{
try {
$key = $this->buildKey($schema, $ast);
/** @phpstan-ignore-next-line */
$this->cache->set($key, true, $this->ttl);
} catch (\Throwable $e) {
// ignore silently
}
}

/**
* @throws \GraphQL\Error\Error
* @throws \GraphQL\Error\InvariantViolation
* @throws \GraphQL\Error\SerializationError
* @throws \JsonException
*/
private function buildKey(Schema $schema, DocumentNode $ast): string
{
// NOTE: You can override this strategy if you want to make schema fingerprinting cheaper
$schemaHash = md5(SchemaPrinter::doPrint($schema));
$astHash = md5($ast->__toString());

return self::KEY_PREFIX . $schemaHash . '_' . $astHash;
}
}