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
, IStoreKeyEncoder
, 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(); these are only advisory */
101 const READ_LATEST
= 1; // if supported, avoid reading stale data due to replication
102 const READ_VERIFIED
= 2; // promise that the caller handles detection of staleness
103 /** Bitfield constants for set()/merge(); these are only advisory */
104 const WRITE_SYNC
= 4; // if supported, block until the write is fully replicated
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 the segments if the value is partitioned
108 const WRITE_BACKGROUND
= 64; // if supported,
110 /** @var string Component to use for key construction of blob segment keys */
111 const SEGMENT_COMPONENT
= 'segment';
115 * - logger: Psr\Log\LoggerInterface instance
116 * - keyspace: Default keyspace for $this->makeKey()
117 * - asyncHandler: Callable to use for scheduling tasks after the web request ends.
118 * In CLI mode, it should run the task immediately.
119 * - reportDupes: Whether to emit warning log messages for all keys that were
120 * requested more than once (requires an asyncHandler).
121 * - syncTimeout: How long to wait with WRITE_SYNC in seconds.
122 * - segmentationSize: The chunk size, in bytes, of segmented values. The value should
123 * not exceed the maximum size of values in the storage backend, as configured by
124 * the site administrator.
125 * - segmentedValueMaxSize: The maximum total size, in bytes, of segmented values.
126 * This should be configured to a reasonable size give the site traffic and the
127 * amount of I/O between application and cache servers that the network can handle.
128 * @param array $params
130 public function __construct( array $params = [] ) {
131 $this->setLogger( $params['logger'] ??
new NullLogger() );
133 if ( isset( $params['keyspace'] ) ) {
134 $this->keyspace
= $params['keyspace'];
137 $this->asyncHandler
= $params['asyncHandler'] ??
null;
139 if ( !empty( $params['reportDupes'] ) && is_callable( $this->asyncHandler
) ) {
140 $this->reportDupes
= true;
143 $this->syncTimeout
= $params['syncTimeout'] ??
3;
144 $this->segmentationSize
= $params['segmentationSize'] ??
8388608; // 8MiB
145 $this->segmentedValueMaxSize
= $params['segmentedValueMaxSize'] ??
67108864; // 64MiB
149 * @param LoggerInterface $logger
152 public function setLogger( LoggerInterface
$logger ) {
153 $this->logger
= $logger;
159 public function setDebug( $bool ) {
160 $this->debugMode
= $bool;
164 * Get an item with the given key, regenerating and setting it if not found
166 * Nothing is stored nor deleted if the callback returns false
169 * @param int $ttl Time-to-live (seconds)
170 * @param callable $callback Callback that derives the new value
171 * @param int $flags Bitfield of BagOStuff::READ_* or BagOStuff::WRITE_* constants [optional]
172 * @return mixed The cached value if found or the result of $callback otherwise
175 final public function getWithSetCallback( $key, $ttl, $callback, $flags = 0 ) {
176 $value = $this->get( $key, $flags );
178 if ( $value === false ) {
179 if ( !is_callable( $callback ) ) {
180 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
182 $value = call_user_func( $callback );
183 if ( $value !== false ) {
184 $this->set( $key, $value, $ttl, $flags );
192 * Get an item with the given key
194 * If the key includes a deterministic input hash (e.g. the key can only have
195 * the correct value) or complete staleness checks are handled by the caller
196 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
197 * This lets tiered backends know they can safely upgrade a cached value to
198 * higher tiers using standard TTLs.
201 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
202 * @return mixed Returns false on failure or if the item does not exist
204 public function get( $key, $flags = 0 ) {
205 $this->trackDuplicateKeys( $key );
207 return $this->resolveSegments( $key, $this->doGet( $key, $flags ) );
211 * Track the number of times that a given key has been used.
214 private function trackDuplicateKeys( $key ) {
215 if ( !$this->reportDupes
) {
219 if ( !isset( $this->duplicateKeyLookups
[$key] ) ) {
220 // Track that we have seen this key. This N-1 counting style allows
221 // easy filtering with array_filter() later.
222 $this->duplicateKeyLookups
[$key] = 0;
224 $this->duplicateKeyLookups
[$key] +
= 1;
226 if ( $this->dupeTrackScheduled
=== false ) {
227 $this->dupeTrackScheduled
= true;
228 // Schedule a callback that logs keys processed more than once by get().
229 call_user_func( $this->asyncHandler
, function () {
230 $dups = array_filter( $this->duplicateKeyLookups
);
231 foreach ( $dups as $key => $count ) {
232 $this->logger
->warning(
233 'Duplicate get(): "{key}" fetched {count} times',
234 // Count is N-1 of the actual lookup count
235 [ 'key' => $key, 'count' => $count +
1, ]
245 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
246 * @param mixed|null &$casToken Token to use for check-and-set comparisons
247 * @return mixed Returns false on failure or if the item does not exist
249 abstract protected function doGet( $key, $flags = 0, &$casToken = null );
255 * @param mixed $value
256 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
257 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
258 * @return bool Success
260 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
262 is_int( $value ) ||
// avoid breaking incr()/decr()
263 ( $flags & self
::WRITE_ALLOW_SEGMENTS
) != self
::WRITE_ALLOW_SEGMENTS ||
264 is_infinite( $this->segmentationSize
)
266 return $this->doSet( $key, $value, $exptime, $flags );
269 $serialized = $this->serialize( $value );
270 $segmentSize = $this->getSegmentationSize();
271 $maxTotalSize = $this->getSegmentedValueMaxSize();
273 $size = strlen( $serialized );
274 if ( $size <= $segmentSize ) {
275 // Since the work of serializing it was already done, just use it inline
278 SerializedValueContainer
::newUnified( $serialized ),
282 } elseif ( $size > $maxTotalSize ) {
283 $this->setLastError( "Key $key exceeded $maxTotalSize bytes." );
290 $count = intdiv( $size, $segmentSize ) +
( ( $size %
$segmentSize ) ?
1 : 0 );
291 for ( $i = 0; $i < $count; ++
$i ) {
292 $segment = substr( $serialized, $i * $segmentSize, $segmentSize );
293 $hash = sha1( $segment );
294 $chunkKey = $this->makeGlobalKey( self
::SEGMENT_COMPONENT
, $key, $hash );
295 $chunksByKey[$chunkKey] = $segment;
296 $segmentHashes[] = $hash;
299 $flags &= ~self
::WRITE_ALLOW_SEGMENTS
; // sanity
300 $ok = $this->setMulti( $chunksByKey, $exptime, $flags );
302 // Only when all segments are stored should the main key be changed
305 SerializedValueContainer
::newSegmented( $segmentHashes ),
318 * @param mixed $value
319 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
320 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
321 * @return bool Success
323 abstract protected function doSet( $key, $value, $exptime = 0, $flags = 0 );
328 * For large values written using WRITE_ALLOW_SEGMENTS, this only deletes the main
329 * segment list key unless WRITE_PRUNE_SEGMENTS is in the flags. While deleting the segment
330 * list key has the effect of functionally deleting the key, it leaves unused blobs in cache.
333 * @return bool True if the item was deleted or not found, false on failure
334 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
336 public function delete( $key, $flags = 0 ) {
337 if ( ( $flags & self
::WRITE_PRUNE_SEGMENTS
) != self
::WRITE_PRUNE_SEGMENTS
) {
338 return $this->doDelete( $key, $flags );
341 $mainValue = $this->doGet( $key, self
::READ_LATEST
);
342 if ( !$this->doDelete( $key, $flags ) ) {
346 if ( !SerializedValueContainer
::isSegmented( $mainValue ) ) {
347 return true; // no segments to delete
350 $orderedKeys = array_map(
351 function ( $segmentHash ) use ( $key ) {
352 return $this->makeGlobalKey( self
::SEGMENT_COMPONENT
, $key, $segmentHash );
354 $mainValue->{SerializedValueContainer
::SEGMENTED_HASHES
}
357 return $this->deleteMulti( $orderedKeys, $flags );
364 * @return bool True if the item was deleted or not found, false on failure
365 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
367 abstract protected function doDelete( $key, $flags = 0 );
370 * Insert an item if it does not already exist
373 * @param mixed $value
374 * @param int $exptime
375 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
376 * @return bool Success
378 abstract public function add( $key, $value, $exptime = 0, $flags = 0 );
381 * Merge changes into the existing cache value (possibly creating a new one)
383 * The callback function returns the new value given the current value
384 * (which will be false if not present), and takes the arguments:
385 * (this BagOStuff, cache key, current value, TTL).
386 * The TTL parameter is reference set to $exptime. It can be overriden in the callback.
387 * Nothing is stored nor deleted if the callback returns false.
390 * @param callable $callback Callback method to be executed
391 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
392 * @param int $attempts The amount of times to attempt a merge in case of failure
393 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
394 * @return bool Success
395 * @throws InvalidArgumentException
397 public function merge( $key, callable
$callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
398 return $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
402 * @see BagOStuff::merge()
405 * @param callable $callback Callback method to be executed
406 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
407 * @param int $attempts The amount of times to attempt a merge in case of failure
408 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
409 * @return bool Success
411 final protected function mergeViaCas( $key, callable
$callback, $exptime, $attempts, $flags ) {
413 $casToken = null; // passed by reference
414 // Get the old value and CAS token from cache
415 $this->clearLastError();
416 $currentValue = $this->resolveSegments(
418 $this->doGet( $key, self
::READ_LATEST
, $casToken )
420 if ( $this->getLastError() ) {
421 $this->logger
->warning(
422 __METHOD__
. ' failed due to I/O error on get() for {key}.',
426 return false; // don't spam retries (retry only on races)
429 // Derive the new value from the old value
430 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
431 $hadNoCurrentValue = ( $currentValue === false );
432 unset( $currentValue ); // free RAM in case the value is large
434 $this->clearLastError();
435 if ( $value === false ) {
436 $success = true; // do nothing
437 } elseif ( $hadNoCurrentValue ) {
438 // Try to create the key, failing if it gets created in the meantime
439 $success = $this->add( $key, $value, $exptime, $flags );
441 // Try to update the key, failing if it gets changed in the meantime
442 $success = $this->cas( $casToken, $key, $value, $exptime, $flags );
444 if ( $this->getLastError() ) {
445 $this->logger
->warning(
446 __METHOD__
. ' failed due to I/O error for {key}.',
450 return false; // IO error; don't spam retries
453 } while ( !$success && --$attempts );
459 * Check and set an item
461 * @param mixed $casToken
463 * @param mixed $value
464 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
465 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
466 * @return bool Success
468 protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
469 if ( !$this->lock( $key, 0 ) ) {
470 return false; // non-blocking
473 $curCasToken = null; // passed by reference
474 $this->doGet( $key, self
::READ_LATEST
, $curCasToken );
475 if ( $casToken === $curCasToken ) {
476 $success = $this->set( $key, $value, $exptime, $flags );
479 __METHOD__
. ' failed due to race condition for {key}.',
483 $success = false; // mismatched or failed
486 $this->unlock( $key );
492 * Change the expiration on a key if it exists
494 * If an expiry in the past is given then the key will immediately be expired
496 * For large values written using WRITE_ALLOW_SEGMENTS, this only changes the TTL of the
497 * main segment list key. While lowering the TTL of the segment list key has the effect of
498 * functionally lowering the TTL of the key, it might leave unused blobs in cache for longer.
499 * Raising the TTL of such keys is not effective, since the expiration of a single segment
500 * key effectively expires the entire value.
503 * @param int $exptime TTL or UNIX timestamp
504 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
505 * @return bool Success Returns false on failure or if the item does not exist
508 public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
509 return $this->doChangeTTL( $key, $exptime, $flags );
514 * @param int $exptime
518 protected function doChangeTTL( $key, $exptime, $flags ) {
519 $expiry = $this->convertToExpiry( $exptime );
520 $delete = ( $expiry != 0 && $expiry < $this->getCurrentTime() );
522 if ( !$this->lock( $key, 0 ) ) {
525 // Use doGet() to avoid having to trigger resolveSegments()
526 $blob = $this->doGet( $key, self
::READ_LATEST
);
529 $ok = $this->doDelete( $key, $flags );
531 $ok = $this->doSet( $key, $blob, $exptime, $flags );
537 $this->unlock( $key );
543 * Acquire an advisory lock on a key string
545 * Note that if reentry is enabled, duplicate calls ignore $expiry
548 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
549 * @param int $expiry Lock expiry [optional]; 1 day maximum
550 * @param string $rclass Allow reentry if set and the current lock used this value
551 * @return bool Success
553 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
554 // Avoid deadlocks and allow lock reentry if specified
555 if ( isset( $this->locks
[$key] ) ) {
556 if ( $rclass != '' && $this->locks
[$key]['class'] === $rclass ) {
557 ++
$this->locks
[$key]['depth'];
565 $expiry = min( $expiry ?
: INF
, self
::TTL_DAY
);
566 $loop = new WaitConditionLoop(
567 function () use ( $key, $expiry, $fname ) {
568 $this->clearLastError();
569 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
570 return WaitConditionLoop
::CONDITION_REACHED
; // locked!
571 } elseif ( $this->getLastError() ) {
572 $this->logger
->warning(
573 $fname . ' failed due to I/O error for {key}.',
577 return WaitConditionLoop
::CONDITION_ABORTED
; // network partition?
580 return WaitConditionLoop
::CONDITION_CONTINUE
;
585 $code = $loop->invoke();
586 $locked = ( $code === $loop::CONDITION_REACHED
);
588 $this->locks
[$key] = [ 'class' => $rclass, 'depth' => 1 ];
589 } elseif ( $code === $loop::CONDITION_TIMED_OUT
) {
590 $this->logger
->warning(
591 "$fname failed due to timeout for {key}.",
592 [ 'key' => $key, 'timeout' => $timeout ]
600 * Release an advisory lock on a key string
603 * @return bool Success
605 public function unlock( $key ) {
606 if ( !isset( $this->locks
[$key] ) ) {
610 if ( --$this->locks
[$key]['depth'] <= 0 ) {
611 unset( $this->locks
[$key] );
613 $ok = $this->doDelete( "{$key}:lock" );
615 $this->logger
->warning(
616 __METHOD__
. ' failed to release lock for {key}.',
628 * Get a lightweight exclusive self-unlocking lock
630 * Note that the same lock cannot be acquired twice.
632 * This is useful for task de-duplication or to avoid obtrusive
633 * (though non-corrupting) DB errors like INSERT key conflicts
634 * or deadlocks when using LOCK IN SHARE MODE.
637 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
638 * @param int $expiry Lock expiry [optional]; 1 day maximum
639 * @param string $rclass Allow reentry if set and the current lock used this value
640 * @return ScopedCallback|null Returns null on failure
643 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
644 $expiry = min( $expiry ?
: INF
, self
::TTL_DAY
);
646 if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
650 $lSince = $this->getCurrentTime(); // lock timestamp
652 return new ScopedCallback( function () use ( $key, $lSince, $expiry ) {
653 $latency = 0.050; // latency skew (err towards keeping lock present)
654 $age = ( $this->getCurrentTime() - $lSince +
$latency );
655 if ( ( $age +
$latency ) >= $expiry ) {
656 $this->logger
->warning(
657 "Lock for {key} held too long ({age} sec).",
658 [ 'key' => $key, 'age' => $age ]
660 return; // expired; it's not "safe" to delete the key
662 $this->unlock( $key );
667 * Delete all objects expiring before a certain date.
668 * @param string|int $timestamp The reference date in MW or TS_UNIX format
669 * @param callable|null $progress Optional, a function which will be called
670 * regularly during long-running operations with the percentage progress
671 * as the first parameter. [optional]
672 * @param int $limit Maximum number of keys to delete [default: INF]
674 * @return bool Success; false if unimplemented
676 public function deleteObjectsExpiringBefore(
678 callable
$progress = null,
685 * Get an associative array containing the item for each of the keys that have items.
686 * @param string[] $keys List of keys; can be a map of (unused => key) for convenience
687 * @param int $flags Bitfield; supports READ_LATEST [optional]
688 * @return mixed[] Map of (key => value) for existing keys; preserves the order of $keys
690 public function getMulti( array $keys, $flags = 0 ) {
691 $foundByKey = $this->doGetMulti( $keys, $flags );
694 foreach ( $keys as $key ) {
695 // Resolve one blob at a time (avoids too much I/O at once)
696 if ( array_key_exists( $key, $foundByKey ) ) {
697 // A value should not appear in the key if a segment is missing
698 $value = $this->resolveSegments( $key, $foundByKey[$key] );
699 if ( $value !== false ) {
709 * Get an associative array containing the item for each of the keys that have items.
710 * @param string[] $keys List of keys
711 * @param int $flags Bitfield; supports READ_LATEST [optional]
712 * @return mixed[] Map of (key => value) for existing keys
714 protected function doGetMulti( array $keys, $flags = 0 ) {
716 foreach ( $keys as $key ) {
717 $val = $this->doGet( $key, $flags );
718 if ( $val !== false ) {
727 * Batch insertion/replace
729 * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O
731 * WRITE_BACKGROUND can be used for bulk insertion where the response is not vital
733 * @param mixed[] $data Map of (key => value)
734 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
735 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
736 * @return bool Success
739 public function setMulti( array $data, $exptime = 0, $flags = 0 ) {
740 if ( ( $flags & self
::WRITE_ALLOW_SEGMENTS
) === self
::WRITE_ALLOW_SEGMENTS
) {
741 throw new InvalidArgumentException( __METHOD__
. ' got WRITE_ALLOW_SEGMENTS' );
743 return $this->doSetMulti( $data, $exptime, $flags );
747 * @param mixed[] $data Map of (key => value)
748 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
749 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
750 * @return bool Success
752 protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
754 foreach ( $data as $key => $value ) {
755 $res = $this->doSet( $key, $value, $exptime, $flags ) && $res;
763 * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O
765 * WRITE_BACKGROUND can be used for bulk deletion where the response is not vital
767 * @param string[] $keys List of keys
768 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
769 * @return bool Success
772 public function deleteMulti( array $keys, $flags = 0 ) {
773 if ( ( $flags & self
::WRITE_ALLOW_SEGMENTS
) === self
::WRITE_ALLOW_SEGMENTS
) {
774 throw new InvalidArgumentException( __METHOD__
. ' got WRITE_ALLOW_SEGMENTS' );
776 return $this->doDeleteMulti( $keys, $flags );
780 * @param string[] $keys List of keys
781 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
782 * @return bool Success
784 protected function doDeleteMulti( array $keys, $flags = 0 ) {
786 foreach ( $keys as $key ) {
787 $res = $this->doDelete( $key, $flags ) && $res;
793 * Change the expiration of multiple keys that exist
795 * @see BagOStuff::changeTTL()
797 * @param string[] $keys List of keys
798 * @param int $exptime TTL or UNIX timestamp
799 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
800 * @return bool Success
803 public function changeTTLMulti( array $keys, $exptime, $flags = 0 ) {
805 foreach ( $keys as $key ) {
806 $res = $this->doChangeTTL( $key, $exptime, $flags ) && $res;
813 * Increase stored value of $key by $value while preserving its TTL
814 * @param string $key Key to increase
815 * @param int $value Value to add to $key (default: 1) [optional]
816 * @return int|bool New value or false on failure
818 abstract public function incr( $key, $value = 1 );
821 * Decrease stored value of $key by $value while preserving its TTL
823 * @param int $value Value to subtract from $key (default: 1) [optional]
824 * @return int|bool New value or false on failure
826 public function decr( $key, $value = 1 ) {
827 return $this->incr( $key, - $value );
831 * Increase stored value of $key by $value while preserving its TTL
833 * This will create the key with value $init and TTL $ttl instead if not present
839 * @return int|bool New value or false on failure
842 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
843 $this->clearLastError();
844 $newValue = $this->incr( $key, $value );
845 if ( $newValue === false && !$this->getLastError() ) {
846 // No key set; initialize
847 $newValue = $this->add( $key, (int)$init, $ttl ) ?
$init : false;
848 if ( $newValue === false && !$this->getLastError() ) {
849 // Raced out initializing; increment
850 $newValue = $this->incr( $key, $value );
858 * Get and reassemble the chunks of blob at the given key
861 * @param mixed $mainValue
862 * @return string|null|bool The combined string, false if missing, null on error
864 final protected function resolveSegments( $key, $mainValue ) {
865 if ( SerializedValueContainer
::isUnified( $mainValue ) ) {
866 return $this->unserialize( $mainValue->{SerializedValueContainer
::UNIFIED_DATA
} );
869 if ( SerializedValueContainer
::isSegmented( $mainValue ) ) {
870 $orderedKeys = array_map(
871 function ( $segmentHash ) use ( $key ) {
872 return $this->makeGlobalKey( self
::SEGMENT_COMPONENT
, $key, $segmentHash );
874 $mainValue->{SerializedValueContainer
::SEGMENTED_HASHES
}
877 $segmentsByKey = $this->doGetMulti( $orderedKeys );
880 foreach ( $orderedKeys as $segmentKey ) {
881 if ( isset( $segmentsByKey[$segmentKey] ) ) {
882 $parts[] = $segmentsByKey[$segmentKey];
884 return false; // missing segment
888 return $this->unserialize( implode( '', $parts ) );
895 * Get the "last error" registered; clearLastError() should be called manually
896 * @return int ERR_* constant for the "last error" registry
899 public function getLastError() {
900 return $this->lastError
;
904 * Clear the "last error" registry
907 public function clearLastError() {
908 $this->lastError
= self
::ERR_NONE
;
912 * Set the "last error" registry
913 * @param int $err ERR_* constant
916 protected function setLastError( $err ) {
917 $this->lastError
= $err;
921 * Let a callback be run to avoid wasting time on special blocking calls
923 * The callbacks may or may not be called ever, in any particular order.
924 * They are likely to be invoked when something WRITE_SYNC is used used.
925 * They should follow a caching pattern as shown below, so that any code
926 * using the work will get it's result no matter what happens.
929 * $workCallback = function () use ( &$result ) {
937 * @param callable $workCallback
940 final public function addBusyCallback( callable
$workCallback ) {
941 $this->busyCallbacks
[] = $workCallback;
945 * @param string $text
947 protected function debug( $text ) {
948 if ( $this->debugMode
) {
949 $this->logger
->debug( "{class} debug: $text", [ 'class' => static::class ] );
954 * @param int $exptime
957 final protected function expiryIsRelative( $exptime ) {
958 return ( $exptime != 0 && $exptime < ( 10 * self
::TTL_YEAR
) );
962 * Convert an optionally relative timestamp to an absolute time
964 * The input value will be cast to an integer and interpreted as follows:
965 * - zero: no expiry; return zero (e.g. TTL_INDEFINITE)
966 * - negative: relative TTL; return UNIX timestamp offset by this value
967 * - positive (< 10 years): relative TTL; return UNIX timestamp offset by this value
968 * - positive (>= 10 years): absolute UNIX timestamp; return this value
970 * @param int $exptime Absolute TTL or 0 for indefinite
973 final protected function convertToExpiry( $exptime ) {
974 return $this->expiryIsRelative( $exptime )
975 ?
(int)$this->getCurrentTime() +
$exptime
980 * Convert an optionally absolute expiry time to a relative time. If an
981 * absolute time is specified which is in the past, use a short expiry time.
983 * @param int $exptime
986 final protected function convertToRelative( $exptime ) {
987 return $this->expiryIsRelative( $exptime )
989 : max( $exptime - (int)$this->getCurrentTime(), 1 );
993 * Check if a value is an integer
995 * @param mixed $value
998 final protected function isInteger( $value ) {
999 if ( is_int( $value ) ) {
1001 } elseif ( !is_string( $value ) ) {
1005 $integer = (int)$value;
1007 return ( $value === (string)$integer );
1011 * Construct a cache key.
1014 * @param string $keyspace
1015 * @param array $args
1016 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
1018 public function makeKeyInternal( $keyspace, $args ) {
1020 foreach ( $args as $arg ) {
1021 $key .= ':' . str_replace( ':', '%3A', $arg );
1023 return strtr( $key, ' ', '_' );
1027 * Make a global cache key.
1030 * @param string $class Key class
1031 * @param string|null $component [optional] Key component (starting with a key collection name)
1032 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
1034 public function makeGlobalKey( $class, $component = null ) {
1035 return $this->makeKeyInternal( 'global', func_get_args() );
1039 * Make a cache key, scoped to this instance's keyspace.
1042 * @param string $class Key class
1043 * @param string|null $component [optional] Key component (starting with a key collection name)
1044 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
1046 public function makeKey( $class, $component = null ) {
1047 return $this->makeKeyInternal( $this->keyspace
, func_get_args() );
1051 * @param int $flag ATTR_* class constant
1052 * @return int QOS_* class constant
1055 public function getQoS( $flag ) {
1056 return $this->attrMap
[$flag] ?? self
::QOS_UNKNOWN
;
1060 * @return int|float The chunk size, in bytes, of segmented objects (INF for no limit)
1063 public function getSegmentationSize() {
1064 return $this->segmentationSize
;
1068 * @return int|float Maximum total segmented object size in bytes (INF for no limit)
1071 public function getSegmentedValueMaxSize() {
1072 return $this->segmentedValueMaxSize
;
1076 * Merge the flag maps of one or more BagOStuff objects into a "lowest common denominator" map
1078 * @param BagOStuff[] $bags
1079 * @return int[] Resulting flag map (class ATTR_* constant => class QOS_* constant)
1081 final protected function mergeFlagMaps( array $bags ) {
1083 foreach ( $bags as $bag ) {
1084 foreach ( $bag->attrMap
as $attr => $rank ) {
1085 if ( isset( $map[$attr] ) ) {
1086 $map[$attr] = min( $map[$attr], $rank );
1088 $map[$attr] = $rank;
1097 * @internal For testing only
1098 * @return float UNIX timestamp
1099 * @codeCoverageIgnore
1101 public function getCurrentTime() {
1102 return $this->wallClockOverride ?
: microtime( true );
1106 * @internal For testing only
1107 * @param float|null &$time Mock UNIX timestamp
1108 * @codeCoverageIgnore
1110 public function setMockTime( &$time ) {
1111 $this->wallClockOverride
=& $time;
1115 * @param mixed $value
1116 * @return string|int String/integer representation
1117 * @note Special handling is usually needed for integers so incr()/decr() work
1119 protected function serialize( $value ) {
1120 return is_int( $value ) ?
$value : serialize( $value );
1124 * @param string|int $value
1125 * @return mixed Original value or false on error
1126 * @note Special handling is usually needed for integers so incr()/decr() work
1128 protected function unserialize( $value ) {
1129 return $this->isInteger( $value ) ?
(int)$value : unserialize( $value );