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() */
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 is_int( $value ) ||
// avoid breaking incr()/decr()
262 ( $flags & self
::WRITE_ALLOW_SEGMENTS
) != self
::WRITE_ALLOW_SEGMENTS ||
263 is_infinite( $this->segmentationSize
)
265 return $this->doSet( $key, $value, $exptime, $flags );
268 $serialized = $this->serialize( $value );
269 $segmentSize = $this->getSegmentationSize();
270 $maxTotalSize = $this->getSegmentedValueMaxSize();
272 $size = strlen( $serialized );
273 if ( $size <= $segmentSize ) {
274 // Since the work of serializing it was already done, just use it inline
277 SerializedValueContainer
::newUnified( $serialized ),
281 } elseif ( $size > $maxTotalSize ) {
282 $this->setLastError( "Key $key exceeded $maxTotalSize bytes." );
289 $count = intdiv( $size, $segmentSize ) +
( ( $size %
$segmentSize ) ?
1 : 0 );
290 for ( $i = 0; $i < $count; ++
$i ) {
291 $segment = substr( $serialized, $i * $segmentSize, $segmentSize );
292 $hash = sha1( $segment );
293 $chunkKey = $this->makeGlobalKey( self
::SEGMENT_COMPONENT
, $key, $hash );
294 $chunksByKey[$chunkKey] = $segment;
295 $segmentHashes[] = $hash;
298 $flags &= ~self
::WRITE_ALLOW_SEGMENTS
; // sanity
299 $ok = $this->setMulti( $chunksByKey, $exptime, $flags );
301 // Only when all segments are stored should the main key be changed
304 SerializedValueContainer
::newSegmented( $segmentHashes ),
317 * @param mixed $value
318 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
319 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
320 * @return bool Success
322 abstract protected function doSet( $key, $value, $exptime = 0, $flags = 0 );
327 * For large values written using WRITE_ALLOW_SEGMENTS, this only deletes the main
328 * segment list key unless WRITE_PRUNE_SEGMENTS is in the flags. While deleting the segment
329 * list key has the effect of functionally deleting the key, it leaves unused blobs in cache.
332 * @return bool True if the item was deleted or not found, false on failure
333 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
335 public function delete( $key, $flags = 0 ) {
336 if ( ( $flags & self
::WRITE_PRUNE_SEGMENTS
) != self
::WRITE_PRUNE_SEGMENTS
) {
337 return $this->doDelete( $key, $flags );
340 $mainValue = $this->doGet( $key, self
::READ_LATEST
);
341 if ( !$this->doDelete( $key, $flags ) ) {
345 if ( !SerializedValueContainer
::isSegmented( $mainValue ) ) {
346 return true; // no segments to delete
349 $orderedKeys = array_map(
350 function ( $segmentHash ) use ( $key ) {
351 return $this->makeGlobalKey( self
::SEGMENT_COMPONENT
, $key, $segmentHash );
353 $mainValue->{SerializedValueContainer
::SEGMENTED_HASHES
}
356 return $this->deleteMulti( $orderedKeys, $flags );
363 * @return bool True if the item was deleted or not found, false on failure
364 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
366 abstract protected function doDelete( $key, $flags = 0 );
369 * Insert an item if it does not already exist
372 * @param mixed $value
373 * @param int $exptime
374 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
375 * @return bool Success
377 abstract public function add( $key, $value, $exptime = 0, $flags = 0 );
380 * Merge changes into the existing cache value (possibly creating a new one)
382 * The callback function returns the new value given the current value
383 * (which will be false if not present), and takes the arguments:
384 * (this BagOStuff, cache key, current value, TTL).
385 * The TTL parameter is reference set to $exptime. It can be overriden in the callback.
386 * Nothing is stored nor deleted if the callback returns false.
389 * @param callable $callback Callback method to be executed
390 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
391 * @param int $attempts The amount of times to attempt a merge in case of failure
392 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
393 * @return bool Success
394 * @throws InvalidArgumentException
396 public function merge( $key, callable
$callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
397 return $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
401 * @see BagOStuff::merge()
404 * @param callable $callback Callback method to be executed
405 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
406 * @param int $attempts The amount of times to attempt a merge in case of failure
407 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
408 * @return bool Success
410 final protected function mergeViaCas( $key, callable
$callback, $exptime, $attempts, $flags ) {
412 $casToken = null; // passed by reference
413 // Get the old value and CAS token from cache
414 $this->clearLastError();
415 $currentValue = $this->resolveSegments(
417 $this->doGet( $key, self
::READ_LATEST
, $casToken )
419 if ( $this->getLastError() ) {
420 $this->logger
->warning(
421 __METHOD__
. ' failed due to I/O error on get() for {key}.',
425 return false; // don't spam retries (retry only on races)
428 // Derive the new value from the old value
429 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
430 $hadNoCurrentValue = ( $currentValue === false );
431 unset( $currentValue ); // free RAM in case the value is large
433 $this->clearLastError();
434 if ( $value === false ) {
435 $success = true; // do nothing
436 } elseif ( $hadNoCurrentValue ) {
437 // Try to create the key, failing if it gets created in the meantime
438 $success = $this->add( $key, $value, $exptime, $flags );
440 // Try to update the key, failing if it gets changed in the meantime
441 $success = $this->cas( $casToken, $key, $value, $exptime, $flags );
443 if ( $this->getLastError() ) {
444 $this->logger
->warning(
445 __METHOD__
. ' failed due to I/O error for {key}.',
449 return false; // IO error; don't spam retries
452 } while ( !$success && --$attempts );
458 * Check and set an item
460 * @param mixed $casToken
462 * @param mixed $value
463 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
464 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
465 * @return bool Success
467 protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
468 if ( !$this->lock( $key, 0 ) ) {
469 return false; // non-blocking
472 $curCasToken = null; // passed by reference
473 $this->doGet( $key, self
::READ_LATEST
, $curCasToken );
474 if ( $casToken === $curCasToken ) {
475 $success = $this->set( $key, $value, $exptime, $flags );
478 __METHOD__
. ' failed due to race condition for {key}.',
482 $success = false; // mismatched or failed
485 $this->unlock( $key );
491 * Change the expiration on a key if it exists
493 * If an expiry in the past is given then the key will immediately be expired
495 * For large values written using WRITE_ALLOW_SEGMENTS, this only changes the TTL of the
496 * main segment list key. While lowering the TTL of the segment list key has the effect of
497 * functionally lowering the TTL of the key, it might leave unused blobs in cache for longer.
498 * Raising the TTL of such keys is not effective, since the expiration of a single segment
499 * key effectively expires the entire value.
502 * @param int $exptime TTL or UNIX timestamp
503 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
504 * @return bool Success Returns false on failure or if the item does not exist
507 public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
508 return $this->doChangeTTL( $key, $exptime, $flags );
513 * @param int $exptime
517 protected function doChangeTTL( $key, $exptime, $flags ) {
518 $expiry = $this->convertToExpiry( $exptime );
519 $delete = ( $expiry != 0 && $expiry < $this->getCurrentTime() );
521 if ( !$this->lock( $key, 0 ) ) {
524 // Use doGet() to avoid having to trigger resolveSegments()
525 $blob = $this->doGet( $key, self
::READ_LATEST
);
528 $ok = $this->doDelete( $key, $flags );
530 $ok = $this->doSet( $key, $blob, $exptime, $flags );
536 $this->unlock( $key );
542 * Acquire an advisory lock on a key string
544 * Note that if reentry is enabled, duplicate calls ignore $expiry
547 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
548 * @param int $expiry Lock expiry [optional]; 1 day maximum
549 * @param string $rclass Allow reentry if set and the current lock used this value
550 * @return bool Success
552 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
553 // Avoid deadlocks and allow lock reentry if specified
554 if ( isset( $this->locks
[$key] ) ) {
555 if ( $rclass != '' && $this->locks
[$key]['class'] === $rclass ) {
556 ++
$this->locks
[$key]['depth'];
564 $expiry = min( $expiry ?
: INF
, self
::TTL_DAY
);
565 $loop = new WaitConditionLoop(
566 function () use ( $key, $expiry, $fname ) {
567 $this->clearLastError();
568 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
569 return WaitConditionLoop
::CONDITION_REACHED
; // locked!
570 } elseif ( $this->getLastError() ) {
571 $this->logger
->warning(
572 $fname . ' failed due to I/O error for {key}.',
576 return WaitConditionLoop
::CONDITION_ABORTED
; // network partition?
579 return WaitConditionLoop
::CONDITION_CONTINUE
;
584 $code = $loop->invoke();
585 $locked = ( $code === $loop::CONDITION_REACHED
);
587 $this->locks
[$key] = [ 'class' => $rclass, 'depth' => 1 ];
588 } elseif ( $code === $loop::CONDITION_TIMED_OUT
) {
589 $this->logger
->warning(
590 "$fname failed due to timeout for {key}.",
591 [ 'key' => $key, 'timeout' => $timeout ]
599 * Release an advisory lock on a key string
602 * @return bool Success
604 public function unlock( $key ) {
605 if ( !isset( $this->locks
[$key] ) ) {
609 if ( --$this->locks
[$key]['depth'] <= 0 ) {
610 unset( $this->locks
[$key] );
612 $ok = $this->doDelete( "{$key}:lock" );
614 $this->logger
->warning(
615 __METHOD__
. ' failed to release lock for {key}.',
627 * Get a lightweight exclusive self-unlocking lock
629 * Note that the same lock cannot be acquired twice.
631 * This is useful for task de-duplication or to avoid obtrusive
632 * (though non-corrupting) DB errors like INSERT key conflicts
633 * or deadlocks when using LOCK IN SHARE MODE.
636 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
637 * @param int $expiry Lock expiry [optional]; 1 day maximum
638 * @param string $rclass Allow reentry if set and the current lock used this value
639 * @return ScopedCallback|null Returns null on failure
642 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
643 $expiry = min( $expiry ?
: INF
, self
::TTL_DAY
);
645 if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
649 $lSince = $this->getCurrentTime(); // lock timestamp
651 return new ScopedCallback( function () use ( $key, $lSince, $expiry ) {
652 $latency = 0.050; // latency skew (err towards keeping lock present)
653 $age = ( $this->getCurrentTime() - $lSince +
$latency );
654 if ( ( $age +
$latency ) >= $expiry ) {
655 $this->logger
->warning(
656 "Lock for {key} held too long ({age} sec).",
657 [ 'key' => $key, 'age' => $age ]
659 return; // expired; it's not "safe" to delete the key
661 $this->unlock( $key );
666 * Delete all objects expiring before a certain date.
667 * @param string|int $timestamp The reference date in MW or TS_UNIX format
668 * @param callable|null $progress Optional, a function which will be called
669 * regularly during long-running operations with the percentage progress
670 * as the first parameter. [optional]
671 * @param int $limit Maximum number of keys to delete [default: INF]
673 * @return bool Success; false if unimplemented
675 public function deleteObjectsExpiringBefore(
677 callable
$progress = null,
684 * Get an associative array containing the item for each of the keys that have items.
685 * @param string[] $keys List of keys; can be a map of (unused => key) for convenience
686 * @param int $flags Bitfield; supports READ_LATEST [optional]
687 * @return mixed[] Map of (key => value) for existing keys; preserves the order of $keys
689 public function getMulti( array $keys, $flags = 0 ) {
690 $foundByKey = $this->doGetMulti( $keys, $flags );
693 foreach ( $keys as $key ) {
694 // Resolve one blob at a time (avoids too much I/O at once)
695 if ( array_key_exists( $key, $foundByKey ) ) {
696 // A value should not appear in the key if a segment is missing
697 $value = $this->resolveSegments( $key, $foundByKey[$key] );
698 if ( $value !== false ) {
708 * Get an associative array containing the item for each of the keys that have items.
709 * @param string[] $keys List of keys
710 * @param int $flags Bitfield; supports READ_LATEST [optional]
711 * @return mixed[] Map of (key => value) for existing keys
713 protected function doGetMulti( array $keys, $flags = 0 ) {
715 foreach ( $keys as $key ) {
716 $val = $this->doGet( $key, $flags );
717 if ( $val !== false ) {
726 * Batch insertion/replace
728 * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O
730 * @param mixed[] $data Map of (key => value)
731 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
732 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
733 * @return bool Success
736 public function setMulti( array $data, $exptime = 0, $flags = 0 ) {
737 if ( ( $flags & self
::WRITE_ALLOW_SEGMENTS
) === self
::WRITE_ALLOW_SEGMENTS
) {
738 throw new InvalidArgumentException( __METHOD__
. ' got WRITE_ALLOW_SEGMENTS' );
740 return $this->doSetMulti( $data, $exptime, $flags );
744 * @param mixed[] $data Map of (key => value)
745 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
746 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
747 * @return bool Success
749 protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
751 foreach ( $data as $key => $value ) {
752 $res = $this->doSet( $key, $value, $exptime, $flags ) && $res;
760 * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O
762 * @param string[] $keys List of keys
763 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
764 * @return bool Success
767 public function deleteMulti( array $keys, $flags = 0 ) {
768 if ( ( $flags & self
::WRITE_ALLOW_SEGMENTS
) === self
::WRITE_ALLOW_SEGMENTS
) {
769 throw new InvalidArgumentException( __METHOD__
. ' got WRITE_ALLOW_SEGMENTS' );
771 return $this->doDeleteMulti( $keys, $flags );
775 * @param string[] $keys List of keys
776 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
777 * @return bool Success
779 protected function doDeleteMulti( array $keys, $flags = 0 ) {
781 foreach ( $keys as $key ) {
782 $res = $this->doDelete( $key, $flags ) && $res;
788 * Change the expiration of multiple keys that exist
790 * @see BagOStuff::changeTTL()
792 * @param string[] $keys List of keys
793 * @param int $exptime TTL or UNIX timestamp
794 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
795 * @return bool Success
798 public function changeTTLMulti( array $keys, $exptime, $flags = 0 ) {
800 foreach ( $keys as $key ) {
801 $res = $this->doChangeTTL( $key, $exptime, $flags ) && $res;
808 * Increase stored value of $key by $value while preserving its TTL
809 * @param string $key Key to increase
810 * @param int $value Value to add to $key (default: 1) [optional]
811 * @return int|bool New value or false on failure
813 abstract public function incr( $key, $value = 1 );
816 * Decrease stored value of $key by $value while preserving its TTL
818 * @param int $value Value to subtract from $key (default: 1) [optional]
819 * @return int|bool New value or false on failure
821 public function decr( $key, $value = 1 ) {
822 return $this->incr( $key, - $value );
826 * Increase stored value of $key by $value while preserving its TTL
828 * This will create the key with value $init and TTL $ttl instead if not present
834 * @return int|bool New value or false on failure
837 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
838 $this->clearLastError();
839 $newValue = $this->incr( $key, $value );
840 if ( $newValue === false && !$this->getLastError() ) {
841 // No key set; initialize
842 $newValue = $this->add( $key, (int)$init, $ttl ) ?
$init : false;
843 if ( $newValue === false && !$this->getLastError() ) {
844 // Raced out initializing; increment
845 $newValue = $this->incr( $key, $value );
853 * Get and reassemble the chunks of blob at the given key
856 * @param mixed $mainValue
857 * @return string|null|bool The combined string, false if missing, null on error
859 final protected function resolveSegments( $key, $mainValue ) {
860 if ( SerializedValueContainer
::isUnified( $mainValue ) ) {
861 return $this->unserialize( $mainValue->{SerializedValueContainer
::UNIFIED_DATA
} );
864 if ( SerializedValueContainer
::isSegmented( $mainValue ) ) {
865 $orderedKeys = array_map(
866 function ( $segmentHash ) use ( $key ) {
867 return $this->makeGlobalKey( self
::SEGMENT_COMPONENT
, $key, $segmentHash );
869 $mainValue->{SerializedValueContainer
::SEGMENTED_HASHES
}
872 $segmentsByKey = $this->doGetMulti( $orderedKeys );
875 foreach ( $orderedKeys as $segmentKey ) {
876 if ( isset( $segmentsByKey[$segmentKey] ) ) {
877 $parts[] = $segmentsByKey[$segmentKey];
879 return false; // missing segment
883 return $this->unserialize( implode( '', $parts ) );
890 * Get the "last error" registered; clearLastError() should be called manually
891 * @return int ERR_* constant for the "last error" registry
894 public function getLastError() {
895 return $this->lastError
;
899 * Clear the "last error" registry
902 public function clearLastError() {
903 $this->lastError
= self
::ERR_NONE
;
907 * Set the "last error" registry
908 * @param int $err ERR_* constant
911 protected function setLastError( $err ) {
912 $this->lastError
= $err;
916 * Let a callback be run to avoid wasting time on special blocking calls
918 * The callbacks may or may not be called ever, in any particular order.
919 * They are likely to be invoked when something WRITE_SYNC is used used.
920 * They should follow a caching pattern as shown below, so that any code
921 * using the work will get it's result no matter what happens.
924 * $workCallback = function () use ( &$result ) {
932 * @param callable $workCallback
935 final public function addBusyCallback( callable
$workCallback ) {
936 $this->busyCallbacks
[] = $workCallback;
940 * @param string $text
942 protected function debug( $text ) {
943 if ( $this->debugMode
) {
944 $this->logger
->debug( "{class} debug: $text", [ 'class' => static::class ] );
949 * @param int $exptime
952 final protected function expiryIsRelative( $exptime ) {
953 return ( $exptime != 0 && $exptime < ( 10 * self
::TTL_YEAR
) );
957 * Convert an optionally relative timestamp to an absolute time
959 * The input value will be cast to an integer and interpreted as follows:
960 * - zero: no expiry; return zero (e.g. TTL_INDEFINITE)
961 * - negative: relative TTL; return UNIX timestamp offset by this value
962 * - positive (< 10 years): relative TTL; return UNIX timestamp offset by this value
963 * - positive (>= 10 years): absolute UNIX timestamp; return this value
965 * @param int $exptime Absolute TTL or 0 for indefinite
968 final protected function convertToExpiry( $exptime ) {
969 return $this->expiryIsRelative( $exptime )
970 ?
(int)$this->getCurrentTime() +
$exptime
975 * Convert an optionally absolute expiry time to a relative time. If an
976 * absolute time is specified which is in the past, use a short expiry time.
978 * @param int $exptime
981 final protected function convertToRelative( $exptime ) {
982 return $this->expiryIsRelative( $exptime )
984 : max( $exptime - (int)$this->getCurrentTime(), 1 );
988 * Check if a value is an integer
990 * @param mixed $value
993 final protected function isInteger( $value ) {
994 if ( is_int( $value ) ) {
996 } elseif ( !is_string( $value ) ) {
1000 $integer = (int)$value;
1002 return ( $value === (string)$integer );
1006 * Construct a cache key.
1009 * @param string $keyspace
1010 * @param array $args
1011 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
1013 public function makeKeyInternal( $keyspace, $args ) {
1015 foreach ( $args as $arg ) {
1016 $key .= ':' . str_replace( ':', '%3A', $arg );
1018 return strtr( $key, ' ', '_' );
1022 * Make a global cache key.
1025 * @param string $class Key class
1026 * @param string|null $component [optional] Key component (starting with a key collection name)
1027 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
1029 public function makeGlobalKey( $class, $component = null ) {
1030 return $this->makeKeyInternal( 'global', func_get_args() );
1034 * Make a cache key, scoped to this instance's keyspace.
1037 * @param string $class Key class
1038 * @param string|null $component [optional] Key component (starting with a key collection name)
1039 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
1041 public function makeKey( $class, $component = null ) {
1042 return $this->makeKeyInternal( $this->keyspace
, func_get_args() );
1046 * @param int $flag ATTR_* class constant
1047 * @return int QOS_* class constant
1050 public function getQoS( $flag ) {
1051 return $this->attrMap
[$flag] ?? self
::QOS_UNKNOWN
;
1055 * @return int|float The chunk size, in bytes, of segmented objects (INF for no limit)
1058 public function getSegmentationSize() {
1059 return $this->segmentationSize
;
1063 * @return int|float Maximum total segmented object size in bytes (INF for no limit)
1066 public function getSegmentedValueMaxSize() {
1067 return $this->segmentedValueMaxSize
;
1071 * Merge the flag maps of one or more BagOStuff objects into a "lowest common denominator" map
1073 * @param BagOStuff[] $bags
1074 * @return int[] Resulting flag map (class ATTR_* constant => class QOS_* constant)
1076 final protected function mergeFlagMaps( array $bags ) {
1078 foreach ( $bags as $bag ) {
1079 foreach ( $bag->attrMap
as $attr => $rank ) {
1080 if ( isset( $map[$attr] ) ) {
1081 $map[$attr] = min( $map[$attr], $rank );
1083 $map[$attr] = $rank;
1092 * @internal For testing only
1093 * @return float UNIX timestamp
1094 * @codeCoverageIgnore
1096 public function getCurrentTime() {
1097 return $this->wallClockOverride ?
: microtime( true );
1101 * @internal For testing only
1102 * @param float|null &$time Mock UNIX timestamp
1103 * @codeCoverageIgnore
1105 public function setMockTime( &$time ) {
1106 $this->wallClockOverride
=& $time;
1110 * @param mixed $value
1111 * @return string|int String/integer representation
1112 * @note Special handling is usually needed for integers so incr()/decr() work
1114 protected function serialize( $value ) {
1115 return is_int( $value ) ?
$value : serialize( $value );
1119 * @param string|int $value
1120 * @return mixed Original value or false on error
1121 * @note Special handling is usually needed for integers so incr()/decr() work
1123 protected function unserialize( $value ) {
1124 return $this->isInteger( $value ) ?
(int)$value : unserialize( $value );