Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
19.41% |
73 / 376 |
|
13.04% |
6 / 46 |
CRAP | |
0.00% |
0 / 1 |
MediumSpecificBagOStuff | |
19.47% |
73 / 375 |
|
13.04% |
6 / 46 |
10823.68 | |
0.00% |
0 / 1 |
__construct | |
80.00% |
4 / 5 |
|
0.00% |
0 / 1 |
3.07 | |||
get | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
trackDuplicateKeys | |
13.33% |
2 / 15 |
|
0.00% |
0 / 1 |
21.27 | |||
doGet | n/a |
0 / 0 |
n/a |
0 / 0 |
0 | |||||
set | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
2 | |||
doSet | n/a |
0 / 0 |
n/a |
0 / 0 |
0 | |||||
delete | |
14.29% |
2 / 14 |
|
0.00% |
0 / 1 |
14.08 | |||
doDelete | n/a |
0 / 0 |
n/a |
0 / 0 |
0 | |||||
add | |
0.00% |
0 / 2 |
|
0.00% |
0 / 1 |
6 | |||
doAdd | n/a |
0 / 0 |
n/a |
0 / 0 |
0 | |||||
merge | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
mergeViaCas | |
0.00% |
0 / 34 |
|
0.00% |
0 / 1 |
90 | |||
cas | |
0.00% |
0 / 8 |
|
0.00% |
0 / 1 |
12 | |||
doCas | |
0.00% |
0 / 20 |
|
0.00% |
0 / 1 |
30 | |||
tokensMatch | |
0.00% |
0 / 6 |
|
0.00% |
0 / 1 |
20 | |||
changeTTL | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
doChangeTTL | |
0.00% |
0 / 12 |
|
0.00% |
0 / 1 |
30 | |||
incrWithInit | |
0.00% |
0 / 3 |
|
0.00% |
0 / 1 |
6 | |||
doIncrWithInit | n/a |
0 / 0 |
n/a |
0 / 0 |
0 | |||||
lock | |
0.00% |
0 / 16 |
|
0.00% |
0 / 1 |
42 | |||
doLock | |
0.00% |
0 / 25 |
|
0.00% |
0 / 1 |
20 | |||
unlock | |
0.00% |
0 / 16 |
|
0.00% |
0 / 1 |
20 | |||
doUnlock | |
0.00% |
0 / 12 |
|
0.00% |
0 / 1 |
12 | |||
makeLockKey | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
deleteObjectsExpiringBefore | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
getMulti | |
0.00% |
0 / 8 |
|
0.00% |
0 / 1 |
20 | |||
doGetMulti | |
0.00% |
0 / 6 |
|
0.00% |
0 / 1 |
12 | |||
setMulti | |
0.00% |
0 / 3 |
|
0.00% |
0 / 1 |
6 | |||
doSetMulti | |
0.00% |
0 / 4 |
|
0.00% |
0 / 1 |
12 | |||
deleteMulti | |
0.00% |
0 / 3 |
|
0.00% |
0 / 1 |
6 | |||
doDeleteMulti | |
0.00% |
0 / 4 |
|
0.00% |
0 / 1 |
12 | |||
changeTTLMulti | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
doChangeTTLMulti | |
0.00% |
0 / 4 |
|
0.00% |
0 / 1 |
12 | |||
resolveSegments | |
13.33% |
2 / 15 |
|
0.00% |
0 / 1 |
14.42 | |||
useSegmentationWrapper | |
30.00% |
3 / 10 |
|
0.00% |
0 / 1 |
29.95 | |||
makeValueOrSegmentList | |
16.00% |
4 / 25 |
|
0.00% |
0 / 1 |
19.82 | |||
isRelativeExpiration | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
2 | |||
getExpirationAsTimestamp | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
3 | |||
getExpirationAsTTL | |
0.00% |
0 / 5 |
|
0.00% |
0 / 1 |
12 | |||
isInteger | |
0.00% |
0 / 6 |
|
0.00% |
0 / 1 |
12 | |||
getQoS | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
getSegmentationSize | |
0.00% |
0 / 2 |
|
0.00% |
0 / 1 |
2 | |||
getSegmentedValueMaxSize | |
0.00% |
0 / 2 |
|
0.00% |
0 / 1 |
2 | |||
getSerialized | |
0.00% |
0 / 2 |
|
0.00% |
0 / 1 |
2 | |||
checkValueSerializability | |
0.00% |
0 / 10 |
|
0.00% |
0 / 1 |
30 | |||
checkIterableMapSerializability | |
0.00% |
0 / 9 |
|
0.00% |
0 / 1 |
30 | |||
serialize | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
6 | |||
unserialize | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
6 | |||
debug | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
determinekeyGroupForStats | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
1 | |||
updateOpStats | |
89.36% |
42 / 47 |
|
0.00% |
0 / 1 |
8.08 |
1 | <?php |
2 | /** |
3 | * This program is free software; you can redistribute it and/or modify |
4 | * it under the terms of the GNU General Public License as published by |
5 | * the Free Software Foundation; either version 2 of the License, or |
6 | * (at your option) any later version. |
7 | * |
8 | * This program is distributed in the hope that it will be useful, |
9 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
11 | * GNU General Public License for more details. |
12 | * |
13 | * You should have received a copy of the GNU General Public License along |
14 | * with this program; if not, write to the Free Software Foundation, Inc., |
15 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
16 | * http://www.gnu.org/copyleft/gpl.html |
17 | * |
18 | * @file |
19 | */ |
20 | namespace Wikimedia\ObjectCache; |
21 | |
22 | use InvalidArgumentException; |
23 | use JsonSerializable; |
24 | use stdClass; |
25 | use Wikimedia\WaitConditionLoop; |
26 | |
27 | /** |
28 | * Helper classs that implements most of BagOStuff for a backend. |
29 | * |
30 | * This should be used by concrete implementations only. Wrapper classes that |
31 | * proxy another BagOStuff should extend and implement BagOStuff directly. |
32 | * |
33 | * @ingroup Cache |
34 | * @since 1.34 |
35 | */ |
36 | abstract class MediumSpecificBagOStuff extends BagOStuff { |
37 | /** @var array<string,array> Map of (key => (class LOCK_* constant => value) */ |
38 | protected $locks = []; |
39 | /** @var int Bytes; chunk size of segmented cache values */ |
40 | protected $segmentationSize; |
41 | /** @var int Bytes; maximum total size of a segmented cache value */ |
42 | protected $segmentedValueMaxSize; |
43 | |
44 | /** @var float Seconds; maximum expected seconds for a lock ping to reach the backend */ |
45 | protected $maxLockSendDelay = 0.05; |
46 | |
47 | /** @var array */ |
48 | private $duplicateKeyLookups = []; |
49 | /** @var bool */ |
50 | private $reportDupes = false; |
51 | /** @var bool */ |
52 | private $dupeTrackScheduled = false; |
53 | |
54 | /** Component to use for key construction of blob segment keys */ |
55 | private const SEGMENT_COMPONENT = 'segment'; |
56 | |
57 | /** Idiom for doGet() to return extra information by reference */ |
58 | protected const PASS_BY_REF = -1; |
59 | |
60 | protected const METRIC_OP_GET = 'get'; |
61 | protected const METRIC_OP_SET = 'set'; |
62 | protected const METRIC_OP_DELETE = 'delete'; |
63 | protected const METRIC_OP_CHANGE_TTL = 'change_ttl'; |
64 | protected const METRIC_OP_ADD = 'add'; |
65 | protected const METRIC_OP_INCR = 'incr'; |
66 | protected const METRIC_OP_DECR = 'decr'; |
67 | protected const METRIC_OP_CAS = 'cas'; |
68 | |
69 | protected const LOCK_RCLASS = 0; |
70 | protected const LOCK_DEPTH = 1; |
71 | protected const LOCK_TIME = 2; |
72 | protected const LOCK_EXPIRY = 3; |
73 | |
74 | /** |
75 | * @see BagOStuff::__construct() |
76 | * Additional $params options include: |
77 | * - logger: Psr\Log\LoggerInterface instance |
78 | * - reportDupes: Whether to emit warning log messages for all keys that were |
79 | * requested more than once (requires an asyncHandler). |
80 | * - segmentationSize: The chunk size, in bytes, of segmented values. The value should |
81 | * not exceed the maximum size of values in the storage backend, as configured by |
82 | * the site administrator. |
83 | * - segmentedValueMaxSize: The maximum total size, in bytes, of segmented values. |
84 | * This should be configured to a reasonable size give the site traffic and the |
85 | * amount of I/O between application and cache servers that the network can handle. |
86 | * |
87 | * @param array $params |
88 | * |
89 | * @phpcs:ignore Generic.Files.LineLength |
90 | * @phan-param array{logger?:\Psr\Log\LoggerInterface,asyncHandler?:callable,reportDupes?:bool,segmentationSize?:int|float,segmentedValueMaxSize?:int} $params |
91 | */ |
92 | public function __construct( array $params = [] ) { |
93 | parent::__construct( $params ); |
94 | |
95 | if ( !empty( $params['reportDupes'] ) && $this->asyncHandler ) { |
96 | $this->reportDupes = true; |
97 | } |
98 | |
99 | // Default to 8MiB if segmentationSize is not set |
100 | $this->segmentationSize = $params['segmentationSize'] ?? 8_388_608; |
101 | // Default to 64MiB if segmentedValueMaxSize is not set |
102 | $this->segmentedValueMaxSize = $params['segmentedValueMaxSize'] ?? 67_108_864; |
103 | } |
104 | |
105 | /** |
106 | * Get an item with the given key |
107 | * |
108 | * If the key includes a deterministic input hash (e.g. the key can only have |
109 | * the correct value) or complete staleness checks are handled by the caller |
110 | * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set. |
111 | * This lets tiered backends know they can safely upgrade a cached value to |
112 | * higher tiers using standard TTLs. |
113 | * |
114 | * @param string $key |
115 | * @param int $flags Bitfield of BagOStuff::READ_* constants [optional] |
116 | * |
117 | * @return mixed Returns false on failure or if the item does not exist |
118 | */ |
119 | public function get( $key, $flags = 0 ) { |
120 | $this->trackDuplicateKeys( $key ); |
121 | |
122 | return $this->resolveSegments( $key, $this->doGet( $key, $flags ) ); |
123 | } |
124 | |
125 | /** |
126 | * Track the number of times that a given key has been used. |
127 | * |
128 | * @param string $key |
129 | */ |
130 | private function trackDuplicateKeys( $key ) { |
131 | if ( !$this->reportDupes ) { |
132 | return; |
133 | } |
134 | |
135 | if ( !isset( $this->duplicateKeyLookups[$key] ) ) { |
136 | // Track that we have seen this key. This N-1 counting style allows |
137 | // easy filtering with array_filter() later. |
138 | $this->duplicateKeyLookups[$key] = 0; |
139 | } else { |
140 | $this->duplicateKeyLookups[$key]++; |
141 | |
142 | if ( $this->dupeTrackScheduled === false ) { |
143 | $this->dupeTrackScheduled = true; |
144 | // Schedule a callback that logs keys processed more than once by get(). |
145 | ( $this->asyncHandler )( function () { |
146 | $dups = array_filter( $this->duplicateKeyLookups ); |
147 | foreach ( $dups as $key => $count ) { |
148 | $this->logger->warning( |
149 | 'Duplicate get(): "{key}" fetched {count} times', |
150 | // Count is N-1 of the actual lookup count |
151 | [ 'key' => $key, 'count' => $count + 1, ] |
152 | ); |
153 | } |
154 | } ); |
155 | } |
156 | } |
157 | } |
158 | |
159 | /** |
160 | * Get an item |
161 | * |
162 | * The CAS token should be null if the key does not exist or the value is corrupt |
163 | * |
164 | * @param string $key |
165 | * @param int $flags Bitfield of BagOStuff::READ_* constants [optional] |
166 | * @param mixed &$casToken CAS token if MediumSpecificBagOStuff::PASS_BY_REF [returned] |
167 | * |
168 | * @return mixed Returns false on failure or if the item does not exist |
169 | */ |
170 | abstract protected function doGet( $key, $flags = 0, &$casToken = null ); |
171 | |
172 | public function set( $key, $value, $exptime = 0, $flags = 0 ) { |
173 | $entry = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags, $ok ); |
174 | |
175 | // Only when all segments (if any) are stored should the main key be changed |
176 | return $ok && $this->doSet( $key, $entry, $exptime, $flags ); |
177 | } |
178 | |
179 | /** |
180 | * Set an item |
181 | * |
182 | * @param string $key |
183 | * @param mixed $value |
184 | * @param int $exptime Either an interval in seconds or a unix timestamp for expiry |
185 | * @param int $flags Bitfield of BagOStuff::WRITE_* constants |
186 | * |
187 | * @return bool Success |
188 | */ |
189 | abstract protected function doSet( $key, $value, $exptime = 0, $flags = 0 ); |
190 | |
191 | public function delete( $key, $flags = 0 ) { |
192 | if ( !$this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS ) ) { |
193 | return $this->doDelete( $key, $flags ); |
194 | } |
195 | |
196 | $mainValue = $this->doGet( $key, self::READ_LATEST ); |
197 | if ( !$this->doDelete( $key, $flags ) ) { |
198 | return false; |
199 | } |
200 | |
201 | if ( !SerializedValueContainer::isSegmented( $mainValue ) ) { |
202 | // no segments to delete |
203 | return true; |
204 | } |
205 | |
206 | $orderedKeys = array_map( |
207 | function ( $segmentHash ) use ( $key ) { |
208 | return $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash ); |
209 | }, |
210 | $mainValue->{SerializedValueContainer::SEGMENTED_HASHES} |
211 | ); |
212 | |
213 | return $this->deleteMulti( $orderedKeys, $flags & ~self::WRITE_ALLOW_SEGMENTS ); |
214 | } |
215 | |
216 | /** |
217 | * Delete an item |
218 | * |
219 | * @param string $key |
220 | * @param int $flags Bitfield of BagOStuff::WRITE_* constants |
221 | * |
222 | * @return bool True if the item was deleted or not found, false on failure |
223 | */ |
224 | abstract protected function doDelete( $key, $flags = 0 ); |
225 | |
226 | public function add( $key, $value, $exptime = 0, $flags = 0 ) { |
227 | $entry = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags, $ok ); |
228 | |
229 | // Only when all segments (if any) are stored should the main key be changed |
230 | return $ok && $this->doAdd( $key, $entry, $exptime, $flags ); |
231 | } |
232 | |
233 | /** |
234 | * Insert an item if it does not already exist |
235 | * |
236 | * @param string $key |
237 | * @param mixed $value |
238 | * @param int $exptime |
239 | * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33) |
240 | * |
241 | * @return bool Success |
242 | */ |
243 | abstract protected function doAdd( $key, $value, $exptime = 0, $flags = 0 ); |
244 | |
245 | /** |
246 | * Merge changes into the existing cache value (possibly creating a new one) |
247 | * |
248 | * The callback function returns the new value given the current value |
249 | * (which will be false if not present), and takes the arguments: |
250 | * (this BagOStuff, cache key, current value, TTL). |
251 | * The TTL parameter is reference set to $exptime. It can be overridden in the callback. |
252 | * Nothing is stored nor deleted if the callback returns false. |
253 | * |
254 | * @param string $key |
255 | * @param callable $callback Callback method to be executed |
256 | * @param int $exptime Either an interval in seconds or a unix timestamp for expiry |
257 | * @param int $attempts The amount of times to attempt a merge in case of failure |
258 | * @param int $flags Bitfield of BagOStuff::WRITE_* constants |
259 | * |
260 | * @return bool Success |
261 | */ |
262 | public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) { |
263 | return $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags ); |
264 | } |
265 | |
266 | /** |
267 | * @param string $key |
268 | * @param callable $callback Callback method to be executed |
269 | * @param int $exptime Either an interval in seconds or a unix timestamp for expiry |
270 | * @param int $attempts The amount of times to attempt a merge in case of failure |
271 | * @param int $flags Bitfield of BagOStuff::WRITE_* constants |
272 | * |
273 | * @return bool Success |
274 | * @see BagOStuff::merge() |
275 | */ |
276 | final protected function mergeViaCas( $key, callable $callback, $exptime, $attempts, $flags ) { |
277 | $attemptsLeft = $attempts; |
278 | do { |
279 | $token = self::PASS_BY_REF; |
280 | // Get the old value and CAS token from cache |
281 | $watchPoint = $this->watchErrors(); |
282 | $currentValue = $this->resolveSegments( |
283 | $key, |
284 | $this->doGet( $key, $flags, $token ) |
285 | ); |
286 | if ( $this->getLastError( $watchPoint ) ) { |
287 | // Don't spam slow retries due to network problems (retry only on races) |
288 | $this->logger->warning( |
289 | __METHOD__ . ' failed due to read I/O error on get() for {key}.', [ 'key' => $key ] |
290 | ); |
291 | $success = false; |
292 | break; |
293 | } |
294 | |
295 | // Derive the new value from the old value |
296 | $value = $callback( $this, $key, $currentValue, $exptime ); |
297 | $keyWasNonexistent = ( $currentValue === false ); |
298 | $valueMatchesOldValue = ( $value === $currentValue ); |
299 | // free RAM in case the value is large |
300 | unset( $currentValue ); |
301 | |
302 | $watchPoint = $this->watchErrors(); |
303 | if ( $value === false || $exptime < 0 ) { |
304 | // do nothing |
305 | $success = true; |
306 | } elseif ( $valueMatchesOldValue && $attemptsLeft !== $attempts ) { |
307 | // recently set by another thread to the same value |
308 | $success = true; |
309 | } elseif ( $keyWasNonexistent ) { |
310 | // Try to create the key, failing if it gets created in the meantime |
311 | $success = $this->add( $key, $value, $exptime, $flags ); |
312 | } else { |
313 | // Try to update the key, failing if it gets changed in the meantime |
314 | $success = $this->cas( $token, $key, $value, $exptime, $flags ); |
315 | } |
316 | if ( $this->getLastError( $watchPoint ) ) { |
317 | // Don't spam slow retries due to network problems (retry only on races) |
318 | $this->logger->warning( |
319 | __METHOD__ . ' failed due to write I/O error for {key}.', |
320 | [ 'key' => $key ] |
321 | ); |
322 | $success = false; |
323 | break; |
324 | } |
325 | |
326 | } while ( !$success && --$attemptsLeft ); |
327 | |
328 | return $success; |
329 | } |
330 | |
331 | /** |
332 | * Set an item if the current CAS token matches the provided CAS token |
333 | * |
334 | * @param mixed $casToken Only set the item if it still has this CAS token |
335 | * @param string $key |
336 | * @param mixed $value |
337 | * @param int $exptime Either an interval in seconds or a unix timestamp for expiry |
338 | * @param int $flags Bitfield of BagOStuff::WRITE_* constants |
339 | * |
340 | * @return bool Success |
341 | */ |
342 | protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) { |
343 | if ( $casToken === null ) { |
344 | $this->logger->warning( |
345 | __METHOD__ . ' got empty CAS token for {key}.', |
346 | [ 'key' => $key ] |
347 | ); |
348 | |
349 | // caller may have meant to use add()? |
350 | return false; |
351 | } |
352 | |
353 | $entry = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags, $ok ); |
354 | |
355 | // Only when all segments (if any) are stored should the main key be changed |
356 | return $ok && $this->doCas( $casToken, $key, $entry, $exptime, $flags ); |
357 | } |
358 | |
359 | /** |
360 | * Set an item if the current CAS token matches the provided CAS token |
361 | * |
362 | * @param mixed $casToken CAS token from an existing version of the key |
363 | * @param string $key |
364 | * @param mixed $value |
365 | * @param int $exptime Either an interval in seconds or a unix timestamp for expiry |
366 | * @param int $flags Bitfield of BagOStuff::WRITE_* constants |
367 | * |
368 | * @return bool Success |
369 | */ |
370 | protected function doCas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) { |
371 | // @TODO: the use of lock() assumes that all other relevant sets() use a lock |
372 | if ( !$this->lock( $key, 0 ) ) { |
373 | // non-blocking |
374 | return false; |
375 | } |
376 | |
377 | $curCasToken = self::PASS_BY_REF; |
378 | $watchPoint = $this->watchErrors(); |
379 | $exists = ( $this->doGet( $key, self::READ_LATEST, $curCasToken ) !== false ); |
380 | if ( $this->getLastError( $watchPoint ) ) { |
381 | // Fail if the old CAS token could not be read |
382 | $success = false; |
383 | $this->logger->warning( |
384 | __METHOD__ . ' failed due to write I/O error for {key}.', |
385 | [ 'key' => $key ] |
386 | ); |
387 | } elseif ( $exists && $this->tokensMatch( $casToken, $curCasToken ) ) { |
388 | $success = $this->doSet( $key, $value, $exptime, $flags ); |
389 | } else { |
390 | // mismatched or failed |
391 | $success = false; |
392 | $this->logger->info( |
393 | __METHOD__ . ' failed due to race condition for {key}.', |
394 | [ 'key' => $key, 'key_exists' => $exists ] |
395 | ); |
396 | } |
397 | |
398 | $this->unlock( $key ); |
399 | |
400 | return $success; |
401 | } |
402 | |
403 | /** |
404 | * @param mixed $value CAS token for an existing key |
405 | * @param mixed $otherValue CAS token for an existing key |
406 | * |
407 | * @return bool Whether the two tokens match |
408 | */ |
409 | final protected function tokensMatch( $value, $otherValue ) { |
410 | $type = gettype( $value ); |
411 | // Ideally, tokens are counters, timestamps, hashes, or serialized PHP values. |
412 | // However, some classes might use the PHP values themselves. |
413 | if ( $type !== gettype( $otherValue ) ) { |
414 | return false; |
415 | } |
416 | // Serialize both tokens to strictly compare objects or arrays (which might objects |
417 | // nested inside). Note that this will not apply if integer/string CAS tokens are used. |
418 | if ( $type === 'array' || $type === 'object' ) { |
419 | return ( serialize( $value ) === serialize( $otherValue ) ); |
420 | } |
421 | |
422 | // For string/integer tokens, use a simple comparison |
423 | return ( $value === $otherValue ); |
424 | } |
425 | |
426 | /** |
427 | * Change the expiration on a key if it exists |
428 | * |
429 | * If an expiry in the past is given then the key will immediately be expired |
430 | * |
431 | * For large values written using WRITE_ALLOW_SEGMENTS, this only changes the TTL of the |
432 | * main segment list key. While lowering the TTL of the segment list key has the effect of |
433 | * functionally lowering the TTL of the key, it might leave unused blobs in cache for longer. |
434 | * Raising the TTL of such keys is not effective, since the expiration of a single segment |
435 | * key effectively expires the entire value. |
436 | * |
437 | * @param string $key |
438 | * @param int $exptime TTL or UNIX timestamp |
439 | * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33) |
440 | * |
441 | * @return bool Success Returns false on failure or if the item does not exist |
442 | * @since 1.28 |
443 | */ |
444 | public function changeTTL( $key, $exptime = 0, $flags = 0 ) { |
445 | return $this->doChangeTTL( $key, $exptime, $flags ); |
446 | } |
447 | |
448 | /** |
449 | * @param string $key |
450 | * @param int $exptime |
451 | * @param int $flags |
452 | * |
453 | * @return bool |
454 | */ |
455 | protected function doChangeTTL( $key, $exptime, $flags ) { |
456 | // @TODO: the use of lock() assumes that all other relevant sets() use a lock |
457 | if ( !$this->lock( $key, 0 ) ) { |
458 | return false; |
459 | } |
460 | |
461 | $expiry = $this->getExpirationAsTimestamp( $exptime ); |
462 | $delete = ( $expiry != self::TTL_INDEFINITE && $expiry < $this->getCurrentTime() ); |
463 | |
464 | // Use doGet() to avoid having to trigger resolveSegments() |
465 | $blob = $this->doGet( $key, self::READ_LATEST ); |
466 | if ( $blob ) { |
467 | if ( $delete ) { |
468 | $ok = $this->doDelete( $key, $flags ); |
469 | } else { |
470 | $ok = $this->doSet( $key, $blob, $exptime, $flags ); |
471 | } |
472 | } else { |
473 | $ok = false; |
474 | } |
475 | |
476 | $this->unlock( $key ); |
477 | |
478 | return $ok; |
479 | } |
480 | |
481 | public function incrWithInit( $key, $exptime, $step = 1, $init = null, $flags = 0 ) { |
482 | $step = (int)$step; |
483 | $init = is_int( $init ) ? $init : $step; |
484 | |
485 | return $this->doIncrWithInit( $key, $exptime, $step, $init, $flags ); |
486 | } |
487 | |
488 | /** |
489 | * @param string $key |
490 | * @param int $exptime |
491 | * @param int $step |
492 | * @param int $init |
493 | * @param int $flags |
494 | * |
495 | * @return int|bool New value or false on failure |
496 | */ |
497 | abstract protected function doIncrWithInit( $key, $exptime, $step, $init, $flags ); |
498 | |
499 | /** |
500 | * @param string $key |
501 | * @param int $timeout |
502 | * @param int $exptime |
503 | * @param string $rclass |
504 | * |
505 | * @return bool |
506 | */ |
507 | public function lock( $key, $timeout = 6, $exptime = 6, $rclass = '' ) { |
508 | $exptime = min( $exptime ?: INF, self::TTL_DAY ); |
509 | |
510 | $acquired = false; |
511 | |
512 | if ( isset( $this->locks[$key] ) ) { |
513 | // Already locked; avoid deadlocks and allow lock reentry if specified |
514 | if ( $rclass != '' && $this->locks[$key][self::LOCK_RCLASS] === $rclass ) { |
515 | ++$this->locks[$key][self::LOCK_DEPTH]; |
516 | $acquired = true; |
517 | } |
518 | } else { |
519 | // Not already locked; acquire a lock on the backend |
520 | $lockTsUnix = $this->doLock( $key, $timeout, $exptime ); |
521 | if ( $lockTsUnix !== null ) { |
522 | $this->locks[$key] = [ |
523 | self::LOCK_RCLASS => $rclass, |
524 | self::LOCK_DEPTH => 1, |
525 | self::LOCK_TIME => $lockTsUnix, |
526 | self::LOCK_EXPIRY => $lockTsUnix + $exptime |
527 | ]; |
528 | $acquired = true; |
529 | } |
530 | } |
531 | |
532 | return $acquired; |
533 | } |
534 | |
535 | /** |
536 | * @see MediumSpecificBagOStuff::lock() |
537 | * |
538 | * @param string $key |
539 | * @param int $timeout Lock wait timeout; 0 for non-blocking [optional] |
540 | * @param int $exptime Lock time-to-live 1 day maximum [optional] |
541 | * |
542 | * @return float|null UNIX timestamp of acquisition; null on failure |
543 | */ |
544 | protected function doLock( $key, $timeout, $exptime ) { |
545 | $lockTsUnix = null; |
546 | |
547 | $fname = __METHOD__; |
548 | $loop = new WaitConditionLoop( |
549 | function () use ( $key, $exptime, $fname, &$lockTsUnix ) { |
550 | $watchPoint = $this->watchErrors(); |
551 | if ( $this->add( $this->makeLockKey( $key ), 1, $exptime ) ) { |
552 | $lockTsUnix = microtime( true ); |
553 | |
554 | return WaitConditionLoop::CONDITION_REACHED; |
555 | } elseif ( $this->getLastError( $watchPoint ) ) { |
556 | $this->logger->warning( |
557 | "$fname failed due to I/O error for {key}.", |
558 | [ 'key' => $key ] |
559 | ); |
560 | |
561 | return WaitConditionLoop::CONDITION_ABORTED; |
562 | } |
563 | |
564 | return WaitConditionLoop::CONDITION_CONTINUE; |
565 | }, |
566 | $timeout |
567 | ); |
568 | $code = $loop->invoke(); |
569 | |
570 | if ( $code === $loop::CONDITION_TIMED_OUT ) { |
571 | $this->logger->warning( |
572 | "$fname failed due to timeout for {key}.", |
573 | [ 'key' => $key, 'timeout' => $timeout ] |
574 | ); |
575 | } |
576 | |
577 | return $lockTsUnix; |
578 | } |
579 | |
580 | /** |
581 | * Release an advisory lock on a key string |
582 | * |
583 | * @param string $key |
584 | * |
585 | * @return bool Success |
586 | */ |
587 | public function unlock( $key ) { |
588 | $released = false; |
589 | |
590 | if ( isset( $this->locks[$key] ) ) { |
591 | if ( --$this->locks[$key][self::LOCK_DEPTH] > 0 ) { |
592 | $released = true; |
593 | } else { |
594 | $released = $this->doUnlock( $key ); |
595 | unset( $this->locks[$key] ); |
596 | if ( !$released ) { |
597 | $this->logger->warning( |
598 | __METHOD__ . ' failed to release lock for {key}.', |
599 | [ 'key' => $key ] |
600 | ); |
601 | } |
602 | } |
603 | } else { |
604 | $this->logger->warning( |
605 | __METHOD__ . ' no lock to release for {key}.', |
606 | [ 'key' => $key ] |
607 | ); |
608 | } |
609 | |
610 | return $released; |
611 | } |
612 | |
613 | /** |
614 | * @see MediumSpecificBagOStuff::unlock() |
615 | * |
616 | * @param string $key |
617 | * |
618 | * @return bool Success |
619 | */ |
620 | protected function doUnlock( $key ) { |
621 | $released = false; |
622 | |
623 | // Estimate the remaining TTL of the lock key |
624 | $curTTL = $this->locks[$key][self::LOCK_EXPIRY] - $this->getCurrentTime(); |
625 | |
626 | // Check the risk of race conditions for key deletion |
627 | if ( $this->getQoS( self::ATTR_DURABILITY ) <= self::QOS_DURABILITY_SCRIPT ) { |
628 | // Lock (and data) keys use memory specific to this request (e.g. HashBagOStuff) |
629 | $isSafe = true; |
630 | } else { |
631 | // It is unsafe to delete the lock key if there is a serious risk of the key already |
632 | // being claimed by another thread before the delete operation reaches the backend |
633 | $isSafe = ( $curTTL > $this->maxLockSendDelay ); |
634 | } |
635 | |
636 | if ( $isSafe ) { |
637 | $released = $this->doDelete( $this->makeLockKey( $key ) ); |
638 | } else { |
639 | $this->logger->warning( |
640 | "Lock for {key} held too long ({age} sec).", |
641 | [ 'key' => $key, 'curTTL' => $curTTL ] |
642 | ); |
643 | } |
644 | |
645 | return $released; |
646 | } |
647 | |
648 | /** |
649 | * @param string $key |
650 | * |
651 | * @return string |
652 | */ |
653 | protected function makeLockKey( $key ) { |
654 | return "$key:lock"; |
655 | } |
656 | |
657 | public function deleteObjectsExpiringBefore( |
658 | $timestamp, |
659 | ?callable $progress = null, |
660 | $limit = INF, |
661 | ?string $tag = null |
662 | ) { |
663 | return false; |
664 | } |
665 | |
666 | /** |
667 | * Get an associative array containing the item for each of the keys that have items. |
668 | * |
669 | * @param string[] $keys List of keys; can be a map of (unused => key) for convenience |
670 | * @param int $flags Bitfield; supports READ_LATEST [optional] |
671 | * |
672 | * @return mixed[] Map of (key => value) for existing keys; preserves the order of $keys |
673 | */ |
674 | public function getMulti( array $keys, $flags = 0 ) { |
675 | $foundByKey = $this->doGetMulti( $keys, $flags ); |
676 | |
677 | $res = []; |
678 | foreach ( $keys as $key ) { |
679 | // Resolve one blob at a time (avoids too much I/O at once) |
680 | if ( array_key_exists( $key, $foundByKey ) ) { |
681 | // A value should not appear in the key if a segment is missing |
682 | $value = $this->resolveSegments( $key, $foundByKey[$key] ); |
683 | if ( $value !== false ) { |
684 | $res[$key] = $value; |
685 | } |
686 | } |
687 | } |
688 | |
689 | return $res; |
690 | } |
691 | |
692 | /** |
693 | * Get an associative array containing the item for each of the keys that have items. |
694 | * |
695 | * @param string[] $keys List of keys |
696 | * @param int $flags Bitfield; supports READ_LATEST [optional] |
697 | * |
698 | * @return array Map of (key => value) for existing keys; preserves the order of $keys |
699 | */ |
700 | protected function doGetMulti( array $keys, $flags = 0 ) { |
701 | $res = []; |
702 | foreach ( $keys as $key ) { |
703 | $val = $this->doGet( $key, $flags ); |
704 | if ( $val !== false ) { |
705 | $res[$key] = $val; |
706 | } |
707 | } |
708 | |
709 | return $res; |
710 | } |
711 | |
712 | /** |
713 | * Batch insertion/replace |
714 | * |
715 | * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O |
716 | * |
717 | * @param mixed[] $valueByKey Map of (key => value) |
718 | * @param int $exptime Either an interval in seconds or a unix timestamp for expiry |
719 | * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33) |
720 | * |
721 | * @return bool Success |
722 | * @since 1.24 |
723 | */ |
724 | public function setMulti( array $valueByKey, $exptime = 0, $flags = 0 ) { |
725 | if ( $this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS ) ) { |
726 | throw new InvalidArgumentException( __METHOD__ . ' got WRITE_ALLOW_SEGMENTS' ); |
727 | } |
728 | |
729 | return $this->doSetMulti( $valueByKey, $exptime, $flags ); |
730 | } |
731 | |
732 | /** |
733 | * @param mixed[] $data Map of (key => value) |
734 | * @param int $exptime Either an interval in seconds or a unix timestamp for expiry |
735 | * @param int $flags Bitfield of BagOStuff::WRITE_* constants |
736 | * |
737 | * @return bool Success |
738 | */ |
739 | protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) { |
740 | $res = true; |
741 | foreach ( $data as $key => $value ) { |
742 | $res = $this->doSet( $key, $value, $exptime, $flags ) && $res; |
743 | } |
744 | |
745 | return $res; |
746 | } |
747 | |
748 | public function deleteMulti( array $keys, $flags = 0 ) { |
749 | if ( $this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS ) ) { |
750 | throw new InvalidArgumentException( __METHOD__ . ' got WRITE_ALLOW_SEGMENTS' ); |
751 | } |
752 | |
753 | return $this->doDeleteMulti( $keys, $flags ); |
754 | } |
755 | |
756 | /** |
757 | * @param string[] $keys List of keys |
758 | * @param int $flags Bitfield of BagOStuff::WRITE_* constants |
759 | * |
760 | * @return bool Success |
761 | */ |
762 | protected function doDeleteMulti( array $keys, $flags = 0 ) { |
763 | $res = true; |
764 | foreach ( $keys as $key ) { |
765 | $res = $this->doDelete( $key, $flags ) && $res; |
766 | } |
767 | |
768 | return $res; |
769 | } |
770 | |
771 | /** |
772 | * Change the expiration of multiple keys that exist |
773 | * |
774 | * @param string[] $keys List of keys |
775 | * @param int $exptime TTL or UNIX timestamp |
776 | * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33) |
777 | * |
778 | * @return bool Success |
779 | * |
780 | * @since 1.34 |
781 | */ |
782 | public function changeTTLMulti( array $keys, $exptime, $flags = 0 ) { |
783 | return $this->doChangeTTLMulti( $keys, $exptime, $flags ); |
784 | } |
785 | |
786 | /** |
787 | * @param string[] $keys List of keys |
788 | * @param int $exptime TTL or UNIX timestamp |
789 | * @param int $flags Bitfield of BagOStuff::WRITE_* constants |
790 | * |
791 | * @return bool Success |
792 | */ |
793 | protected function doChangeTTLMulti( array $keys, $exptime, $flags = 0 ) { |
794 | $res = true; |
795 | foreach ( $keys as $key ) { |
796 | $res = $this->doChangeTTL( $key, $exptime, $flags ) && $res; |
797 | } |
798 | |
799 | return $res; |
800 | } |
801 | |
802 | /** |
803 | * Get and reassemble the chunks of blob at the given key |
804 | * |
805 | * @param string $key |
806 | * @param mixed $mainValue |
807 | * |
808 | * @return string|null|bool The combined string, false if missing, null on error |
809 | */ |
810 | final protected function resolveSegments( $key, $mainValue ) { |
811 | if ( SerializedValueContainer::isSegmented( $mainValue ) ) { |
812 | $orderedKeys = array_map( |
813 | function ( $segmentHash ) use ( $key ) { |
814 | return $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash ); |
815 | }, |
816 | $mainValue->{SerializedValueContainer::SEGMENTED_HASHES} |
817 | ); |
818 | |
819 | $segmentsByKey = $this->doGetMulti( $orderedKeys ); |
820 | |
821 | $parts = []; |
822 | foreach ( $orderedKeys as $segmentKey ) { |
823 | if ( isset( $segmentsByKey[$segmentKey] ) ) { |
824 | $parts[] = $segmentsByKey[$segmentKey]; |
825 | } else { |
826 | // missing segment |
827 | return false; |
828 | } |
829 | } |
830 | |
831 | return $this->unserialize( implode( '', $parts ) ); |
832 | } |
833 | |
834 | return $mainValue; |
835 | } |
836 | |
837 | /** |
838 | * Check if a value should use a segmentation wrapper due to its size |
839 | * |
840 | * In order to avoid extra serialization and/or twice-serialized wrappers, just check if |
841 | * the value is a large string. Support cache wrappers (e.g. WANObjectCache) that use 2D |
842 | * arrays to wrap values. This does not recurse in order to avoid overhead from complex |
843 | * structures and the risk of infinite loops (due to references). |
844 | * |
845 | * @param mixed $value |
846 | * @param int $flags |
847 | * |
848 | * @return bool |
849 | */ |
850 | private function useSegmentationWrapper( $value, $flags ) { |
851 | if ( |
852 | $this->segmentationSize === INF || |
853 | !$this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS ) |
854 | ) { |
855 | return false; |
856 | } |
857 | |
858 | if ( is_string( $value ) ) { |
859 | return ( strlen( $value ) >= $this->segmentationSize ); |
860 | } |
861 | |
862 | if ( is_array( $value ) ) { |
863 | // Expect that the contained value will be one of the first array entries |
864 | foreach ( array_slice( $value, 0, 4 ) as $v ) { |
865 | if ( is_string( $v ) && strlen( $v ) >= $this->segmentationSize ) { |
866 | return true; |
867 | } |
868 | } |
869 | } |
870 | |
871 | // Avoid breaking functions for incrementing/decrementing integer key values |
872 | return false; |
873 | } |
874 | |
875 | /** |
876 | * Make the entry to store at a key (inline or segment list), storing any segments |
877 | * |
878 | * @param string $key |
879 | * @param mixed $value |
880 | * @param int $exptime |
881 | * @param int $flags |
882 | * @param mixed|null &$ok Whether the entry is usable (e.g. no missing segments) [returned] |
883 | * |
884 | * @return mixed The entry (inline value, wrapped inline value, or wrapped segment list) |
885 | * @since 1.34 |
886 | */ |
887 | final protected function makeValueOrSegmentList( $key, $value, $exptime, $flags, &$ok ) { |
888 | $entry = $value; |
889 | $ok = true; |
890 | |
891 | if ( $this->useSegmentationWrapper( $value, $flags ) ) { |
892 | $segmentSize = $this->segmentationSize; |
893 | $maxTotalSize = $this->segmentedValueMaxSize; |
894 | $serialized = $this->getSerialized( $value, $key ); |
895 | $size = strlen( $serialized ); |
896 | if ( $size > $maxTotalSize ) { |
897 | $this->logger->warning( |
898 | "Value for {key} exceeds $maxTotalSize bytes; cannot segment.", |
899 | [ 'key' => $key ] |
900 | ); |
901 | } else { |
902 | // Split the serialized value into chunks and store them at different keys |
903 | $chunksByKey = []; |
904 | $segmentHashes = []; |
905 | $count = intdiv( $size, $segmentSize ) + ( ( $size % $segmentSize ) ? 1 : 0 ); |
906 | for ( $i = 0; $i < $count; ++$i ) { |
907 | $segment = substr( $serialized, $i * $segmentSize, $segmentSize ); |
908 | $hash = sha1( $segment ); |
909 | $chunkKey = $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $hash ); |
910 | $chunksByKey[$chunkKey] = $segment; |
911 | $segmentHashes[] = $hash; |
912 | } |
913 | $flags &= ~self::WRITE_ALLOW_SEGMENTS; |
914 | $ok = $this->setMulti( $chunksByKey, $exptime, $flags ); |
915 | $entry = SerializedValueContainer::newSegmented( $segmentHashes ); |
916 | } |
917 | } |
918 | |
919 | return $entry; |
920 | } |
921 | |
922 | /** |
923 | * @param int|float $exptime |
924 | * |
925 | * @return bool Whether the expiry is non-infinite, and, negative or not a UNIX timestamp |
926 | * @since 1.34 |
927 | */ |
928 | final protected function isRelativeExpiration( $exptime ) { |
929 | return ( $exptime !== self::TTL_INDEFINITE && $exptime < ( 10 * self::TTL_YEAR ) ); |
930 | } |
931 | |
932 | /** |
933 | * Convert an optionally relative timestamp to an absolute time |
934 | * |
935 | * The input value will be cast to an integer and interpreted as follows: |
936 | * - zero: no expiry; return zero (e.g. TTL_INDEFINITE) |
937 | * - negative: relative TTL; return UNIX timestamp offset by this value |
938 | * - positive (< 10 years): relative TTL; return UNIX timestamp offset by this value |
939 | * - positive (>= 10 years): absolute UNIX timestamp; return this value |
940 | * |
941 | * @param int $exptime |
942 | * |
943 | * @return int Expiration timestamp or TTL_INDEFINITE for indefinite |
944 | * @since 1.34 |
945 | */ |
946 | final protected function getExpirationAsTimestamp( $exptime ) { |
947 | if ( $exptime == self::TTL_INDEFINITE ) { |
948 | return $exptime; |
949 | } |
950 | |
951 | return $this->isRelativeExpiration( $exptime ) |
952 | ? intval( $this->getCurrentTime() + $exptime ) |
953 | : $exptime; |
954 | } |
955 | |
956 | /** |
957 | * Convert an optionally absolute expiry time to a relative time. If an |
958 | * absolute time is specified which is in the past, use a short expiry time. |
959 | * |
960 | * The input value will be cast to an integer and interpreted as follows: |
961 | * - zero: no expiry; return zero (e.g. TTL_INDEFINITE) |
962 | * - negative: relative TTL; return a short expiry time (1 second) |
963 | * - positive (< 10 years): relative TTL; return this value |
964 | * - positive (>= 10 years): absolute UNIX timestamp; return offset to current time |
965 | * |
966 | * @param int $exptime |
967 | * |
968 | * @return int Relative TTL or TTL_INDEFINITE for indefinite |
969 | * @since 1.34 |
970 | */ |
971 | final protected function getExpirationAsTTL( $exptime ) { |
972 | if ( $exptime == self::TTL_INDEFINITE ) { |
973 | return $exptime; |
974 | } |
975 | |
976 | return $this->isRelativeExpiration( $exptime ) |
977 | ? $exptime |
978 | : (int)max( $exptime - $this->getCurrentTime(), 1 ); |
979 | } |
980 | |
981 | /** |
982 | * Check if a value is an integer |
983 | * |
984 | * @param mixed $value |
985 | * |
986 | * @return bool |
987 | */ |
988 | final protected function isInteger( $value ) { |
989 | if ( is_int( $value ) ) { |
990 | return true; |
991 | } elseif ( !is_string( $value ) ) { |
992 | return false; |
993 | } |
994 | |
995 | $integer = (int)$value; |
996 | |
997 | return ( $value === (string)$integer ); |
998 | } |
999 | |
1000 | public function getQoS( $flag ) { |
1001 | return $this->attrMap[$flag] ?? self::QOS_UNKNOWN; |
1002 | } |
1003 | |
1004 | /** |
1005 | * @deprecated since 1.43, not used anywhere. |
1006 | */ |
1007 | public function getSegmentationSize() { |
1008 | wfDeprecated( __METHOD__, '1.43' ); |
1009 | |
1010 | return $this->segmentationSize; |
1011 | } |
1012 | |
1013 | /** |
1014 | * @deprecated since 1.43, not used anywhere. |
1015 | */ |
1016 | public function getSegmentedValueMaxSize() { |
1017 | wfDeprecated( __METHOD__, '1.43' ); |
1018 | |
1019 | return $this->segmentedValueMaxSize; |
1020 | } |
1021 | |
1022 | /** |
1023 | * Get the serialized form a value, logging a warning if it involves custom classes |
1024 | * |
1025 | * @param mixed $value |
1026 | * @param string $key |
1027 | * |
1028 | * @return string|int String/integer representation of value |
1029 | * @since 1.35 |
1030 | */ |
1031 | protected function getSerialized( $value, $key ) { |
1032 | $this->checkValueSerializability( $value, $key ); |
1033 | |
1034 | return $this->serialize( $value ); |
1035 | } |
1036 | |
1037 | /** |
1038 | * Log if a new cache value does not appear suitable for serialization at a quick glance |
1039 | * |
1040 | * This aids migration of values to JSON-like structures and the debugging of exceptions |
1041 | * due to serialization failure. |
1042 | * |
1043 | * This does not recurse more than one level into container structures. |
1044 | * |
1045 | * A proper cache key value is one of the following: |
1046 | * - null |
1047 | * - a scalar |
1048 | * - an array with scalar/null values |
1049 | * - an array tree with scalar/null "leaf" values |
1050 | * - an stdClass instance with scalar/null field values |
1051 | * - an stdClass instance tree with scalar/null "leaf" values |
1052 | * - an instance of a class that implements JsonSerializable |
1053 | * |
1054 | * @param mixed $value Result of the value generation callback for the key |
1055 | * @param string $key Cache key |
1056 | */ |
1057 | private function checkValueSerializability( $value, $key ) { |
1058 | if ( is_array( $value ) ) { |
1059 | $this->checkIterableMapSerializability( $value, $key ); |
1060 | } elseif ( is_object( $value ) ) { |
1061 | // Note that Closure instances count as objects |
1062 | if ( $value instanceof stdClass ) { |
1063 | $this->checkIterableMapSerializability( $value, $key ); |
1064 | } elseif ( !( $value instanceof JsonSerializable ) ) { |
1065 | $this->logger->warning( |
1066 | "{class} value for '{cachekey}'; serialization is suspect.", |
1067 | [ 'cachekey' => $key, 'class' => get_class( $value ) ] |
1068 | ); |
1069 | } |
1070 | } |
1071 | } |
1072 | |
1073 | /** |
1074 | * @param array|stdClass $value Result of the value generation callback for the key |
1075 | * @param string $key Cache key |
1076 | */ |
1077 | private function checkIterableMapSerializability( $value, $key ) { |
1078 | foreach ( $value as $index => $entry ) { |
1079 | if ( is_object( $entry ) ) { |
1080 | // Note that Closure instances count as objects |
1081 | if ( |
1082 | !( $entry instanceof \stdClass ) && |
1083 | !( $entry instanceof \JsonSerializable ) |
1084 | ) { |
1085 | $this->logger->warning( |
1086 | "{class} value for '{cachekey}' at '$index'; serialization is suspect.", |
1087 | [ 'cachekey' => $key, 'class' => get_class( $entry ) ] |
1088 | ); |
1089 | |
1090 | return; |
1091 | } |
1092 | } |
1093 | } |
1094 | } |
1095 | |
1096 | /** |
1097 | * @param mixed $value |
1098 | * |
1099 | * @return string|int|false String/integer representation |
1100 | * @note Special handling is usually needed for integers so incr()/decr() work |
1101 | */ |
1102 | protected function serialize( $value ) { |
1103 | return is_int( $value ) ? $value : serialize( $value ); |
1104 | } |
1105 | |
1106 | /** |
1107 | * @param string|int|false $value |
1108 | * |
1109 | * @return mixed Original value or false on error |
1110 | * @note Special handling is usually needed for integers so incr()/decr() work |
1111 | */ |
1112 | protected function unserialize( $value ) { |
1113 | return $this->isInteger( $value ) ? (int)$value : unserialize( $value ); |
1114 | } |
1115 | |
1116 | /** |
1117 | * @param string $text |
1118 | */ |
1119 | protected function debug( $text ) { |
1120 | $this->logger->debug( "{class} debug: $text", [ 'class' => static::class ] ); |
1121 | } |
1122 | |
1123 | /** |
1124 | * @param string $key Key generated by BagOStuff::makeKeyInternal |
1125 | * |
1126 | * @return string A stats prefix to describe this class of key (e.g. "objectcache.file") |
1127 | */ |
1128 | private function determinekeyGroupForStats( $key ): string { |
1129 | // Key came directly from BagOStuff::makeKey() or BagOStuff::makeGlobalKey() |
1130 | // and thus has the format of "<scope>:<collection>[:<constant or variable>]..." |
1131 | $components = explode( ':', $key, 3 ); |
1132 | // Handle legacy callers that fail to use the key building methods |
1133 | $keygroup = $components[1] ?? 'UNKNOWN'; |
1134 | |
1135 | return strtr( $keygroup, '.', '_' ); |
1136 | } |
1137 | |
1138 | /** |
1139 | * @param string $op Operation name as a MediumSpecificBagOStuff::METRIC_OP_* constant |
1140 | * @param array<int,string>|array<string,int[]> $keyInfo Key list, if payload sizes are not |
1141 | * applicable, otherwise, map of (key => (send payload size, receive payload size)); send |
1142 | * and receive sizes are 0 where not applicable and receive sizes are "false" for keys |
1143 | * that were not found during read operations |
1144 | */ |
1145 | protected function updateOpStats( string $op, array $keyInfo ) { |
1146 | $deltasByMetric = []; |
1147 | |
1148 | foreach ( $keyInfo as $indexOrKey => $keyOrSizes ) { |
1149 | if ( is_array( $keyOrSizes ) ) { |
1150 | $key = $indexOrKey; |
1151 | [ $sPayloadSize, $rPayloadSize ] = $keyOrSizes; |
1152 | } else { |
1153 | $key = $keyOrSizes; |
1154 | $sPayloadSize = 0; |
1155 | $rPayloadSize = 0; |
1156 | } |
1157 | |
1158 | // Metric prefix for the cache wrapper and key collection name |
1159 | $keygroup = $this->determinekeyGroupForStats( $key ); |
1160 | |
1161 | if ( $op === self::METRIC_OP_GET ) { |
1162 | // This operation was either a "hit" or "miss" for this key |
1163 | if ( $rPayloadSize === false ) { |
1164 | $statsdName = "objectcache.{$keygroup}.{$op}_miss_rate"; |
1165 | $statsName = "bagostuff_miss_total"; |
1166 | } else { |
1167 | $statsdName = "objectcache.{$keygroup}.{$op}_hit_rate"; |
1168 | $statsName = "bagostuff_hit_total"; |
1169 | } |
1170 | } else { |
1171 | // There is no concept of "hit" or "miss" for this operation |
1172 | $statsdName = "objectcache.{$keygroup}.{$op}_call_rate"; |
1173 | $statsName = "bagostuff_call_total"; |
1174 | } |
1175 | $deltasByMetric[$statsdName] = [ |
1176 | 'delta' => ( $deltasByMetric[$statsdName]['delta'] ?? 0 ) + 1, |
1177 | 'metric' => $statsName, |
1178 | 'keygroup' => $keygroup, |
1179 | 'operation' => $op, |
1180 | ]; |
1181 | |
1182 | if ( $sPayloadSize > 0 ) { |
1183 | $statsdName = "objectcache.{$keygroup}.{$op}_bytes_sent"; |
1184 | $statsName = "bagostuff_bytes_sent_total"; |
1185 | $deltasByMetric[$statsdName] = [ |
1186 | 'delta' => ( $deltasByMetric[$statsdName]['delta'] ?? 0 ) + $sPayloadSize, |
1187 | 'metric' => $statsName, |
1188 | 'keygroup' => $keygroup, |
1189 | 'operation' => $op, |
1190 | ]; |
1191 | } |
1192 | |
1193 | if ( $rPayloadSize > 0 ) { |
1194 | $statsdName = "objectcache.{$keygroup}.{$op}_bytes_read"; |
1195 | $statsName = "bagostuff_bytes_read_total"; |
1196 | $deltasByMetric[$statsdName] = [ |
1197 | 'delta' => ( $deltasByMetric[$statsdName]['delta'] ?? 0 ) + $rPayloadSize, |
1198 | 'metric' => $statsName, |
1199 | 'keygroup' => $keygroup, |
1200 | 'operation' => $op, |
1201 | ]; |
1202 | } |
1203 | } |
1204 | |
1205 | foreach ( $deltasByMetric as $statsdName => $delta ) { |
1206 | $this->stats->getCounter( $delta['metric'] ) |
1207 | ->setLabel( 'keygroup', $delta['keygroup'] ) |
1208 | ->setLabel( 'operation', $delta['operation'] ) |
1209 | ->copyToStatsdAt( $statsdName ) |
1210 | ->incrementBy( $delta['delta'] ); |
1211 | } |
1212 | } |
1213 | } |
1214 | |
1215 | /** @deprecated class alias since 1.43 */ |
1216 | class_alias( MediumSpecificBagOStuff::class, 'MediumSpecificBagOStuff' ); |