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
|
<?php
namespace MediaWiki\Settings\Cache;
use MediaWiki\Settings\SettingsBuilderException;
use MediaWiki\Settings\Source\SettingsIncludeLocator;
use MediaWiki\Settings\Source\SettingsSource;
use Stringable;
use Wikimedia\ObjectCache\BagOStuff;
use Wikimedia\WaitConditionLoop;
/**
* Provides a caching layer for a {@link CacheableSource}.
*
* @newable
* @since 1.38
*/
class CachedSource implements Stringable, SettingsSource, SettingsIncludeLocator {
/**
* Cached source generation timeout (in seconds).
*/
private const TIMEOUT = 2;
/** @var BagOStuff */
private $cache;
/** @var CacheableSource */
private $source;
/**
* Constructs a new CachedSource using an instantiated cache and
* {@link CacheableSource}.
*
* @stable to call
*
* @param BagOStuff $cache
* @param CacheableSource $source
*/
public function __construct(
BagOStuff $cache,
CacheableSource $source
) {
$this->cache = $cache;
$this->source = $source;
}
/**
* Queries cache for source contents and performs loading/caching of the
* source contents on miss.
*
* If the load fails but the source implements {@link
* CacheableSource::allowsStaleLoad()} as <code>true</code>, stale results
* may be returned if still present in the cache store.
*
* @return array
*/
public function load(): array {
$key = $this->cache->makeGlobalKey(
__CLASS__,
$this->source->getHashKey()
);
$result = null;
$loop = new WaitConditionLoop(
function () use ( $key, &$result ) {
$item = $this->cache->get( $key );
if ( $this->isValidHit( $item ) ) {
if ( $this->isExpired( $item ) ) {
// The cached item is stale but use it as a default in
// case of failure if the source allows that
if ( $this->source->allowsStaleLoad() ) {
$result = $item['value'];
}
} else {
$result = $item['value'];
return WaitConditionLoop::CONDITION_REACHED;
}
}
if ( $this->cache->lock( $key, 0, self::TIMEOUT ) ) {
try {
$result = $this->loadAndCache( $key );
} catch ( SettingsBuilderException $e ) {
if ( $result === null ) {
// We have a failure and no stale result to fall
// back on, so throw
throw $e;
}
} finally {
$this->cache->unlock( $key );
}
}
return $result === null
? WaitConditionLoop::CONDITION_CONTINUE
: WaitConditionLoop::CONDITION_REACHED;
},
self::TIMEOUT
);
if ( $loop->invoke() !== WaitConditionLoop::CONDITION_REACHED ) {
throw new SettingsBuilderException(
'Exceeded {timeout}s timeout attempting to load and cache source {source}',
[
'timeout' => self::TIMEOUT,
'source' => $this->source,
]
);
}
// @phan-suppress-next-line PhanTypeMismatchReturn WaitConditionLoop throws or value set
return $result;
}
/**
* Returns the string representation of the encapsulated source.
*
* @return string
*/
public function __toString(): string {
return $this->source->__toString();
}
/**
* Whether the given cache item is considered a cache hit, in other words:
* - it is not a falsey value
* - it has the correct type and structure for this cache implementation
*
* @param mixed $item Cache item.
*
* @return bool
*/
private function isValidHit( $item ): bool {
return $item &&
is_array( $item ) &&
isset( $item['expiry'] ) &&
isset( $item['generation'] ) &&
isset( $item['value'] );
}
/**
* Whether the given cache item is considered expired, in other words:
* - its expiry timestamp has passed
* - it is deemed to expire early so as to mitigate cache stampedes
*
* @param array $item Cache item.
*
* @return bool
*/
private function isExpired( $item ): bool {
return $item['expiry'] < microtime( true ) ||
$this->expiresEarly( $item, $this->source->getExpiryWeight() );
}
/**
* Decide whether the cached source should be expired early according to a
* probabilistic calculation that becomes more likely as the normal expiry
* approaches.
*
* In other words, we're going to pretend we're a bit further into the
* future than we are so that we might expire and regenerate the cached
* settings before other threads attempt to the do the same. The number of
* threads that will pretend to be far into the future (and thus will
* concurrently reload/cache the settings) will most probably be so
* exponentially fewer than the number of threads pretending to be near
* into the future that it will approach optimal stampede protection
* without the use of an exclusive lock.
*
* @param array $item Cached source with expiry metadata.
* @param float $weight Coefficient used to increase/decrease the
* likelihood of early expiration.
*
* @link https://en.wikipedia.org/wiki/Cache_stampede#Probabilistic_early_expiration
*
* @return bool
*/
private function expiresEarly( array $item, float $weight ): bool {
if ( $weight == 0 || !isset( $item['expiry'] ) || !isset( $item['generation'] ) ) {
return false;
}
// Calculate a negative expiry offset using generation time, expiry
// weight, and a random number within the exponentially distributed
// range of log n where n: (0, 1] (which is always negative)
$expiryOffset =
$item['generation'] *
$weight *
log( random_int( 1, PHP_INT_MAX ) / PHP_INT_MAX );
return ( $item['expiry'] + $expiryOffset ) <= microtime( true );
}
/**
* Loads the source and caches the result.
*
* @param string $key
*
* @return array
*/
private function loadAndCache( string $key ): array {
$ttl =
$this->source->allowsStaleLoad()
? BagOStuff::TTL_INDEFINITE
: $this->source->getExpiryTtl();
$item = $this->loadWithMetadata();
$this->cache->set( $key, $item, $ttl );
return $item['value'];
}
/**
* Wraps cached source with the metadata needed to perform probabilistic
* early expiration to help mitigate cache stampedes.
*
* @return array
*/
private function loadWithMetadata(): array {
$start = microtime( true );
$value = $this->source->load();
$finish = microtime( true );
return [
'value' => $value,
'expiry' => $start + $this->source->getExpiryTtl(),
'generation' => $finish - $start,
];
}
public function locateInclude( string $location ): string {
if ( $this->source instanceof SettingsIncludeLocator ) {
return $this->source->locateInclude( $location );
} else {
// Just return the location as-is
return $location;
}
}
}
|