Debian Codegraph @

includes/Settings/Cache/CachedSource.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Settings\Cache;
4
5 use MediaWiki\Settings\SettingsBuilderException;
6 use MediaWiki\Settings\Source\SettingsIncludeLocator;
7 use MediaWiki\Settings\Source\SettingsSource;
8 use Stringable;
9 use Wikimedia\ObjectCache\BagOStuff;
10 use Wikimedia\WaitConditionLoop;
11
12 /**
13 * Provides a caching layer for a {@link CacheableSource}.
14 *
15 * @newable
16 * @since 1.38
17 */
18 class CachedSource implements Stringable, SettingsSource, SettingsIncludeLocator {
19 /**
20 * Cached source generation timeout (in seconds).
21 */
22 private const TIMEOUT = 2;
23
24 /** @var BagOStuff */
25 private $cache;
26
27 /** @var CacheableSource */
28 private $source;
29
30 /**
31 * Constructs a new CachedSource using an instantiated cache and
32 * {@link CacheableSource}.
33 *
34 * @stable to call
35 *
36 * @param BagOStuff $cache
37 * @param CacheableSource $source
38 */
39 public function __construct(
40 BagOStuff $cache,
41 CacheableSource $source
42 ) {
43 $this->cache = $cache;
44 $this->source = $source;
45 }
46
47 /**
48 * Queries cache for source contents and performs loading/caching of the
49 * source contents on miss.
50 *
51 * If the load fails but the source implements {@link
52 * CacheableSource::allowsStaleLoad()} as <code>true</code>, stale results
53 * may be returned if still present in the cache store.
54 *
55 * @return array
56 */
57 public function load(): array {
58 $key = $this->cache->makeGlobalKey(
59 __CLASS__,
60 $this->source->getHashKey()
61 );
62
63 $result = null;
64 $loop = new WaitConditionLoop(
65 function () use ( $key, &$result ) {
66 $item = $this->cache->get( $key );
67
68 if ( $this->isValidHit( $item ) ) {
69 if ( $this->isExpired( $item ) ) {
70 // The cached item is stale but use it as a default in
71 // case of failure if the source allows that
72 if ( $this->source->allowsStaleLoad() ) {
73 $result = $item['value'];
74 }
75 } else {
76 $result = $item['value'];
77 return WaitConditionLoop::CONDITION_REACHED;
78 }
79 }
80
81 if ( $this->cache->lock( $key, 0, self::TIMEOUT ) ) {
82 try {
83 $result = $this->loadAndCache( $key );
84 } catch ( SettingsBuilderException $e ) {
85 if ( $result === null ) {
86 // We have a failure and no stale result to fall
87 // back on, so throw
88 throw $e;
89 }
90 } finally {
91 $this->cache->unlock( $key );
92 }
93 }
94
95 return $result === null
96 ? WaitConditionLoop::CONDITION_CONTINUE
97 : WaitConditionLoop::CONDITION_REACHED;
98 },
99 self::TIMEOUT
100 );
101
102 if ( $loop->invoke() !== WaitConditionLoop::CONDITION_REACHED ) {
103 throw new SettingsBuilderException(
104 'Exceeded {timeout}s timeout attempting to load and cache source {source}',
105 [
106 'timeout' => self::TIMEOUT,
107 'source' => $this->source,
108 ]
109
110 );
111 }
112
113 // @phan-suppress-next-line PhanTypeMismatchReturn WaitConditionLoop throws or value set
114 return $result;
115 }
116
117 /**
118 * Returns the string representation of the encapsulated source.
119 *
120 * @return string
121 */
122 public function __toString(): string {
123 return $this->source->__toString();
124 }
125
126 /**
127 * Whether the given cache item is considered a cache hit, in other words:
128 * - it is not a falsey value
129 * - it has the correct type and structure for this cache implementation
130 *
131 * @param mixed $item Cache item.
132 *
133 * @return bool
134 */
135 private function isValidHit( $item ): bool {
136 return $item &&
137 is_array( $item ) &&
138 isset( $item['expiry'] ) &&
139 isset( $item['generation'] ) &&
140 isset( $item['value'] );
141 }
142
143 /**
144 * Whether the given cache item is considered expired, in other words:
145 * - its expiry timestamp has passed
146 * - it is deemed to expire early so as to mitigate cache stampedes
147 *
148 * @param array $item Cache item.
149 *
150 * @return bool
151 */
152 private function isExpired( $item ): bool {
153 return $item['expiry'] < microtime( true ) ||
154 $this->expiresEarly( $item, $this->source->getExpiryWeight() );
155 }
156
157 /**
158 * Decide whether the cached source should be expired early according to a
159 * probabilistic calculation that becomes more likely as the normal expiry
160 * approaches.
161 *
162 * In other words, we're going to pretend we're a bit further into the
163 * future than we are so that we might expire and regenerate the cached
164 * settings before other threads attempt to the do the same. The number of
165 * threads that will pretend to be far into the future (and thus will
166 * concurrently reload/cache the settings) will most probably be so
167 * exponentially fewer than the number of threads pretending to be near
168 * into the future that it will approach optimal stampede protection
169 * without the use of an exclusive lock.
170 *
171 * @param array $item Cached source with expiry metadata.
172 * @param float $weight Coefficient used to increase/decrease the
173 * likelihood of early expiration.
174 *
175 * @link https://en.wikipedia.org/wiki/Cache_stampede#Probabilistic_early_expiration
176 *
177 * @return bool
178 */
179 private function expiresEarly( array $item, float $weight ): bool {
180 if ( $weight == 0 || !isset( $item['expiry'] ) || !isset( $item['generation'] ) ) {
181 return false;
182 }
183
184 // Calculate a negative expiry offset using generation time, expiry
185 // weight, and a random number within the exponentially distributed
186 // range of log n where n: (0, 1] (which is always negative)
187 $expiryOffset =
188 $item['generation'] *
189 $weight *
190 log( random_int( 1, PHP_INT_MAX ) / PHP_INT_MAX );
191
192 return ( $item['expiry'] + $expiryOffset ) <= microtime( true );
193 }
194
195 /**
196 * Loads the source and caches the result.
197 *
198 * @param string $key
199 *
200 * @return array
201 */
202 private function loadAndCache( string $key ): array {
203 $ttl =
204 $this->source->allowsStaleLoad()
205 ? BagOStuff::TTL_INDEFINITE
206 : $this->source->getExpiryTtl();
207
208 $item = $this->loadWithMetadata();
209 $this->cache->set( $key, $item, $ttl );
210 return $item['value'];
211 }
212
213 /**
214 * Wraps cached source with the metadata needed to perform probabilistic
215 * early expiration to help mitigate cache stampedes.
216 *
217 * @return array
218 */
219 private function loadWithMetadata(): array {
220 $start = microtime( true );
221 $value = $this->source->load();
222 $finish = microtime( true );
223
224 return [
225 'value' => $value,
226 'expiry' => $start + $this->source->getExpiryTtl(),
227 'generation' => $finish - $start,
228 ];
229 }
230
231 public function locateInclude( string $location ): string {
232 if ( $this->source instanceof SettingsIncludeLocator ) {
233 return $this->source->locateInclude( $location );
234 } else {
235 // Just return the location as-is
236 return $location;
237 }
238 }
239 }