-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathCacheUrlMappingAspect.php
More file actions
217 lines (186 loc) · 8.19 KB
/
CacheUrlMappingAspect.php
File metadata and controls
217 lines (186 loc) · 8.19 KB
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
<?php
declare(strict_types=1);
namespace Flowpack\DecoupledContentStore\Aspects;
use Flowpack\DecoupledContentStore\Exception;
use Flowpack\DecoupledContentStore\Core\Infrastructure\ContentReleaseLogger;
use Flowpack\DecoupledContentStore\NodeRendering\Dto\DocumentNodeCacheKey;
use Flowpack\DecoupledContentStore\NodeRendering\Dto\DocumentNodeCacheValues;
use Flowpack\DecoupledContentStore\NodeRendering\Extensibility\NodeRenderingExtensionManager;
use Flowpack\DecoupledContentStore\NodeRendering\Render\DocumentRenderer;
use Flowpack\DecoupledContentStore\NodeRendering\Render\RenderExceptionExtractor;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Aop\JoinPointInterface;
use Neos\Fusion\Core\Cache\CacheSegmentParser;
use Neos\Utility\ObjectAccess;
use Neos\ContentRepository\Domain\Model\NodeInterface;
/**
* This aspect creates the root cache entry which maps the URL to the root cache identifier during rendering.
*
* NOTE: This aspect is NOT active during interactive page rendering; but only when a content release is built
* through Batch Rendering (so when {@see DocumentRenderer} has invoked the rendering. This is to keep complexity lower
* and code paths simpler: The system NEVER re-uses content cache entries created by editors while browsing the page; but
* ONLY re-uses content cache entries created by previous Batch Renderings.
*
* @Flow\Aspect
* @Flow\Scope("singleton")
*/
class CacheUrlMappingAspect
{
/**
* are we currently rendering the page from within a Content Release? {@see DocumentRenderer}
*
* @var bool
*/
protected $isActive = false;
/**
* @var null | int
*/
protected $renderTimestamp = null;
/**
* @var array
*/
protected $currentEvaluateContext;
/**
* @var \Neos\Flow\Mvc\Controller\ControllerContext
*/
protected $controllerContext;
/**
* @Flow\Inject
* @var \Neos\Fusion\Core\Cache\ContentCache
*/
protected $contentCache;
/**
* @Flow\Inject
* @var NodeRenderingExtensionManager
*/
protected $nodeRenderingExtensionManager;
/**
* @var \Neos\Cache\Frontend\StringFrontend
*/
protected $contentCacheFrontend;
/**
* @Flow\InjectConfiguration(path="nodeRendering.urlExcludelistRegex")
* @var string|false
*/
protected $urlExcludelistRegex = false;
/**
* @var ContentReleaseLogger
*/
protected $contentReleaseLogger;
/**
* @Flow\Before("method(Neos\Fusion\Core\Cache\RuntimeContentCache->postProcess())")
*/
public function getCurrentEvaluateAndControllerContext(JoinPointInterface $joinPoint)
{
$this->currentEvaluateContext = $joinPoint->getMethodArgument('evaluateContext');
/** @var \Neos\Fusion\Core\Cache\RuntimeContentCache $runtimeContentCache */
$runtimeContentCache = $joinPoint->getProxy();
/** @var \Neos\Fusion\Core\Runtime $runtime */
$runtime = ObjectAccess::getProperty($runtimeContentCache, 'runtime', true);
$this->controllerContext = $runtime->getControllerContext();
}
/**
* @Flow\After("method(Neos\Fusion\Core\Cache\ContentCache->processCacheSegments())")
*/
public function storeRootCacheIdentifier(JoinPointInterface $joinPoint)
{
if (!$this->isActive) {
return;
}
if (!isset($this->currentEvaluateContext['cacheIdentifierValues']['node']) || !$this->currentEvaluateContext['cacheIdentifierValues']['node'] instanceof NodeInterface) {
return;
}
/** @var NodeInterface $node */
$node = $this->currentEvaluateContext['cacheIdentifierValues']['node'];
$url = $this->getCurrentUrl();
$storeCacheEntries = $joinPoint->getMethodArgument('storeCacheEntries');
// Do not create mapping (and check for consistency of root identifier) if storage of entries was disabled (e.g. exception was catched)
if (!$storeCacheEntries) {
$content = $joinPoint->getMethodArgument('content');
$extractedExceptionDto = RenderExceptionExtractor::extractRenderingException($content);
throw new Exception('Cache was disabled for ' . $url . ' with node ' . $node->getContextPath() . ', but no exception was handled by the publishing. This could be caused by a missing publishing aware @exceptionHandler in Fusion.' . ($extractedExceptionDto !== null ? "\nException extracted from output: {$extractedExceptionDto}" : ''), 1539156004);
}
$content = $joinPoint->getMethodArgument('content');
$randomCacheMarker = ObjectAccess::getProperty($this->contentCache, 'randomCacheMarker', true);
$parser = new CacheSegmentParser($content, $randomCacheMarker);
// The last segment is (for now) always the root path (if it's cached)
$segments = $parser->getCacheSegments();
$lastSegment = end($segments);
$rootIdentifier = $lastSegment['identifier'];
$rootTags = explode(',', $lastSegment['metadata']);
$rootTags = $this->sanitizeTags($rootTags);
$logger = $this->contentReleaseLogger;
if ($logger === null) {
throw new \RuntimeException('TODO Logger not found - should never happen');
}
if ($this->urlIsMatchingBlacklist($url)) {
$logger->info(sprintf('Skipping URL %s, because it matches the blacklist %s', $url, $this->urlExcludelistRegex));
return;
}
if ($rootIdentifier === null) {
throw new Exception('Could not find root cache identifier for ' . $url . ', possible rendering error?', 1491394849);
}
$logger->debug('Mapping URL ' . $url . ' to ' . $rootIdentifier . ' with tags ' . implode(', ', $rootTags));
$arguments = $this->getCurrentArguments($node);
// TODO: To make parallel rendering possible, we need to make sure that the cache key also includes the currently rendered workspace, as the node might originate from a base workspace (usually live). See `DocumentNodeCacheKey`.
$rootKey = DocumentNodeCacheKey::fromNodeAndArguments($node, $arguments);
$rootCacheValues = DocumentNodeCacheValues::create($rootIdentifier, $url)
->withMetadata('renderTime', (int)(microtime(true) * 1000) - $this->renderTimestamp);
// allow other document metadata generators here
$rootCacheValues = $this->nodeRenderingExtensionManager->runDocumentMetadataGenerators($node, $arguments, $this->controllerContext, $rootCacheValues);
$this->contentCacheFrontend->set($rootKey->redisKeyName(), json_encode($rootCacheValues), $rootTags);
}
/**
* @return string
*/
protected function getCurrentUrl(): string
{
/** @var \Neos\Flow\Mvc\ActionRequest $actionRequest */
$actionRequest = $this->controllerContext->getRequest();
$httpRequest = $actionRequest->getHttpRequest();
$url = $httpRequest->getUri();
$url = $url->withQuery('');
return (string)$url;
}
/**
* @param NodeInterface $node
*/
protected function getCurrentArguments(NodeInterface $node): array
{
/** @var \Neos\Flow\Mvc\ActionRequest $actionRequest */
$actionRequest = $this->controllerContext->getRequest();
$arguments = $actionRequest->getArguments();
unset($arguments['node']);
return $arguments;
}
/**
* @param array $tags
* @return array
*/
protected function sanitizeTags($tags)
{
foreach ($tags as $key => $value) {
$tags[$key] = strtr($value, '.:', '_-');
}
return $tags;
}
private function urlIsMatchingBlacklist(string $url): bool
{
if (!is_string($this->urlExcludelistRegex)) {
// no blacklist configured; so we allow all URLs.
return false;
}
return preg_match($this->urlExcludelistRegex, $url) === 1;
}
public function beforeDocumentRendering(ContentReleaseLogger $contentReleaseLogger): void
{
$this->isActive = true;
$this->contentReleaseLogger = $contentReleaseLogger;
$this->renderTimestamp = (int)(microtime(true) * 1000);
}
public function afterDocumentRendering(): void
{
$this->isActive = false;
$this->contentReleaseLogger = null;
}
}