Merge "Exclude redirects from Special:Fewestrevisions"
[lhc/web/wiklou.git] / includes / libs / objectcache / MediumSpecificBagOStuff.php
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[] Lock tracking */
36 protected $locks = [];
37 /** @var int ERR_* class constant */
38 protected $lastError = self::ERR_NONE;
39 /** @var string */
40 protected $keyspace = 'local';
41 /** @var int Seconds */
42 protected $syncTimeout;
43 /** @var int Bytes; chunk size of segmented cache values */
44 protected $segmentationSize;
45 /** @var int Bytes; maximum total size of a segmented cache value */
46 protected $segmentedValueMaxSize;
47
48 /** @var array */
49 private $duplicateKeyLookups = [];
50 /** @var bool */
51 private $reportDupes = false;
52 /** @var bool */
53 private $dupeTrackScheduled = false;
54
55 /** @var callable[] */
56 protected $busyCallbacks = [];
57
58 /** @var string Component to use for key construction of blob segment keys */
59 const SEGMENT_COMPONENT = 'segment';
60
61 /**
62 * @see BagOStuff::__construct()
63 * Additional $params options include:
64 * - logger: Psr\Log\LoggerInterface instance
65 * - keyspace: Default keyspace for $this->makeKey()
66 * - reportDupes: Whether to emit warning log messages for all keys that were
67 * requested more than once (requires an asyncHandler).
68 * - syncTimeout: How long to wait with WRITE_SYNC in seconds.
69 * - segmentationSize: The chunk size, in bytes, of segmented values. The value should
70 * not exceed the maximum size of values in the storage backend, as configured by
71 * the site administrator.
72 * - segmentedValueMaxSize: The maximum total size, in bytes, of segmented values.
73 * This should be configured to a reasonable size give the site traffic and the
74 * amount of I/O between application and cache servers that the network can handle.
75 * @param array $params
76 */
77 public function __construct( array $params = [] ) {
78 parent::__construct( $params );
79
80 if ( isset( $params['keyspace'] ) ) {
81 $this->keyspace = $params['keyspace'];
82 }
83
84 if ( !empty( $params['reportDupes'] ) && is_callable( $this->asyncHandler ) ) {
85 $this->reportDupes = true;
86 }
87
88 $this->syncTimeout = $params['syncTimeout'] ?? 3;
89 $this->segmentationSize = $params['segmentationSize'] ?? 8388608; // 8MiB
90 $this->segmentedValueMaxSize = $params['segmentedValueMaxSize'] ?? 67108864; // 64MiB
91 }
92
93 /**
94 * Get an item with the given key
95 *
96 * If the key includes a deterministic input hash (e.g. the key can only have
97 * the correct value) or complete staleness checks are handled by the caller
98 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
99 * This lets tiered backends know they can safely upgrade a cached value to
100 * higher tiers using standard TTLs.
101 *
102 * @param string $key
103 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
104 * @return mixed Returns false on failure or if the item does not exist
105 */
106 public function get( $key, $flags = 0 ) {
107 $this->trackDuplicateKeys( $key );
108
109 return $this->resolveSegments( $key, $this->doGet( $key, $flags ) );
110 }
111
112 /**
113 * Track the number of times that a given key has been used.
114 * @param string $key
115 */
116 private function trackDuplicateKeys( $key ) {
117 if ( !$this->reportDupes ) {
118 return;
119 }
120
121 if ( !isset( $this->duplicateKeyLookups[$key] ) ) {
122 // Track that we have seen this key. This N-1 counting style allows
123 // easy filtering with array_filter() later.
124 $this->duplicateKeyLookups[$key] = 0;
125 } else {
126 $this->duplicateKeyLookups[$key] += 1;
127
128 if ( $this->dupeTrackScheduled === false ) {
129 $this->dupeTrackScheduled = true;
130 // Schedule a callback that logs keys processed more than once by get().
131 call_user_func( $this->asyncHandler, function () {
132 $dups = array_filter( $this->duplicateKeyLookups );
133 foreach ( $dups as $key => $count ) {
134 $this->logger->warning(
135 'Duplicate get(): "{key}" fetched {count} times',
136 // Count is N-1 of the actual lookup count
137 [ 'key' => $key, 'count' => $count + 1, ]
138 );
139 }
140 } );
141 }
142 }
143 }
144
145 /**
146 * @param string $key
147 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
148 * @param mixed|null &$casToken Token to use for check-and-set comparisons
149 * @return mixed Returns false on failure or if the item does not exist
150 */
151 abstract protected function doGet( $key, $flags = 0, &$casToken = null );
152
153 /**
154 * Set an item
155 *
156 * @param string $key
157 * @param mixed $value
158 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
159 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
160 * @return bool Success
161 */
162 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
163 if (
164 is_int( $value ) || // avoid breaking incr()/decr()
165 ( $flags & self::WRITE_ALLOW_SEGMENTS ) != self::WRITE_ALLOW_SEGMENTS ||
166 is_infinite( $this->segmentationSize )
167 ) {
168 return $this->doSet( $key, $value, $exptime, $flags );
169 }
170
171 $serialized = $this->serialize( $value );
172 $segmentSize = $this->getSegmentationSize();
173 $maxTotalSize = $this->getSegmentedValueMaxSize();
174
175 $size = strlen( $serialized );
176 if ( $size <= $segmentSize ) {
177 // Since the work of serializing it was already done, just use it inline
178 return $this->doSet(
179 $key,
180 SerializedValueContainer::newUnified( $serialized ),
181 $exptime,
182 $flags
183 );
184 } elseif ( $size > $maxTotalSize ) {
185 $this->setLastError( "Key $key exceeded $maxTotalSize bytes." );
186
187 return false;
188 }
189
190 $chunksByKey = [];
191 $segmentHashes = [];
192 $count = intdiv( $size, $segmentSize ) + ( ( $size % $segmentSize ) ? 1 : 0 );
193 for ( $i = 0; $i < $count; ++$i ) {
194 $segment = substr( $serialized, $i * $segmentSize, $segmentSize );
195 $hash = sha1( $segment );
196 $chunkKey = $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $hash );
197 $chunksByKey[$chunkKey] = $segment;
198 $segmentHashes[] = $hash;
199 }
200
201 $flags &= ~self::WRITE_ALLOW_SEGMENTS; // sanity
202 $ok = $this->setMulti( $chunksByKey, $exptime, $flags );
203 if ( $ok ) {
204 // Only when all segments are stored should the main key be changed
205 $ok = $this->doSet(
206 $key,
207 SerializedValueContainer::newSegmented( $segmentHashes ),
208 $exptime,
209 $flags
210 );
211 }
212
213 return $ok;
214 }
215
216 /**
217 * Set an item
218 *
219 * @param string $key
220 * @param mixed $value
221 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
222 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
223 * @return bool Success
224 */
225 abstract protected function doSet( $key, $value, $exptime = 0, $flags = 0 );
226
227 /**
228 * Delete an item
229 *
230 * For large values written using WRITE_ALLOW_SEGMENTS, this only deletes the main
231 * segment list key unless WRITE_PRUNE_SEGMENTS is in the flags. While deleting the segment
232 * list key has the effect of functionally deleting the key, it leaves unused blobs in cache.
233 *
234 * @param string $key
235 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
236 * @return bool True if the item was deleted or not found, false on failure
237 */
238 public function delete( $key, $flags = 0 ) {
239 if ( ( $flags & self::WRITE_PRUNE_SEGMENTS ) != self::WRITE_PRUNE_SEGMENTS ) {
240 return $this->doDelete( $key, $flags );
241 }
242
243 $mainValue = $this->doGet( $key, self::READ_LATEST );
244 if ( !$this->doDelete( $key, $flags ) ) {
245 return false;
246 }
247
248 if ( !SerializedValueContainer::isSegmented( $mainValue ) ) {
249 return true; // no segments to delete
250 }
251
252 $orderedKeys = array_map(
253 function ( $segmentHash ) use ( $key ) {
254 return $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash );
255 },
256 $mainValue->{SerializedValueContainer::SEGMENTED_HASHES}
257 );
258
259 return $this->deleteMulti( $orderedKeys, $flags );
260 }
261
262 /**
263 * Delete an item
264 *
265 * @param string $key
266 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
267 * @return bool True if the item was deleted or not found, false on failure
268 */
269 abstract protected function doDelete( $key, $flags = 0 );
270
271 /**
272 * Merge changes into the existing cache value (possibly creating a new one)
273 *
274 * The callback function returns the new value given the current value
275 * (which will be false if not present), and takes the arguments:
276 * (this BagOStuff, cache key, current value, TTL).
277 * The TTL parameter is reference set to $exptime. It can be overriden in the callback.
278 * Nothing is stored nor deleted if the callback returns false.
279 *
280 * @param string $key
281 * @param callable $callback Callback method to be executed
282 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
283 * @param int $attempts The amount of times to attempt a merge in case of failure
284 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
285 * @return bool Success
286 * @throws InvalidArgumentException
287 */
288 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
289 return $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
290 }
291
292 /**
293 * @param string $key
294 * @param callable $callback Callback method to be executed
295 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
296 * @param int $attempts The amount of times to attempt a merge in case of failure
297 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
298 * @return bool Success
299 * @see BagOStuff::merge()
300 *
301 */
302 final protected function mergeViaCas( $key, callable $callback, $exptime, $attempts, $flags ) {
303 do {
304 $casToken = null; // passed by reference
305 // Get the old value and CAS token from cache
306 $this->clearLastError();
307 $currentValue = $this->resolveSegments(
308 $key,
309 $this->doGet( $key, self::READ_LATEST, $casToken )
310 );
311 if ( $this->getLastError() ) {
312 $this->logger->warning(
313 __METHOD__ . ' failed due to I/O error on get() for {key}.',
314 [ 'key' => $key ]
315 );
316
317 return false; // don't spam retries (retry only on races)
318 }
319
320 // Derive the new value from the old value
321 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
322 $hadNoCurrentValue = ( $currentValue === false );
323 unset( $currentValue ); // free RAM in case the value is large
324
325 $this->clearLastError();
326 if ( $value === false ) {
327 $success = true; // do nothing
328 } elseif ( $hadNoCurrentValue ) {
329 // Try to create the key, failing if it gets created in the meantime
330 $success = $this->add( $key, $value, $exptime, $flags );
331 } else {
332 // Try to update the key, failing if it gets changed in the meantime
333 $success = $this->cas( $casToken, $key, $value, $exptime, $flags );
334 }
335 if ( $this->getLastError() ) {
336 $this->logger->warning(
337 __METHOD__ . ' failed due to I/O error for {key}.',
338 [ 'key' => $key ]
339 );
340
341 return false; // IO error; don't spam retries
342 }
343
344 } while ( !$success && --$attempts );
345
346 return $success;
347 }
348
349 /**
350 * Check and set an item
351 *
352 * @param mixed $casToken
353 * @param string $key
354 * @param mixed $value
355 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
356 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
357 * @return bool Success
358 */
359 protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
360 if ( !$this->lock( $key, 0 ) ) {
361 return false; // non-blocking
362 }
363
364 $curCasToken = null; // passed by reference
365 $this->doGet( $key, self::READ_LATEST, $curCasToken );
366 if ( $casToken === $curCasToken ) {
367 $success = $this->set( $key, $value, $exptime, $flags );
368 } else {
369 $this->logger->info(
370 __METHOD__ . ' failed due to race condition for {key}.',
371 [ 'key' => $key ]
372 );
373
374 $success = false; // mismatched or failed
375 }
376
377 $this->unlock( $key );
378
379 return $success;
380 }
381
382 /**
383 * Change the expiration on a key if it exists
384 *
385 * If an expiry in the past is given then the key will immediately be expired
386 *
387 * For large values written using WRITE_ALLOW_SEGMENTS, this only changes the TTL of the
388 * main segment list key. While lowering the TTL of the segment list key has the effect of
389 * functionally lowering the TTL of the key, it might leave unused blobs in cache for longer.
390 * Raising the TTL of such keys is not effective, since the expiration of a single segment
391 * key effectively expires the entire value.
392 *
393 * @param string $key
394 * @param int $exptime TTL or UNIX timestamp
395 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
396 * @return bool Success Returns false on failure or if the item does not exist
397 * @since 1.28
398 */
399 public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
400 return $this->doChangeTTL( $key, $exptime, $flags );
401 }
402
403 /**
404 * @param string $key
405 * @param int $exptime
406 * @param int $flags
407 * @return bool
408 */
409 protected function doChangeTTL( $key, $exptime, $flags ) {
410 $expiry = $this->convertToExpiry( $exptime );
411 $delete = ( $expiry != 0 && $expiry < $this->getCurrentTime() );
412
413 if ( !$this->lock( $key, 0 ) ) {
414 return false;
415 }
416 // Use doGet() to avoid having to trigger resolveSegments()
417 $blob = $this->doGet( $key, self::READ_LATEST );
418 if ( $blob ) {
419 if ( $delete ) {
420 $ok = $this->doDelete( $key, $flags );
421 } else {
422 $ok = $this->doSet( $key, $blob, $exptime, $flags );
423 }
424 } else {
425 $ok = false;
426 }
427
428 $this->unlock( $key );
429
430 return $ok;
431 }
432
433 /**
434 * Acquire an advisory lock on a key string
435 *
436 * Note that if reentry is enabled, duplicate calls ignore $expiry
437 *
438 * @param string $key
439 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
440 * @param int $expiry Lock expiry [optional]; 1 day maximum
441 * @param string $rclass Allow reentry if set and the current lock used this value
442 * @return bool Success
443 */
444 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
445 // Avoid deadlocks and allow lock reentry if specified
446 if ( isset( $this->locks[$key] ) ) {
447 if ( $rclass != '' && $this->locks[$key]['class'] === $rclass ) {
448 ++$this->locks[$key]['depth'];
449 return true;
450 } else {
451 return false;
452 }
453 }
454
455 $fname = __METHOD__;
456 $expiry = min( $expiry ?: INF, self::TTL_DAY );
457 $loop = new WaitConditionLoop(
458 function () use ( $key, $expiry, $fname ) {
459 $this->clearLastError();
460 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
461 return WaitConditionLoop::CONDITION_REACHED; // locked!
462 } elseif ( $this->getLastError() ) {
463 $this->logger->warning(
464 $fname . ' failed due to I/O error for {key}.',
465 [ 'key' => $key ]
466 );
467
468 return WaitConditionLoop::CONDITION_ABORTED; // network partition?
469 }
470
471 return WaitConditionLoop::CONDITION_CONTINUE;
472 },
473 $timeout
474 );
475
476 $code = $loop->invoke();
477 $locked = ( $code === $loop::CONDITION_REACHED );
478 if ( $locked ) {
479 $this->locks[$key] = [ 'class' => $rclass, 'depth' => 1 ];
480 } elseif ( $code === $loop::CONDITION_TIMED_OUT ) {
481 $this->logger->warning(
482 "$fname failed due to timeout for {key}.",
483 [ 'key' => $key, 'timeout' => $timeout ]
484 );
485 }
486
487 return $locked;
488 }
489
490 /**
491 * Release an advisory lock on a key string
492 *
493 * @param string $key
494 * @return bool Success
495 */
496 public function unlock( $key ) {
497 if ( !isset( $this->locks[$key] ) ) {
498 return false;
499 }
500
501 if ( --$this->locks[$key]['depth'] <= 0 ) {
502 unset( $this->locks[$key] );
503
504 $ok = $this->doDelete( "{$key}:lock" );
505 if ( !$ok ) {
506 $this->logger->warning(
507 __METHOD__ . ' failed to release lock for {key}.',
508 [ 'key' => $key ]
509 );
510 }
511
512 return $ok;
513 }
514
515 return true;
516 }
517
518 /**
519 * Delete all objects expiring before a certain date.
520 * @param string|int $timestamp The reference date in MW or TS_UNIX format
521 * @param callable|null $progress Optional, a function which will be called
522 * regularly during long-running operations with the percentage progress
523 * as the first parameter. [optional]
524 * @param int $limit Maximum number of keys to delete [default: INF]
525 *
526 * @return bool Success; false if unimplemented
527 */
528 public function deleteObjectsExpiringBefore(
529 $timestamp,
530 callable $progress = null,
531 $limit = INF
532 ) {
533 return false;
534 }
535
536 /**
537 * Get an associative array containing the item for each of the keys that have items.
538 * @param string[] $keys List of keys; can be a map of (unused => key) for convenience
539 * @param int $flags Bitfield; supports READ_LATEST [optional]
540 * @return mixed[] Map of (key => value) for existing keys; preserves the order of $keys
541 */
542 public function getMulti( array $keys, $flags = 0 ) {
543 $foundByKey = $this->doGetMulti( $keys, $flags );
544
545 $res = [];
546 foreach ( $keys as $key ) {
547 // Resolve one blob at a time (avoids too much I/O at once)
548 if ( array_key_exists( $key, $foundByKey ) ) {
549 // A value should not appear in the key if a segment is missing
550 $value = $this->resolveSegments( $key, $foundByKey[$key] );
551 if ( $value !== false ) {
552 $res[$key] = $value;
553 }
554 }
555 }
556
557 return $res;
558 }
559
560 /**
561 * Get an associative array containing the item for each of the keys that have items.
562 * @param string[] $keys List of keys
563 * @param int $flags Bitfield; supports READ_LATEST [optional]
564 * @return array Map of (key => value) for existing keys
565 */
566 protected function doGetMulti( array $keys, $flags = 0 ) {
567 $res = [];
568 foreach ( $keys as $key ) {
569 $val = $this->doGet( $key, $flags );
570 if ( $val !== false ) {
571 $res[$key] = $val;
572 }
573 }
574
575 return $res;
576 }
577
578 /**
579 * Batch insertion/replace
580 *
581 * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O
582 *
583 * @param mixed[] $data Map of (key => value)
584 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
585 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
586 * @return bool Success
587 * @since 1.24
588 */
589 public function setMulti( array $data, $exptime = 0, $flags = 0 ) {
590 if ( ( $flags & self::WRITE_ALLOW_SEGMENTS ) === self::WRITE_ALLOW_SEGMENTS ) {
591 throw new InvalidArgumentException( __METHOD__ . ' got WRITE_ALLOW_SEGMENTS' );
592 }
593 return $this->doSetMulti( $data, $exptime, $flags );
594 }
595
596 /**
597 * @param mixed[] $data Map of (key => value)
598 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
599 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
600 * @return bool Success
601 */
602 protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
603 $res = true;
604 foreach ( $data as $key => $value ) {
605 $res = $this->doSet( $key, $value, $exptime, $flags ) && $res;
606 }
607 return $res;
608 }
609
610 /**
611 * Batch deletion
612 *
613 * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O
614 *
615 * @param string[] $keys List of keys
616 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
617 * @return bool Success
618 * @since 1.33
619 */
620 public function deleteMulti( array $keys, $flags = 0 ) {
621 if ( ( $flags & self::WRITE_ALLOW_SEGMENTS ) === self::WRITE_ALLOW_SEGMENTS ) {
622 throw new InvalidArgumentException( __METHOD__ . ' got WRITE_ALLOW_SEGMENTS' );
623 }
624 return $this->doDeleteMulti( $keys, $flags );
625 }
626
627 /**
628 * @param string[] $keys List of keys
629 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
630 * @return bool Success
631 */
632 protected function doDeleteMulti( array $keys, $flags = 0 ) {
633 $res = true;
634 foreach ( $keys as $key ) {
635 $res = $this->doDelete( $key, $flags ) && $res;
636 }
637 return $res;
638 }
639
640 /**
641 * Change the expiration of multiple keys that exist
642 *
643 * @param string[] $keys List of keys
644 * @param int $exptime TTL or UNIX timestamp
645 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
646 * @return bool Success
647 * @see BagOStuff::changeTTL()
648 *
649 * @since 1.34
650 */
651 public function changeTTLMulti( array $keys, $exptime, $flags = 0 ) {
652 $res = true;
653 foreach ( $keys as $key ) {
654 $res = $this->doChangeTTL( $key, $exptime, $flags ) && $res;
655 }
656
657 return $res;
658 }
659
660 /**
661 * Decrease stored value of $key by $value while preserving its TTL
662 * @param string $key
663 * @param int $value Value to subtract from $key (default: 1) [optional]
664 * @return int|bool New value or false on failure
665 */
666 public function decr( $key, $value = 1 ) {
667 return $this->incr( $key, -$value );
668 }
669
670 /**
671 * Increase stored value of $key by $value while preserving its TTL
672 *
673 * This will create the key with value $init and TTL $ttl instead if not present
674 *
675 * @param string $key
676 * @param int $ttl
677 * @param int $value
678 * @param int $init
679 * @return int|bool New value or false on failure
680 * @since 1.24
681 */
682 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
683 $this->clearLastError();
684 $newValue = $this->incr( $key, $value );
685 if ( $newValue === false && !$this->getLastError() ) {
686 // No key set; initialize
687 $newValue = $this->add( $key, (int)$init, $ttl ) ? $init : false;
688 if ( $newValue === false && !$this->getLastError() ) {
689 // Raced out initializing; increment
690 $newValue = $this->incr( $key, $value );
691 }
692 }
693
694 return $newValue;
695 }
696
697 /**
698 * Get and reassemble the chunks of blob at the given key
699 *
700 * @param string $key
701 * @param mixed $mainValue
702 * @return string|null|bool The combined string, false if missing, null on error
703 */
704 final protected function resolveSegments( $key, $mainValue ) {
705 if ( SerializedValueContainer::isUnified( $mainValue ) ) {
706 return $this->unserialize( $mainValue->{SerializedValueContainer::UNIFIED_DATA} );
707 }
708
709 if ( SerializedValueContainer::isSegmented( $mainValue ) ) {
710 $orderedKeys = array_map(
711 function ( $segmentHash ) use ( $key ) {
712 return $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash );
713 },
714 $mainValue->{SerializedValueContainer::SEGMENTED_HASHES}
715 );
716
717 $segmentsByKey = $this->doGetMulti( $orderedKeys );
718
719 $parts = [];
720 foreach ( $orderedKeys as $segmentKey ) {
721 if ( isset( $segmentsByKey[$segmentKey] ) ) {
722 $parts[] = $segmentsByKey[$segmentKey];
723 } else {
724 return false; // missing segment
725 }
726 }
727
728 return $this->unserialize( implode( '', $parts ) );
729 }
730
731 return $mainValue;
732 }
733
734 /**
735 * Get the "last error" registered; clearLastError() should be called manually
736 * @return int ERR_* constant for the "last error" registry
737 * @since 1.23
738 */
739 public function getLastError() {
740 return $this->lastError;
741 }
742
743 /**
744 * Clear the "last error" registry
745 * @since 1.23
746 */
747 public function clearLastError() {
748 $this->lastError = self::ERR_NONE;
749 }
750
751 /**
752 * Set the "last error" registry
753 * @param int $err ERR_* constant
754 * @since 1.23
755 */
756 protected function setLastError( $err ) {
757 $this->lastError = $err;
758 }
759
760 /**
761 * Let a callback be run to avoid wasting time on special blocking calls
762 *
763 * The callbacks may or may not be called ever, in any particular order.
764 * They are likely to be invoked when something WRITE_SYNC is used used.
765 * They should follow a caching pattern as shown below, so that any code
766 * using the work will get it's result no matter what happens.
767 * @code
768 * $result = null;
769 * $workCallback = function () use ( &$result ) {
770 * if ( !$result ) {
771 * $result = ....
772 * }
773 * return $result;
774 * }
775 * @endcode
776 *
777 * @param callable $workCallback
778 * @since 1.28
779 */
780 final public function addBusyCallback( callable $workCallback ) {
781 $this->busyCallbacks[] = $workCallback;
782 }
783
784 /**
785 * @param int $exptime
786 * @return bool
787 */
788 final protected function expiryIsRelative( $exptime ) {
789 return ( $exptime != 0 && $exptime < ( 10 * self::TTL_YEAR ) );
790 }
791
792 /**
793 * Convert an optionally relative timestamp to an absolute time
794 *
795 * The input value will be cast to an integer and interpreted as follows:
796 * - zero: no expiry; return zero (e.g. TTL_INDEFINITE)
797 * - negative: relative TTL; return UNIX timestamp offset by this value
798 * - positive (< 10 years): relative TTL; return UNIX timestamp offset by this value
799 * - positive (>= 10 years): absolute UNIX timestamp; return this value
800 *
801 * @param int $exptime Absolute TTL or 0 for indefinite
802 * @return int
803 */
804 final protected function convertToExpiry( $exptime ) {
805 return $this->expiryIsRelative( $exptime )
806 ? (int)$this->getCurrentTime() + $exptime
807 : $exptime;
808 }
809
810 /**
811 * Convert an optionally absolute expiry time to a relative time. If an
812 * absolute time is specified which is in the past, use a short expiry time.
813 *
814 * @param int $exptime
815 * @return int
816 */
817 final protected function convertToRelative( $exptime ) {
818 return $this->expiryIsRelative( $exptime )
819 ? (int)$exptime
820 : max( $exptime - (int)$this->getCurrentTime(), 1 );
821 }
822
823 /**
824 * Check if a value is an integer
825 *
826 * @param mixed $value
827 * @return bool
828 */
829 final protected function isInteger( $value ) {
830 if ( is_int( $value ) ) {
831 return true;
832 } elseif ( !is_string( $value ) ) {
833 return false;
834 }
835
836 $integer = (int)$value;
837
838 return ( $value === (string)$integer );
839 }
840
841 /**
842 * Construct a cache key.
843 *
844 * @param string $keyspace
845 * @param array $args
846 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
847 * @since 1.27
848 */
849 public function makeKeyInternal( $keyspace, $args ) {
850 $key = $keyspace;
851 foreach ( $args as $arg ) {
852 $key .= ':' . str_replace( ':', '%3A', $arg );
853 }
854 return strtr( $key, ' ', '_' );
855 }
856
857 /**
858 * Make a global cache key.
859 *
860 * @param string $class Key class
861 * @param string|null $component [optional] Key component (starting with a key collection name)
862 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
863 * @since 1.27
864 */
865 public function makeGlobalKey( $class, $component = null ) {
866 return $this->makeKeyInternal( 'global', func_get_args() );
867 }
868
869 /**
870 * Make a cache key, scoped to this instance's keyspace.
871 *
872 * @param string $class Key class
873 * @param string|null $component [optional] Key component (starting with a key collection name)
874 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
875 * @since 1.27
876 */
877 public function makeKey( $class, $component = null ) {
878 return $this->makeKeyInternal( $this->keyspace, func_get_args() );
879 }
880
881 /**
882 * @param int $flag ATTR_* class constant
883 * @return int QOS_* class constant
884 * @since 1.28
885 */
886 public function getQoS( $flag ) {
887 return $this->attrMap[$flag] ?? self::QOS_UNKNOWN;
888 }
889
890 /**
891 * @return int|float The chunk size, in bytes, of segmented objects (INF for no limit)
892 * @since 1.34
893 */
894 public function getSegmentationSize() {
895 return $this->segmentationSize;
896 }
897
898 /**
899 * @return int|float Maximum total segmented object size in bytes (INF for no limit)
900 * @since 1.34
901 */
902 public function getSegmentedValueMaxSize() {
903 return $this->segmentedValueMaxSize;
904 }
905
906 /**
907 * @param mixed $value
908 * @return string|int String/integer representation
909 * @note Special handling is usually needed for integers so incr()/decr() work
910 */
911 protected function serialize( $value ) {
912 return is_int( $value ) ? $value : serialize( $value );
913 }
914
915 /**
916 * @param string|int $value
917 * @return mixed Original value or false on error
918 * @note Special handling is usually needed for integers so incr()/decr() work
919 */
920 protected function unserialize( $value ) {
921 return $this->isInteger( $value ) ? (int)$value : unserialize( $value );
922 }
923
924 /**
925 * @param string $text
926 */
927 protected function debug( $text ) {
928 if ( $this->debugMode ) {
929 $this->logger->debug( "{class} debug: $text", [ 'class' => static::class ] );
930 }
931 }
932 }