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