3 * Copyright © 2003-2004 Brion Vibber <brion@pobox.com>
4 * https://www.mediawiki.org/
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
26 * @defgroup Cache Cache
29 use Psr\Log\LoggerAwareInterface
;
30 use Psr\Log\LoggerInterface
;
31 use Psr\Log\NullLogger
;
32 use Wikimedia\ScopedCallback
;
33 use Wikimedia\WaitConditionLoop
;
36 * Class representing a cache/ephemeral data store
38 * This interface is intended to be more or less compatible with the PHP memcached client.
40 * Instances of this class should be created with an intended access scope, such as:
41 * - a) A single PHP thread on a server (e.g. stored in a PHP variable)
42 * - b) A single application server (e.g. stored in APC or sqlite)
43 * - c) All application servers in datacenter (e.g. stored in memcached or mysql)
44 * - d) All application servers in all datacenters (e.g. stored via mcrouter or dynomite)
46 * Callers should use the proper factory methods that yield BagOStuff instances. Site admins
47 * should make sure the configuration for those factory methods matches their access scope.
48 * BagOStuff subclasses have widely varying levels of support for replication features.
50 * For any given instance, methods like lock(), unlock(), merge(), and set() with WRITE_SYNC
51 * should semantically operate over its entire access scope; any nodes/threads in that scope
52 * should serialize appropriately when using them. Likewise, a call to get() with READ_LATEST
53 * from one node in its access scope should reflect the prior changes of any other node its
54 * access scope. Any get() should reflect the changes of any prior set() with WRITE_SYNC.
56 * Subclasses should override the default "segmentationSize" field with an appropriate value.
57 * The value should not be larger than what the storage backend (by default) supports. It also
58 * should be roughly informed by common performance bottlenecks (e.g. values over a certain size
59 * having poor scalability). The same goes for the "segmentedValueMaxSize" member, which limits
60 * the maximum size and chunk count (indirectly) of values.
64 abstract class BagOStuff
implements IExpiringStore
, LoggerAwareInterface
{
65 /** @var array[] Lock tracking */
66 protected $locks = [];
67 /** @var int ERR_* class constant */
68 protected $lastError = self
::ERR_NONE
;
70 protected $keyspace = 'local';
71 /** @var LoggerInterface */
73 /** @var callable|null */
74 protected $asyncHandler;
75 /** @var int Seconds */
76 protected $syncTimeout;
77 /** @var int Bytes; chunk size of segmented cache values */
78 protected $segmentationSize;
79 /** @var int Bytes; maximum total size of a segmented cache value */
80 protected $segmentedValueMaxSize;
83 private $debugMode = false;
85 private $duplicateKeyLookups = [];
87 private $reportDupes = false;
89 private $dupeTrackScheduled = false;
91 /** @var callable[] */
92 protected $busyCallbacks = [];
94 /** @var float|null */
95 private $wallClockOverride;
97 /** @var int[] Map of (ATTR_* class constant => QOS_* class constant) */
98 protected $attrMap = [];
100 /** Bitfield constants for get()/getMulti() */
101 const READ_LATEST
= 1; // use latest data for replicated stores
102 const READ_VERIFIED
= 2; // promise that caller can tell when keys are stale
103 /** Bitfield constants for set()/merge() */
104 const WRITE_SYNC
= 4; // synchronously write to all locations for replicated stores
105 const WRITE_CACHE_ONLY
= 8; // Only change state of the in-memory cache
106 const WRITE_ALLOW_SEGMENTS
= 16; // Allow partitioning of the value if it is large
107 const WRITE_PRUNE_SEGMENTS
= 32; // Delete all partition segments of the value
109 /** @var string Component to use for key construction of blob segment keys */
110 const SEGMENT_COMPONENT
= 'segment';
114 * - logger: Psr\Log\LoggerInterface instance
115 * - keyspace: Default keyspace for $this->makeKey()
116 * - asyncHandler: Callable to use for scheduling tasks after the web request ends.
117 * In CLI mode, it should run the task immediately.
118 * - reportDupes: Whether to emit warning log messages for all keys that were
119 * requested more than once (requires an asyncHandler).
120 * - syncTimeout: How long to wait with WRITE_SYNC in seconds.
121 * - segmentationSize: The chunk size, in bytes, of segmented values. The value should
122 * not exceed the maximum size of values in the storage backend, as configured by
123 * the site administrator.
124 * - segmentedValueMaxSize: The maximum total size, in bytes, of segmented values.
125 * This should be configured to a reasonable size give the site traffic and the
126 * amount of I/O between application and cache servers that the network can handle.
127 * @param array $params
129 public function __construct( array $params = [] ) {
130 $this->setLogger( $params['logger'] ??
new NullLogger() );
132 if ( isset( $params['keyspace'] ) ) {
133 $this->keyspace
= $params['keyspace'];
136 $this->asyncHandler
= $params['asyncHandler'] ??
null;
138 if ( !empty( $params['reportDupes'] ) && is_callable( $this->asyncHandler
) ) {
139 $this->reportDupes
= true;
142 $this->syncTimeout
= $params['syncTimeout'] ??
3;
143 $this->segmentationSize
= $params['segmentationSize'] ??
8388608; // 8MiB
144 $this->segmentedValueMaxSize
= $params['segmentedValueMaxSize'] ??
67108864; // 64MiB
148 * @param LoggerInterface $logger
151 public function setLogger( LoggerInterface
$logger ) {
152 $this->logger
= $logger;
158 public function setDebug( $bool ) {
159 $this->debugMode
= $bool;
163 * Get an item with the given key, regenerating and setting it if not found
165 * Nothing is stored nor deleted if the callback returns false
168 * @param int $ttl Time-to-live (seconds)
169 * @param callable $callback Callback that derives the new value
170 * @param int $flags Bitfield of BagOStuff::READ_* or BagOStuff::WRITE_* constants [optional]
171 * @return mixed The cached value if found or the result of $callback otherwise
174 final public function getWithSetCallback( $key, $ttl, $callback, $flags = 0 ) {
175 $value = $this->get( $key, $flags );
177 if ( $value === false ) {
178 if ( !is_callable( $callback ) ) {
179 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
181 $value = call_user_func( $callback );
182 if ( $value !== false ) {
183 $this->set( $key, $value, $ttl, $flags );
191 * Get an item with the given key
193 * If the key includes a deterministic input hash (e.g. the key can only have
194 * the correct value) or complete staleness checks are handled by the caller
195 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
196 * This lets tiered backends know they can safely upgrade a cached value to
197 * higher tiers using standard TTLs.
200 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
201 * @return mixed Returns false on failure or if the item does not exist
203 public function get( $key, $flags = 0 ) {
204 $this->trackDuplicateKeys( $key );
206 return $this->resolveSegments( $key, $this->doGet( $key, $flags ) );
210 * Track the number of times that a given key has been used.
213 private function trackDuplicateKeys( $key ) {
214 if ( !$this->reportDupes
) {
218 if ( !isset( $this->duplicateKeyLookups
[$key] ) ) {
219 // Track that we have seen this key. This N-1 counting style allows
220 // easy filtering with array_filter() later.
221 $this->duplicateKeyLookups
[$key] = 0;
223 $this->duplicateKeyLookups
[$key] +
= 1;
225 if ( $this->dupeTrackScheduled
=== false ) {
226 $this->dupeTrackScheduled
= true;
227 // Schedule a callback that logs keys processed more than once by get().
228 call_user_func( $this->asyncHandler
, function () {
229 $dups = array_filter( $this->duplicateKeyLookups
);
230 foreach ( $dups as $key => $count ) {
231 $this->logger
->warning(
232 'Duplicate get(): "{key}" fetched {count} times',
233 // Count is N-1 of the actual lookup count
234 [ 'key' => $key, 'count' => $count +
1, ]
244 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
245 * @param mixed|null &$casToken Token to use for check-and-set comparisons
246 * @return mixed Returns false on failure or if the item does not exist
248 abstract protected function doGet( $key, $flags = 0, &$casToken = null );
254 * @param mixed $value
255 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
256 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
257 * @return bool Success
259 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
261 ( $flags & self
::WRITE_ALLOW_SEGMENTS
) != self
::WRITE_ALLOW_SEGMENTS ||
262 is_infinite( $this->segmentationSize
)
264 return $this->doSet( $key, $value, $exptime, $flags );
267 $serialized = $this->serialize( $value );
268 $segmentSize = $this->getSegmentationSize();
269 $maxTotalSize = $this->getSegmentedValueMaxSize();
271 $size = strlen( $serialized );
272 if ( $size <= $segmentSize ) {
273 // Since the work of serializing it was already done, just use it inline
276 SerializedValueContainer
::newUnified( $serialized ),
280 } elseif ( $size > $maxTotalSize ) {
281 $this->setLastError( "Key $key exceeded $maxTotalSize bytes." );
288 $count = intdiv( $size, $segmentSize ) +
( ( $size %
$segmentSize ) ?
1 : 0 );
289 for ( $i = 0; $i < $count; ++
$i ) {
290 $segment = substr( $serialized, $i * $segmentSize, $segmentSize );
291 $hash = sha1( $segment );
292 $chunkKey = $this->makeGlobalKey( self
::SEGMENT_COMPONENT
, $key, $hash );
293 $chunksByKey[$chunkKey] = $segment;
294 $segmentHashes[] = $hash;
297 $ok = $this->setMulti( $chunksByKey, $exptime, $flags );
299 // Only when all segments are stored should the main key be changed
302 SerializedValueContainer
::newSegmented( $segmentHashes ),
315 * @param mixed $value
316 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
317 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
318 * @return bool Success
320 abstract protected function doSet( $key, $value, $exptime = 0, $flags = 0 );
325 * For large values written using WRITE_ALLOW_SEGMENTS, this only deletes the main
326 * segment list key unless WRITE_PRUNE_SEGMENTS is in the flags. While deleting the segment
327 * list key has the effect of functionally deleting the key, it leaves unused blobs in cache.
330 * @return bool True if the item was deleted or not found, false on failure
331 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
333 public function delete( $key, $flags = 0 ) {
334 if ( ( $flags & self
::WRITE_PRUNE_SEGMENTS
) != self
::WRITE_PRUNE_SEGMENTS
) {
335 return $this->doDelete( $key, $flags );
338 $mainValue = $this->doGet( $key, self
::READ_LATEST
);
339 if ( !$this->doDelete( $key, $flags ) ) {
343 if ( !SerializedValueContainer
::isSegmented( $mainValue ) ) {
344 return true; // no segments to delete
347 $orderedKeys = array_map(
348 function ( $segmentHash ) use ( $key ) {
349 return $this->makeGlobalKey( self
::SEGMENT_COMPONENT
, $key, $segmentHash );
351 $mainValue->{SerializedValueContainer
::SEGMENTED_HASHES
}
354 return $this->deleteMulti( $orderedKeys, $flags );
361 * @return bool True if the item was deleted or not found, false on failure
362 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
364 abstract protected function doDelete( $key, $flags = 0 );
367 * Insert an item if it does not already exist
370 * @param mixed $value
371 * @param int $exptime
372 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
373 * @return bool Success
375 abstract public function add( $key, $value, $exptime = 0, $flags = 0 );
378 * Merge changes into the existing cache value (possibly creating a new one)
380 * The callback function returns the new value given the current value
381 * (which will be false if not present), and takes the arguments:
382 * (this BagOStuff, cache key, current value, TTL).
383 * The TTL parameter is reference set to $exptime. It can be overriden in the callback.
384 * Nothing is stored nor deleted if the callback returns false.
387 * @param callable $callback Callback method to be executed
388 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
389 * @param int $attempts The amount of times to attempt a merge in case of failure
390 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
391 * @return bool Success
392 * @throws InvalidArgumentException
394 public function merge( $key, callable
$callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
395 return $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
399 * @see BagOStuff::merge()
402 * @param callable $callback Callback method to be executed
403 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
404 * @param int $attempts The amount of times to attempt a merge in case of failure
405 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
406 * @return bool Success
408 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
410 $casToken = null; // passed by reference
411 // Get the old value and CAS token from cache
412 $this->clearLastError();
413 $currentValue = $this->resolveSegments(
415 $this->doGet( $key, self
::READ_LATEST
, $casToken )
417 if ( $this->getLastError() ) {
418 $this->logger
->warning(
419 __METHOD__
. ' failed due to I/O error on get() for {key}.',
423 return false; // don't spam retries (retry only on races)
426 // Derive the new value from the old value
427 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
428 $hadNoCurrentValue = ( $currentValue === false );
429 unset( $currentValue ); // free RAM in case the value is large
431 $this->clearLastError();
432 if ( $value === false ) {
433 $success = true; // do nothing
434 } elseif ( $hadNoCurrentValue ) {
435 // Try to create the key, failing if it gets created in the meantime
436 $success = $this->add( $key, $value, $exptime, $flags );
438 // Try to update the key, failing if it gets changed in the meantime
439 $success = $this->cas( $casToken, $key, $value, $exptime, $flags );
441 if ( $this->getLastError() ) {
442 $this->logger
->warning(
443 __METHOD__
. ' failed due to I/O error for {key}.',
447 return false; // IO error; don't spam retries
450 } while ( !$success && --$attempts );
456 * Check and set an item
458 * @param mixed $casToken
460 * @param mixed $value
461 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
462 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
463 * @return bool Success
465 protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
466 if ( !$this->lock( $key, 0 ) ) {
467 return false; // non-blocking
470 $curCasToken = null; // passed by reference
471 $this->doGet( $key, self
::READ_LATEST
, $curCasToken );
472 if ( $casToken === $curCasToken ) {
473 $success = $this->set( $key, $value, $exptime, $flags );
476 __METHOD__
. ' failed due to race condition for {key}.',
480 $success = false; // mismatched or failed
483 $this->unlock( $key );
489 * Change the expiration on a key if it exists
491 * If an expiry in the past is given then the key will immediately be expired
493 * For large values written using WRITE_ALLOW_SEGMENTS, this only changes the TTL of the
494 * main segment list key. While lowering the TTL of the segment list key has the effect of
495 * functionally lowering the TTL of the key, it might leave unused blobs in cache for longer.
496 * Raising the TTL of such keys is not effective, since the expiration of a single segment
497 * key effectively expires the entire value.
500 * @param int $exptime TTL or UNIX timestamp
501 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
502 * @return bool Success Returns false on failure or if the item does not exist
505 public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
506 $expiry = $this->convertToExpiry( $exptime );
507 $delete = ( $expiry != 0 && $expiry < $this->getCurrentTime() );
509 if ( !$this->lock( $key, 0 ) ) {
512 // Use doGet() to avoid having to trigger resolveSegments()
513 $blob = $this->doGet( $key, self
::READ_LATEST
);
516 $ok = $this->doDelete( $key, $flags );
518 $ok = $this->doSet( $key, $blob, $exptime, $flags );
524 $this->unlock( $key );
530 * Acquire an advisory lock on a key string
532 * Note that if reentry is enabled, duplicate calls ignore $expiry
535 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
536 * @param int $expiry Lock expiry [optional]; 1 day maximum
537 * @param string $rclass Allow reentry if set and the current lock used this value
538 * @return bool Success
540 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
541 // Avoid deadlocks and allow lock reentry if specified
542 if ( isset( $this->locks
[$key] ) ) {
543 if ( $rclass != '' && $this->locks
[$key]['class'] === $rclass ) {
544 ++
$this->locks
[$key]['depth'];
552 $expiry = min( $expiry ?
: INF
, self
::TTL_DAY
);
553 $loop = new WaitConditionLoop(
554 function () use ( $key, $expiry, $fname ) {
555 $this->clearLastError();
556 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
557 return WaitConditionLoop
::CONDITION_REACHED
; // locked!
558 } elseif ( $this->getLastError() ) {
559 $this->logger
->warning(
560 $fname . ' failed due to I/O error for {key}.',
564 return WaitConditionLoop
::CONDITION_ABORTED
; // network partition?
567 return WaitConditionLoop
::CONDITION_CONTINUE
;
572 $code = $loop->invoke();
573 $locked = ( $code === $loop::CONDITION_REACHED
);
575 $this->locks
[$key] = [ 'class' => $rclass, 'depth' => 1 ];
576 } elseif ( $code === $loop::CONDITION_TIMED_OUT
) {
577 $this->logger
->warning(
578 "$fname failed due to timeout for {key}.",
579 [ 'key' => $key, 'timeout' => $timeout ]
587 * Release an advisory lock on a key string
590 * @return bool Success
592 public function unlock( $key ) {
593 if ( isset( $this->locks
[$key] ) && --$this->locks
[$key]['depth'] <= 0 ) {
594 unset( $this->locks
[$key] );
596 $ok = $this->doDelete( "{$key}:lock" );
598 $this->logger
->warning(
599 __METHOD__
. ' failed to release lock for {key}.',
611 * Get a lightweight exclusive self-unlocking lock
613 * Note that the same lock cannot be acquired twice.
615 * This is useful for task de-duplication or to avoid obtrusive
616 * (though non-corrupting) DB errors like INSERT key conflicts
617 * or deadlocks when using LOCK IN SHARE MODE.
620 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
621 * @param int $expiry Lock expiry [optional]; 1 day maximum
622 * @param string $rclass Allow reentry if set and the current lock used this value
623 * @return ScopedCallback|null Returns null on failure
626 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
627 $expiry = min( $expiry ?
: INF
, self
::TTL_DAY
);
629 if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
633 $lSince = $this->getCurrentTime(); // lock timestamp
635 return new ScopedCallback( function () use ( $key, $lSince, $expiry ) {
636 $latency = 0.050; // latency skew (err towards keeping lock present)
637 $age = ( $this->getCurrentTime() - $lSince +
$latency );
638 if ( ( $age +
$latency ) >= $expiry ) {
639 $this->logger
->warning(
640 "Lock for {key} held too long ({age} sec).",
641 [ 'key' => $key, 'age' => $age ]
643 return; // expired; it's not "safe" to delete the key
645 $this->unlock( $key );
650 * Delete all objects expiring before a certain date.
651 * @param string $date The reference date in MW format
652 * @param callable|bool $progressCallback Optional, a function which will be called
653 * regularly during long-running operations with the percentage progress
654 * as the first parameter.
656 * @return bool Success, false if unimplemented
658 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
664 * Get an associative array containing the item for each of the keys that have items.
665 * @param string[] $keys List of keys
666 * @param int $flags Bitfield; supports READ_LATEST [optional]
669 public function getMulti( array $keys, $flags = 0 ) {
670 $valuesBykey = $this->doGetMulti( $keys, $flags );
671 foreach ( $valuesBykey as $key => $value ) {
672 // Resolve one blob at a time (avoids too much I/O at once)
673 $valuesBykey[$key] = $this->resolveSegments( $key, $value );
680 * Get an associative array containing the item for each of the keys that have items.
681 * @param string[] $keys List of keys
682 * @param int $flags Bitfield; supports READ_LATEST [optional]
685 protected function doGetMulti( array $keys, $flags = 0 ) {
687 foreach ( $keys as $key ) {
688 $val = $this->doGet( $key, $flags );
689 if ( $val !== false ) {
698 * Batch insertion/replace
700 * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O
702 * @param mixed[] $data Map of (key => value)
703 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
704 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
705 * @return bool Success
708 public function setMulti( array $data, $exptime = 0, $flags = 0 ) {
709 if ( ( $flags & self
::WRITE_ALLOW_SEGMENTS
) === self
::WRITE_ALLOW_SEGMENTS
) {
710 throw new InvalidArgumentException( __METHOD__
. ' got WRITE_ALLOW_SEGMENTS' );
714 foreach ( $data as $key => $value ) {
715 $res = $this->doSet( $key, $value, $exptime, $flags ) && $res;
724 * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O
726 * @param string[] $keys List of keys
727 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
728 * @return bool Success
731 public function deleteMulti( array $keys, $flags = 0 ) {
733 foreach ( $keys as $key ) {
734 $res = $this->doDelete( $key, $flags ) && $res;
741 * Increase stored value of $key by $value while preserving its TTL
742 * @param string $key Key to increase
743 * @param int $value Value to add to $key (default: 1) [optional]
744 * @return int|bool New value or false on failure
746 abstract public function incr( $key, $value = 1 );
749 * Decrease stored value of $key by $value while preserving its TTL
751 * @param int $value Value to subtract from $key (default: 1) [optional]
752 * @return int|bool New value or false on failure
754 public function decr( $key, $value = 1 ) {
755 return $this->incr( $key, - $value );
759 * Increase stored value of $key by $value while preserving its TTL
761 * This will create the key with value $init and TTL $ttl instead if not present
767 * @return int|bool New value or false on failure
770 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
771 $this->clearLastError();
772 $newValue = $this->incr( $key, $value );
773 if ( $newValue === false && !$this->getLastError() ) {
774 // No key set; initialize
775 $newValue = $this->add( $key, (int)$init, $ttl ) ?
$init : false;
776 if ( $newValue === false && !$this->getLastError() ) {
777 // Raced out initializing; increment
778 $newValue = $this->incr( $key, $value );
786 * Get and reassemble the chunks of blob at the given key
789 * @param mixed $mainValue
790 * @return string|null|bool The combined string, false if missing, null on error
792 protected function resolveSegments( $key, $mainValue ) {
793 if ( SerializedValueContainer
::isUnified( $mainValue ) ) {
794 return $this->unserialize( $mainValue->{SerializedValueContainer
::UNIFIED_DATA
} );
797 if ( SerializedValueContainer
::isSegmented( $mainValue ) ) {
798 $orderedKeys = array_map(
799 function ( $segmentHash ) use ( $key ) {
800 return $this->makeGlobalKey( self
::SEGMENT_COMPONENT
, $key, $segmentHash );
802 $mainValue->{SerializedValueContainer
::SEGMENTED_HASHES
}
805 $segmentsByKey = $this->doGetMulti( $orderedKeys );
808 foreach ( $orderedKeys as $segmentKey ) {
809 if ( isset( $segmentsByKey[$segmentKey] ) ) {
810 $parts[] = $segmentsByKey[$segmentKey];
812 return false; // missing segment
816 return $this->unserialize( implode( '', $parts ) );
823 * Get the "last error" registered; clearLastError() should be called manually
824 * @return int ERR_* constant for the "last error" registry
827 public function getLastError() {
828 return $this->lastError
;
832 * Clear the "last error" registry
835 public function clearLastError() {
836 $this->lastError
= self
::ERR_NONE
;
840 * Set the "last error" registry
841 * @param int $err ERR_* constant
844 protected function setLastError( $err ) {
845 $this->lastError
= $err;
849 * Let a callback be run to avoid wasting time on special blocking calls
851 * The callbacks may or may not be called ever, in any particular order.
852 * They are likely to be invoked when something WRITE_SYNC is used used.
853 * They should follow a caching pattern as shown below, so that any code
854 * using the work will get it's result no matter what happens.
857 * $workCallback = function () use ( &$result ) {
865 * @param callable $workCallback
868 public function addBusyCallback( callable
$workCallback ) {
869 $this->busyCallbacks
[] = $workCallback;
873 * @param string $text
875 protected function debug( $text ) {
876 if ( $this->debugMode
) {
877 $this->logger
->debug( "{class} debug: $text", [
878 'class' => static::class,
884 * @param int $exptime
887 protected function expiryIsRelative( $exptime ) {
888 return ( $exptime != 0 && $exptime < ( 10 * self
::TTL_YEAR
) );
892 * Convert an optionally relative time to an absolute time
893 * @param int $exptime
896 protected function convertToExpiry( $exptime ) {
897 if ( $this->expiryIsRelative( $exptime ) ) {
898 return (int)$this->getCurrentTime() +
$exptime;
905 * Convert an optionally absolute expiry time to a relative time. If an
906 * absolute time is specified which is in the past, use a short expiry time.
908 * @param int $exptime
911 protected function convertToRelative( $exptime ) {
912 if ( $exptime >= ( 10 * self
::TTL_YEAR
) ) {
913 $exptime -= (int)$this->getCurrentTime();
914 if ( $exptime <= 0 ) {
924 * Check if a value is an integer
926 * @param mixed $value
929 protected function isInteger( $value ) {
930 if ( is_int( $value ) ) {
932 } elseif ( !is_string( $value ) ) {
936 $integer = (int)$value;
938 return ( $value === (string)$integer );
942 * Construct a cache key.
945 * @param string $keyspace
947 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
949 public function makeKeyInternal( $keyspace, $args ) {
951 foreach ( $args as $arg ) {
952 $key .= ':' . str_replace( ':', '%3A', $arg );
954 return strtr( $key, ' ', '_' );
958 * Make a global cache key.
961 * @param string $class Key class
962 * @param string|null $component [optional] Key component (starting with a key collection name)
963 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
965 public function makeGlobalKey( $class, $component = null ) {
966 return $this->makeKeyInternal( 'global', func_get_args() );
970 * Make a cache key, scoped to this instance's keyspace.
973 * @param string $class Key class
974 * @param string|null $component [optional] Key component (starting with a key collection name)
975 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
977 public function makeKey( $class, $component = null ) {
978 return $this->makeKeyInternal( $this->keyspace
, func_get_args() );
982 * @param int $flag ATTR_* class constant
983 * @return int QOS_* class constant
986 public function getQoS( $flag ) {
987 return $this->attrMap
[$flag] ?? self
::QOS_UNKNOWN
;
991 * @return int|float The chunk size, in bytes, of segmented objects (INF for no limit)
994 public function getSegmentationSize() {
995 return $this->segmentationSize
;
999 * @return int|float Maximum total segmented object size in bytes (INF for no limit)
1002 public function getSegmentedValueMaxSize() {
1003 return $this->segmentedValueMaxSize
;
1007 * Merge the flag maps of one or more BagOStuff objects into a "lowest common denominator" map
1009 * @param BagOStuff[] $bags
1010 * @return int[] Resulting flag map (class ATTR_* constant => class QOS_* constant)
1012 protected function mergeFlagMaps( array $bags ) {
1014 foreach ( $bags as $bag ) {
1015 foreach ( $bag->attrMap
as $attr => $rank ) {
1016 if ( isset( $map[$attr] ) ) {
1017 $map[$attr] = min( $map[$attr], $rank );
1019 $map[$attr] = $rank;
1028 * @internal For testing only
1029 * @return float UNIX timestamp
1030 * @codeCoverageIgnore
1032 public function getCurrentTime() {
1033 return $this->wallClockOverride ?
: microtime( true );
1037 * @internal For testing only
1038 * @param float|null &$time Mock UNIX timestamp
1039 * @codeCoverageIgnore
1041 public function setMockTime( &$time ) {
1042 $this->wallClockOverride
=& $time;
1046 * @param mixed $value
1047 * @return string|int String/integer representation
1048 * @note Special handling is usually needed for integers so incr()/decr() work
1050 protected function serialize( $value ) {
1051 return is_int( $value ) ?
$value : serialize( $value );
1055 * @param string|int $value
1056 * @return mixed Original value or false on error
1057 * @note Special handling is usually needed for integers so incr()/decr() work
1059 protected function unserialize( $value ) {
1060 return $this->isInteger( $value ) ?
(int)$value : unserialize( $value );