-
Notifications
You must be signed in to change notification settings - Fork 5
/
Psr6Store.php
617 lines (521 loc) · 18.4 KB
/
Psr6Store.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
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
<?php
/*
* This file is part of the toflar/psr6-symfony-http-cache-store package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Yanick Witschi <yanick.witschi@terminal42.ch>
*/
namespace Toflar\Psr6HttpCacheStore;
use Psr\Cache\InvalidArgumentException;
use Symfony\Component\Cache\Adapter\AdapterInterface;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Adapter\FilesystemTagAwareAdapter;
use Symfony\Component\Cache\Adapter\TagAwareAdapter;
use Symfony\Component\Cache\Adapter\TagAwareAdapterInterface;
use Symfony\Component\Cache\PruneableInterface;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Lock\BlockingStoreInterface;
use Symfony\Component\Lock\Exception\LockReleasingException;
use Symfony\Component\Lock\Factory;
use Symfony\Component\Lock\LockFactory;
use Symfony\Component\Lock\LockInterface;
use Symfony\Component\Lock\Store\FlockStore;
use Symfony\Component\Lock\Store\SemaphoreStore;
use Symfony\Component\Lock\StoreInterface as LockStoreInterface;
use Symfony\Component\OptionsResolver\Exception\MissingOptionsException;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Implements a storage for Symfony's HttpCache that supports PSR-6 cache
* back ends, auto-pruning of expired entries on local filesystem and cache
* invalidation by tags.
*
* @author Yanick Witschi <yanick.witschi@terminal42.ch>
*/
class Psr6Store implements Psr6StoreInterface
{
const NON_VARYING_KEY = 'non-varying';
const COUNTER_KEY = 'write-operations-counter';
/**
* @var array
*/
private $options;
/**
* @var TagAwareAdapterInterface
*/
private $cache;
/**
* @var Factory|LockFactory
*/
private $lockFactory;
/**
* @var LockInterface[]
*/
private $locks = [];
/**
* When creating a Psr6Store you can configure a number options.
*
* Either cache_directory or cache and lock_factory are required. If you
* want to set a custom cache / lock_factory, please **read the warning in
* the README first**.
*
* - cache_directory: Path to the cache directory for the default cache
* adapter and lock factory.
*
* - cache: Explicitly specify the cache adapter you want to
* use. Note that if you want to make use of cache
* tagging, this cache must implement the
* Symfony\Component\Cache\Adapter\TagAwareAdapterInterface
*
* Make sure that lock and cache have the same
* scope. *Read the warning in the README!*
*
* Type: Symfony\Component\Cache\Adapter\AdapterInterface
*
* - lock_factory: Explicitly specify the cache adapter you want to
* use. Make sure that lock and cache have the same
* scope. *Read the warning in the README!*
*
* Type: Symfony\Component\Lock\Factory
* Default: Factory with SemaphoreStore if available,
* FlockStore otherwise.
*
* - prune_threshold: Configure the number of write actions until the
* store will prune the expired cache entries. Pass
* 0 to disable automated pruning.
*
* Type: int
* Default: 500
*
* - cache_tags_header: Name of HTTP header containing a comma separated
* list of tags to tag the response with.
*
* Type: string
* Default: Cache-Tags
*/
public function __construct(array $options = [])
{
$resolver = new OptionsResolver();
$resolver->setDefined('cache_directory')
->setAllowedTypes('cache_directory', 'string');
$resolver->setDefault('prune_threshold', 500)
->setAllowedTypes('prune_threshold', 'int');
$resolver->setDefault('cache_tags_header', 'Cache-Tags')
->setAllowedTypes('cache_tags_header', 'string');
$resolver->setDefault('cache', function (Options $options) {
if (!isset($options['cache_directory'])) {
throw new MissingOptionsException('The cache_directory option is required unless you set the cache explicitly');
}
// As of Symfony 4.3+ we can use the optimized FilesystemTagAwareAdapter
if (class_exists(FilesystemTagAwareAdapter::class)) {
return new FilesystemTagAwareAdapter('', 0, $options['cache_directory']);
}
return new TagAwareAdapter(
new FilesystemAdapter('', 0, $options['cache_directory'])
);
})->setAllowedTypes('cache', AdapterInterface::class);
$resolver->setDefault('lock_factory', function (Options $options) {
if (!isset($options['cache_directory'])) {
throw new MissingOptionsException('The cache_directory option is required unless you set the lock_factory explicitly as by default locks are also stored in the configured cache_directory.');
}
$defaultLockStore = $this->getDefaultLockStore($options['cache_directory']);
if (class_exists(LockFactory::class)) {
// Symfony >= 4.4
return new LockFactory($defaultLockStore);
}
// Symfony < 4.4
return new Factory($defaultLockStore);
})->setAllowedTypes('lock_factory', [Factory::class, LockFactory::class]);
$this->options = $resolver->resolve($options);
$this->cache = $this->options['cache'];
$this->lockFactory = $this->options['lock_factory'];
}
/**
* Locates a cached Response for the Request provided.
*
* @param Request $request A Request instance
*
* @return Response|null A Response instance, or null if no cache entry was found
*/
public function lookup(Request $request)
{
$cacheKey = $this->getCacheKey($request);
$item = $this->cache->getItem($cacheKey);
if (!$item->isHit()) {
return null;
}
$entries = $item->get();
foreach ($entries as $varyKeyResponse => $responseData) {
// This can only happen if one entry only
if (self::NON_VARYING_KEY === $varyKeyResponse) {
return $this->restoreResponse($responseData);
}
// Otherwise we have to see if Vary headers match
$varyKeyRequest = $this->getVaryKey(
$responseData['vary'],
$request
);
if ($varyKeyRequest === $varyKeyResponse) {
return $this->restoreResponse($responseData);
}
}
return null;
}
/**
* Writes a cache entry to the store for the given Request and Response.
*
* Existing entries are read and any that match the response are removed. This
* method calls write with the new list of cache entries.
*
* @param Request $request A Request instance
* @param Response $response A Response instance
*
* @return string The key under which the response is stored
*/
public function write(Request $request, Response $response)
{
if (!$response->headers->has('X-Content-Digest')) {
$contentDigest = $this->generateContentDigest($response);
$cacheValue = $this->isBinaryFileResponseContentDigest($contentDigest) ?
$response->getFile()->getPathname() :
$response->getContent();
if (false === $this->saveDeferred($contentDigest, $cacheValue)) {
throw new \RuntimeException('Unable to store the entity.');
}
$response->headers->set('X-Content-Digest', $contentDigest);
if (!$response->headers->has('Transfer-Encoding')) {
$response->headers->set('Content-Length', \strlen($response->getContent()));
}
}
$cacheKey = $this->getCacheKey($request);
$headers = $response->headers->all();
unset($headers['age']);
$item = $this->cache->getItem($cacheKey);
if (!$item->isHit()) {
$entries = [];
} else {
$entries = $item->get();
}
// Add or replace entry with current Vary header key
$entries[$this->getVaryKey($response->getVary(), $request)] = [
'vary' => $response->getVary(),
'headers' => $headers,
'status' => $response->getStatusCode(),
];
// If the response has a Vary header we remove the non-varying entry
if ($response->hasVary()) {
unset($entries[self::NON_VARYING_KEY]);
}
// Tags
$tags = [];
if ($response->headers->has($this->options['cache_tags_header'])) {
// Compatibility with Symfony 3+
$allHeaders = $response->headers->all();
$key = str_replace('_', '-', strtolower($this->options['cache_tags_header']));
$headers = isset($allHeaders[$key]) ? $allHeaders[$key] : [];
foreach ($headers as $header) {
foreach (explode(',', $header) as $tag) {
$tags[] = $tag;
}
}
}
// Prune expired entries on file system if needed
$this->autoPruneExpiredEntries();
$this->saveDeferred($cacheKey, $entries, $response->getMaxAge(), $tags);
$this->cache->commit();
return $cacheKey;
}
/**
* Invalidates all cache entries that match the request.
*
* @param Request $request A Request instance
*/
public function invalidate(Request $request)
{
$cacheKey = $this->getCacheKey($request);
$this->cache->deleteItem($cacheKey);
}
/**
* Locks the cache for a given Request.
*
* @param Request $request A Request instance
*
* @return bool|string true if the lock is acquired, the path to the current lock otherwise
*/
public function lock(Request $request)
{
$cacheKey = $this->getCacheKey($request);
if (isset($this->locks[$cacheKey])) {
return false;
}
$this->locks[$cacheKey] = $this->lockFactory
->createLock($cacheKey);
return $this->locks[$cacheKey]->acquire();
}
/**
* Releases the lock for the given Request.
*
* @param Request $request A Request instance
*
* @return bool False if the lock file does not exist or cannot be unlocked, true otherwise
*/
public function unlock(Request $request)
{
$cacheKey = $this->getCacheKey($request);
if (!isset($this->locks[$cacheKey])) {
return false;
}
try {
$this->locks[$cacheKey]->release();
} catch (LockReleasingException $e) {
return false;
} finally {
unset($this->locks[$cacheKey]);
}
return true;
}
/**
* Returns whether or not a lock exists.
*
* @param Request $request A Request instance
*
* @return bool true if lock exists, false otherwise
*/
public function isLocked(Request $request)
{
$cacheKey = $this->getCacheKey($request);
if (!isset($this->locks[$cacheKey])) {
return false;
}
return $this->locks[$cacheKey]->isAcquired();
}
/**
* Purges data for the given URL.
*
* @param string $url A URL
*
* @return bool true if the URL exists and has been purged, false otherwise
*/
public function purge($url)
{
$cacheKey = $this->getCacheKey(Request::create($url));
return $this->cache->deleteItem($cacheKey);
}
/**
* Release all locks.
*
* {@inheritdoc}
*/
public function cleanup()
{
try {
foreach ($this->locks as $lock) {
$lock->release();
}
} catch (LockReleasingException $e) {
// noop
} finally {
$this->locks = [];
}
}
/**
* The tags are set from the header configured in cache_tags_header.
*
* {@inheritdoc}
*/
public function invalidateTags(array $tags)
{
if (!$this->cache instanceof TagAwareAdapterInterface) {
throw new \RuntimeException('Cannot invalidate tags on a cache
implementation that does not implement the TagAwareAdapterInterface.');
}
try {
return $this->cache->invalidateTags($tags);
} catch (InvalidArgumentException $e) {
return false;
}
}
/**
* {@inheritdoc}
*/
public function prune()
{
if (!$this->cache instanceof PruneableInterface) {
return;
}
// Make sure we do not have multiple pruning processes running
$lock = $this->lockFactory->createLock('prune-lock');
if ($lock->acquire()) {
$this->cache->prune();
$lock->release();
}
}
/**
* {@inheritdoc}
*/
public function clear()
{
// Make sure we do not have multiple pruning processes running
$lock = $this->lockFactory->createLock('clear-lock');
if ($lock->acquire()) {
$this->cache->clear();
$lock->release();
}
}
/**
* @return string
*/
public function getCacheKey(Request $request)
{
// Strip scheme to treat https and http the same
$uri = $request->getUri();
$uri = substr($uri, \strlen($request->getScheme().'://'));
return 'md'.hash('sha256', $uri);
}
/**
* @return string
*/
public function getVaryKey(array $vary, Request $request)
{
if (0 === \count($vary)) {
return self::NON_VARYING_KEY;
}
// Normalize
$vary = array_map('strtolower', $vary);
sort($vary);
$hashData = '';
foreach ($vary as $headerName) {
if ('cookie' === $headerName) {
continue;
}
$hashData .= $headerName.':'.$request->headers->get($headerName);
}
if (\in_array('cookie', $vary, true)) {
$hashData .= 'cookies:';
foreach ($request->cookies->all() as $k => $v) {
$hashData .= $k.'='.$v;
}
}
return hash('sha256', $hashData);
}
/**
* @return string
*/
public function generateContentDigest(Response $response)
{
if ($response instanceof BinaryFileResponse) {
return 'bf'.hash_file('sha256', $response->getFile()->getPathname());
}
return 'en'.hash('sha256', $response->getContent());
}
/**
* Test whether a given digest identifies a BinaryFileResponse.
*
* @param string $digest
*
* @return bool
*/
private function isBinaryFileResponseContentDigest($digest)
{
return 'bf' === substr($digest, 0, 2);
}
/**
* Increases a counter every time an item is stored to the cache and then
* prunes expired cache entries if a configurable threshold is reached.
* This only happens during write operations so cache retrieval is not
* slowed down.
*/
private function autoPruneExpiredEntries()
{
if (0 === $this->options['prune_threshold']) {
return;
}
$item = $this->cache->getItem(self::COUNTER_KEY);
$counter = (int) $item->get();
if ($counter > $this->options['prune_threshold']) {
$this->prune();
$counter = 0;
} else {
++$counter;
}
$item->set($counter);
$this->cache->saveDeferred($item);
}
/**
* @param string $key
* @param string $data
* @param int $expiresAfter
* @param array $tags
*
* @return bool
*/
private function saveDeferred($key, $data, $expiresAfter = null, $tags = [])
{
$item = $this->cache->getItem($key);
$item->set($data);
$item->expiresAfter($expiresAfter);
if (0 !== \count($tags)) {
$item->tag($tags);
}
return $this->cache->saveDeferred($item);
}
/**
* Restores a Response from the cached data.
*
* @param array $cacheData An array containing the cache data
*
* @return Response|null
*/
private function restoreResponse(array $cacheData)
{
if (isset($cacheData['headers']['x-content-digest'][0])) {
$item = $this->cache->getItem($cacheData['headers']['x-content-digest'][0]);
if ($item->isHit()) {
$value = $item->get();
if ($this->isBinaryFileResponseContentDigest($cacheData['headers']['x-content-digest'][0])) {
try {
$file = new File($value);
} catch (FileNotFoundException $e) {
return null;
}
return new BinaryFileResponse(
$file,
$cacheData['status'],
$cacheData['headers']
);
}
return new Response(
$value,
$cacheData['status'],
$cacheData['headers']
);
}
}
return null;
}
/**
* Build and return a default lock factory for when no explicit factory
* was specified.
* The default factory uses the best quality lock store that is available
* on this system.
*
* @param string $cacheDir
*
* @return LockStoreInterface|BlockingStoreInterface
*
* @codeCoverageIgnore Depends on your system.
*/
private function getDefaultLockStore($cacheDir)
{
if (SemaphoreStore::isSupported(false)) {
return new SemaphoreStore();
}
return new FlockStore($cacheDir);
}
}