-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathQueryCachingMiddleware.php
158 lines (140 loc) · 4.65 KB
/
QueryCachingMiddleware.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
<?php
namespace SilverStripe\GraphQL\Middleware;
use GraphQL\Executor\ExecutionResult;
use Psr\SimpleCache\CacheInterface;
use Psr\SimpleCache\InvalidArgumentException;
use SilverStripe\Core\Flushable;
use SilverStripe\Core\Injector\Injectable;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\GraphQL\Extensions\QueryRecorderExtension;
use SilverStripe\GraphQL\QueryHandler\QueryHandlerInterface;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\FieldType\DBDatetime;
use Exception;
use GraphQL\Type\Schema;
/**
* Enables graphql responses to be cached.
* Internally uses QueryRecorderExtension to determine which records are queried in order to generate given responses.
*
* CAUTION: Experimental
*
* @internal
*/
class QueryCachingMiddleware implements QueryMiddleware, Flushable
{
use Injectable;
/**
* @var CacheInterface
*/
protected $cache;
/**
* @inheritDoc
*/
public function process(Schema $schema, string $query, array $context, array $vars, callable $next)
{
if (!DataObject::singleton()->hasExtension(QueryRecorderExtension::class)) {
throw new Exception(sprintf(
'You must apply the %s extension to the %s in order to use the %s middleware',
QueryRecorderExtension::class,
DataObject::class,
__CLASS__
));
}
$vars = $vars['vars'] ?? [];
$key = $this->generateCacheKey($query, $vars);
// Get successful cache response
$response = $this->getCachedResponse($key);
if ($response) {
return $response;
}
// Closure begins / ends recording of classes queried by DataQuery.
// ClassSpyExtension is added to DataQuery via yml
$spy = QueryRecorderExtension::singleton();
list($classesUsed, $response) = $spy->recordClasses(function () use ($schema, $query, $context, $vars, $next) {
return $next($schema, $query, $context, $vars);
});
// Save freshly generated response
$this->storeCache($key, $response, $classesUsed);
return $response;
}
/**
* @return CacheInterface
*/
public function getCache(): CacheInterface
{
return $this->cache;
}
public function setCache(CacheInterface $cache): self
{
$this->cache = $cache;
return $this;
}
/**
* Generate cache key
*/
protected function generateCacheKey(string $query, array $vars): string
{
return md5(var_export(
[
'query' => $query,
'params' => $vars
],
true
) ?? '');
}
/**
* Get and validate cached response.
*
* Note: Cached responses can only be returned in array format, not object format.
* @throws InvalidArgumentException
*/
protected function getCachedResponse(string $key): ?array
{
// Initially check if the cached value exists at all
$cache = $this->getCache();
$cached = $cache->get($key);
if (!isset($cached)) {
return null;
}
// On cache success validate against cached classes
foreach ($cached['classes'] as $class) {
// Note: Could combine these clases into a UNION to cut down on extravagant queries
// Todo: We can get last-deleted/modified as well for versioned records
$lastEditedDate = DataObject::get($class)->max('LastEdited');
if (strtotime($lastEditedDate ?? '') > strtotime($cached['date'] ?? '')) {
// class modified, fail validation of cache
return null;
}
}
// On cache success + validation
return $cached['response'];
}
/**
* Send a successful response to the cache
*
* @param ExecutionResult|array $response
* @throws InvalidArgumentException
*/
protected function storeCache(string $key, $response, array $classesUsed): void
{
// Ensure we store serialisable version of result
if ($response instanceof ExecutionResult) {
$handler = Injector::inst()->get(QueryHandlerInterface::class);
$response = $handler->serialiseResult($response);
}
// Don't store an error response
$errors = $response['errors'] ?? [];
if (!empty($errors)) {
return;
}
$this->getCache()->set($key, [
'classes' => $classesUsed,
'response' => $response,
'date' => DBDatetime::now()->getValue()
]);
}
public static function flush()
{
static::singleton()->getCache()->clear();
}
}