8000 [Cache] Prevent stampede at warmup using flock() · symfony/symfony@7c8dafa · GitHub
[go: up one dir, main page]

Skip to content

Commit 7c8dafa

Browse files
[Cache] Prevent stampede at warmup using flock()
1 parent b560883 commit 7c8dafa

File tree

3 files changed

+158
-18
lines changed

3 files changed

+158
-18
lines changed
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\Cache;
13+
14+
use Psr\Cache\CacheItemInterface;
15+
use Psr\Cache\CacheItemPoolInterface;
16+
17+
/**
18+
* LockRegistry is used internally by existing adapters to protect against cache stampede.
19+
*
20+
* It does so by wrapping the computation of items in a pool of locks.
21+
* Foreach each apps, there can be at most 20 concurrent processes that
22+
* compute items at the same time and only one per cache-key.
23+
*
24+
* @author Nicolas Grekas <p@tchwork.com>
25+
*/
26+
class LockRegistry
27+
{
28+
private static $save;
29+
private static $openedFiles = array();
30+
private static $lockedFiles = array();
31+
private static $files = array(
32+
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'AbstractAdapter.php',
33+
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'AdapterInterface.php',
34+
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'ApcuAdapter.php',
35+
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'ArrayAdapter.php',
36+
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'ChainAdapter.php',
37+
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'DoctrineAdapter.php',
38+
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'FilesystemAdapter.php',
39+
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'MemcachedAdapter.php',
40+
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'NullAdapter.php',
41+
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'PdoAdapter.php',
42+
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'PhpArrayAdapter.php',
43+
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'PhpFilesAdapter.php',
44+
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'ProxyAdapter.php',
45+
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'RedisAdapter.php',
46+
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'SimpleCacheAdapter.php',
47+
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'TagAwareAdapter.php',
48+
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'TagAwareAdapterInterface.php',
49+
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'TraceableAdapter.php',
50+
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'TraceableTagAwareAdapter.php',
51+
);
52+
53+
/**
54+
* Defines a set of existing files that will be used as keys to acquire locks.
55+
*
56+
* @return array The previously defined set of files
57+
*/
58+
public static function setFiles(array $files): array
59+
{
60+
$previousFiles = self::$files;
61+
self::$files = $files;
62+
63+
foreach (self::$openedFiles as $k => $file) {
64+
flock($file, LOCK_UN);
65+
fclose($file);
66+
}
67+
self::$openedFiles = self::$lockedFiles = array();
68+
69+
return $previousFiles;
70+
}
71+
72+
/**
73+
* @internal
74+
*/
75+
public static function save(string $key, CacheItemPoolInterface $pool, CacheItemInterface $item, callable $callback, float $startTime, &$value): bool
76+
{
77+
self::$save = self::$save ?? \Closure::bind(
78+
function (CacheItemPoolInterface $pool, CacheItemInterface $item, $value, float $startTime) {
79+
if ($item instanceof CacheItem && $startTime && $item->expiry > $endTime = microtime(true)) {
80+
$item->newMetadata[CacheItem::METADATA_EXPIRY] = $item->expiry;
81+
$item->newMetadata[CacheItem::METADATA_CTIME] = 1000 * (int) ($endTime - $startTime);
82+
}
83+
$pool->save($item->set($value));
84+
85+
return $value;
86+
},
87+
null,
88+
CacheItem::class
89+
);
90+
91+
$key = self::$files ? crc32($key) % \count(self::$files) : -1;
92+
93+
if ($key < 0 || (self::$lockedFiles[$key] ?? false) || !$lock = self::open($key)) {
94+
$value = (self::$save)($pool, $item, $callback($item), $startTime);
95+
96+
return true;
97+
}
98+
99+
try {
100+
// race to get the lock in non-blocking mode
101+
if (flock($lock, LOCK_EX | LOCK_NB)) {
102+
self::$lockedFiles[$key] = true;
103+
$value = (self::$save)($pool, $item, $callback($item), $startTime);
104+
105+
return true;
106+
}
107+
// if we failed the race, retry locking in blocking mode to wait for the winner
108+
flock($lock, LOCK_SH);
109+
} finally {
110+
flock($lock, LOCK_UN);
111+
self::$lockedFiles[$key] = false;
112+
}
113+
114+
return false;
115+
}
116+
117+
private static function open(int $key)
118+
{
119+
if ($h = self::$openedFiles[$key] ?? null) {
120+
return $h;
121+
}
122+
if ($h = fopen(self::$files[$key], 'rb')) {
123+
return self::$openedFiles[$key] = $h;
124+
}
125+
}
126+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\Cache\Tests;
13+
14+
use PHPUnit\Framework\TestCase;
15+
use Symfony\Component\Cache\LockRegistry;
16+
17+
class LockRegistryTest extends TestCase
18+
{
19+
public function testFiles()
20+
{
21+
$lockFiles = LockRegistry::setFiles(array());
22+
LockRegistry::setFiles($lockFiles);
23+
$expected = array_map('realpath', glob(__DIR__.'/../Adapter/*'));
24+
$this->assertSame($expected, $lockFiles);
25+
}
26+
}

src/Symfony/Component/Cache/Traits/GetTrait.php

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@
1111

1212
namespace Symfony\Component\Cache\Traits;
1313

14-
use Psr\Cache\CacheItemInterface;
1514
use Psr\Cache\CacheItemPoolInterface;
1615
use Symfony\Component\Cache\CacheItem;
16+
use Symfony\Component\Cache\LockRegistry;
1717

1818
/**
1919
* An implementation for CacheInterface that provides stampede protection via probabilistic early expiration.
@@ -36,6 +36,7 @@ public function get(string $key, callable $callback, float $beta = null)
3636

3737
private function doGet(CacheItemPoolInterface $pool, string $key, callable $callback, float $beta)
3838
{
39+
retry:
3940
$t = 0;
4041
$item = $pool->getItem($key);
4142
$recompute = !$item->isHit() || INF === $beta;
@@ -63,24 +64,11 @@ private function doGet(CacheItemPoolInterface $pool, string $key, callable $call
6364
return $item->get();
6465
}
6566

66-
static $save = null;
67-
68-
if (null === $save) {
69-
$save = \Closure::bind(
70-
function (CacheItemPoolInterface $pool, CacheItemInterface $item, $value, float $startTime) {
71-
if ($item instanceof CacheItem && $startTime && $item->expiry > $endTime = microtime(true)) {
72-
$item->newMetadata[CacheItem::METADATA_EXPIRY] = $item->expiry;
73-
$item->newMetadata[CacheItem::METADATA_CTIME] = 1000 * (int) ($endTime - $startTime);
74-
}
75-
$pool->save($item->set($value));
76-
77-
return $value;
78-
},
79-
null,
80-
CacheItem::class
81-
);
67+
if (!LockRegistry::save($key, $pool, $item, $callback, $t, $value)) {
68+
$beta = 0;
69+
goto retry;
8270
}
8371

84-
return $save($pool, $item, $callback($item), $t);
72+
return $value;
8573
}
8674
}

0 commit comments

Comments
 (0)
0