3 * Storage medium specific cache for storing items.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 use Wikimedia\WaitConditionLoop
;
27 * Storage medium specific cache for storing items (e.g. redis, memcached, ...)
29 * This should not be used for proxy classes that simply wrap other cache instances
34 abstract class MediumSpecificBagOStuff
extends BagOStuff
{
35 /** @var array[] Lock tracking */
36 protected $locks = [];
37 /** @var int ERR_* class constant */
38 protected $lastError = self
::ERR_NONE
;
40 protected $keyspace = 'local';
41 /** @var int Seconds */
42 protected $syncTimeout;
43 /** @var int Bytes; chunk size of segmented cache values */
44 protected $segmentationSize;
45 /** @var int Bytes; maximum total size of a segmented cache value */
46 protected $segmentedValueMaxSize;
49 private $duplicateKeyLookups = [];
51 private $reportDupes = false;
53 private $dupeTrackScheduled = false;
55 /** @var callable[] */
56 protected $busyCallbacks = [];
58 /** @var string Component to use for key construction of blob segment keys */
59 const SEGMENT_COMPONENT
= 'segment';
62 * @see BagOStuff::__construct()
63 * Additional $params options include:
64 * - logger: Psr\Log\LoggerInterface instance
65 * - keyspace: Default keyspace for $this->makeKey()
66 * - reportDupes: Whether to emit warning log messages for all keys that were
67 * requested more than once (requires an asyncHandler).
68 * - syncTimeout: How long to wait with WRITE_SYNC in seconds.
69 * - segmentationSize: The chunk size, in bytes, of segmented values. The value should
70 * not exceed the maximum size of values in the storage backend, as configured by
71 * the site administrator.
72 * - segmentedValueMaxSize: The maximum total size, in bytes, of segmented values.
73 * This should be configured to a reasonable size give the site traffic and the
74 * amount of I/O between application and cache servers that the network can handle.
75 * @param array $params
76 * @codingStandardsIgnoreStart
77 * @phan-param array{logger?:Psr\Log\LoggerInterface,asyncHandler?:callable,keyspace?:string,reportDupes?:bool,syncTimeout?:int,segmentationSize?:int,segmentedValueMaxSize?:int} $params
78 * @codingStandardsIgnoreEnd
80 public function __construct( array $params = [] ) {
81 parent
::__construct( $params );
83 if ( isset( $params['keyspace'] ) ) {
84 $this->keyspace
= $params['keyspace'];
87 if ( !empty( $params['reportDupes'] ) && is_callable( $this->asyncHandler
) ) {
88 $this->reportDupes
= true;
91 $this->syncTimeout
= $params['syncTimeout'] ??
3;
92 $this->segmentationSize
= $params['segmentationSize'] ??
8388608; // 8MiB
93 $this->segmentedValueMaxSize
= $params['segmentedValueMaxSize'] ??
67108864; // 64MiB
97 * Get an item with the given key
99 * If the key includes a deterministic input hash (e.g. the key can only have
100 * the correct value) or complete staleness checks are handled by the caller
101 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
102 * This lets tiered backends know they can safely upgrade a cached value to
103 * higher tiers using standard TTLs.
106 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
107 * @return mixed Returns false on failure or if the item does not exist
109 public function get( $key, $flags = 0 ) {
110 $this->trackDuplicateKeys( $key );
112 return $this->resolveSegments( $key, $this->doGet( $key, $flags ) );
116 * Track the number of times that a given key has been used.
119 private function trackDuplicateKeys( $key ) {
120 if ( !$this->reportDupes
) {
124 if ( !isset( $this->duplicateKeyLookups
[$key] ) ) {
125 // Track that we have seen this key. This N-1 counting style allows
126 // easy filtering with array_filter() later.
127 $this->duplicateKeyLookups
[$key] = 0;
129 $this->duplicateKeyLookups
[$key] +
= 1;
131 if ( $this->dupeTrackScheduled
=== false ) {
132 $this->dupeTrackScheduled
= true;
133 // Schedule a callback that logs keys processed more than once by get().
134 call_user_func( $this->asyncHandler
, function () {
135 $dups = array_filter( $this->duplicateKeyLookups
);
136 foreach ( $dups as $key => $count ) {
137 $this->logger
->warning(
138 'Duplicate get(): "{key}" fetched {count} times',
139 // Count is N-1 of the actual lookup count
140 [ 'key' => $key, 'count' => $count +
1, ]
150 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
151 * @param mixed|null &$casToken Token to use for check-and-set comparisons
152 * @return mixed Returns false on failure or if the item does not exist
154 abstract protected function doGet( $key, $flags = 0, &$casToken = null );
160 * @param mixed $value
161 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
162 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
163 * @return bool Success
165 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
166 list( $entry, $usable ) = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags );
167 // Only when all segments (if any) are stored should the main key be changed
168 return $usable ?
$this->doSet( $key, $entry, $exptime, $flags ) : false;
175 * @param mixed $value
176 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
177 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
178 * @return bool Success
180 abstract protected function doSet( $key, $value, $exptime = 0, $flags = 0 );
185 * For large values written using WRITE_ALLOW_SEGMENTS, this only deletes the main
186 * segment list key unless WRITE_PRUNE_SEGMENTS is in the flags. While deleting the segment
187 * list key has the effect of functionally deleting the key, it leaves unused blobs in cache.
190 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
191 * @return bool True if the item was deleted or not found, false on failure
193 public function delete( $key, $flags = 0 ) {
194 if ( !$this->fieldHasFlags( $flags, self
::WRITE_PRUNE_SEGMENTS
) ) {
195 return $this->doDelete( $key, $flags );
198 $mainValue = $this->doGet( $key, self
::READ_LATEST
);
199 if ( !$this->doDelete( $key, $flags ) ) {
203 if ( !SerializedValueContainer
::isSegmented( $mainValue ) ) {
204 return true; // no segments to delete
207 $orderedKeys = array_map(
208 function ( $segmentHash ) use ( $key ) {
209 return $this->makeGlobalKey( self
::SEGMENT_COMPONENT
, $key, $segmentHash );
211 $mainValue->{SerializedValueContainer
::SEGMENTED_HASHES
}
214 return $this->deleteMulti( $orderedKeys, $flags & ~self
::WRITE_PRUNE_SEGMENTS
);
221 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
222 * @return bool True if the item was deleted or not found, false on failure
224 abstract protected function doDelete( $key, $flags = 0 );
226 public function add( $key, $value, $exptime = 0, $flags = 0 ) {
227 list( $entry, $usable ) = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags );
228 // Only when all segments (if any) are stored should the main key be changed
229 return $usable ?
$this->doAdd( $key, $entry, $exptime, $flags ) : false;
233 * Insert an item if it does not already exist
236 * @param mixed $value
237 * @param int $exptime
238 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
239 * @return bool Success
241 abstract protected function doAdd( $key, $value, $exptime = 0, $flags = 0 );
244 * Merge changes into the existing cache value (possibly creating a new one)
246 * The callback function returns the new value given the current value
247 * (which will be false if not present), and takes the arguments:
248 * (this BagOStuff, cache key, current value, TTL).
249 * The TTL parameter is reference set to $exptime. It can be overriden in the callback.
250 * Nothing is stored nor deleted if the callback returns false.
253 * @param callable $callback Callback method to be executed
254 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
255 * @param int $attempts The amount of times to attempt a merge in case of failure
256 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
257 * @return bool Success
259 public function merge( $key, callable
$callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
260 return $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
265 * @param callable $callback Callback method to be executed
266 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
267 * @param int $attempts The amount of times to attempt a merge in case of failure
268 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
269 * @return bool Success
270 * @see BagOStuff::merge()
272 final protected function mergeViaCas( $key, callable
$callback, $exptime, $attempts, $flags ) {
273 $attemptsLeft = $attempts;
275 $token = null; // passed by reference
276 // Get the old value and CAS token from cache
277 $this->clearLastError();
278 $currentValue = $this->resolveSegments(
280 $this->doGet( $key, $flags, $token )
282 if ( $this->getLastError() ) {
283 // Don't spam slow retries due to network problems (retry only on races)
284 $this->logger
->warning(
285 __METHOD__
. ' failed due to read I/O error on get() for {key}.',
292 // Derive the new value from the old value
293 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
294 $keyWasNonexistant = ( $currentValue === false );
295 $valueMatchesOldValue = ( $value === $currentValue );
296 unset( $currentValue ); // free RAM in case the value is large
298 $this->clearLastError();
299 if ( $value === false ||
$exptime < 0 ) {
300 $success = true; // do nothing
301 } elseif ( $valueMatchesOldValue && $attemptsLeft !== $attempts ) {
302 $success = true; // recently set by another thread to the same value
303 } elseif ( $keyWasNonexistant ) {
304 // Try to create the key, failing if it gets created in the meantime
305 $success = $this->add( $key, $value, $exptime, $flags );
307 // Try to update the key, failing if it gets changed in the meantime
308 $success = $this->cas( $token, $key, $value, $exptime, $flags );
310 if ( $this->getLastError() ) {
311 // Don't spam slow retries due to network problems (retry only on races)
312 $this->logger
->warning(
313 __METHOD__
. ' failed due to write I/O error for {key}.',
320 } while ( !$success && --$attemptsLeft );
326 * Check and set an item
328 * @param mixed $casToken
330 * @param mixed $value
331 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
332 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
333 * @return bool Success
335 protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
336 if ( $casToken === null ) {
337 $this->logger
->warning(
338 __METHOD__
. ' got empty CAS token for {key}.',
342 return false; // caller may have meant to use add()?
345 list( $entry, $usable ) = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags );
346 // Only when all segments (if any) are stored should the main key be changed
347 return $usable ?
$this->doCas( $casToken, $key, $entry, $exptime, $flags ) : false;
351 * Check and set an item
353 * @param mixed $casToken
355 * @param mixed $value
356 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
357 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
358 * @return bool Success
360 protected function doCas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
361 // @TODO: the lock() call assumes that all other relavent sets() use one
362 if ( !$this->lock( $key, 0 ) ) {
363 return false; // non-blocking
366 $curCasToken = null; // passed by reference
367 $this->clearLastError();
368 $this->doGet( $key, self
::READ_LATEST
, $curCasToken );
369 if ( is_object( $curCasToken ) ) {
370 // Using === does not work with objects since it checks for instance identity
371 throw new UnexpectedValueException( "CAS token cannot be an object" );
373 if ( $this->getLastError() ) {
374 // Fail if the old CAS token could not be read
376 $this->logger
->warning(
377 __METHOD__
. ' failed due to write I/O error for {key}.',
380 } elseif ( $casToken === $curCasToken ) {
381 $success = $this->doSet( $key, $value, $exptime, $flags );
383 $success = false; // mismatched or failed
385 __METHOD__
. ' failed due to race condition for {key}.',
390 $this->unlock( $key );
396 * Change the expiration on a key if it exists
398 * If an expiry in the past is given then the key will immediately be expired
400 * For large values written using WRITE_ALLOW_SEGMENTS, this only changes the TTL of the
401 * main segment list key. While lowering the TTL of the segment list key has the effect of
402 * functionally lowering the TTL of the key, it might leave unused blobs in cache for longer.
403 * Raising the TTL of such keys is not effective, since the expiration of a single segment
404 * key effectively expires the entire value.
407 * @param int $exptime TTL or UNIX timestamp
408 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
409 * @return bool Success Returns false on failure or if the item does not exist
412 public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
413 return $this->doChangeTTL( $key, $exptime, $flags );
418 * @param int $exptime
422 protected function doChangeTTL( $key, $exptime, $flags ) {
423 if ( !$this->lock( $key, 0 ) ) {
427 $expiry = $this->getExpirationAsTimestamp( $exptime );
428 $delete = ( $expiry != self
::TTL_INDEFINITE
&& $expiry < $this->getCurrentTime() );
430 // Use doGet() to avoid having to trigger resolveSegments()
431 $blob = $this->doGet( $key, self
::READ_LATEST
);
434 $ok = $this->doDelete( $key, $flags );
436 $ok = $this->doSet( $key, $blob, $exptime, $flags );
442 $this->unlock( $key );
448 * Acquire an advisory lock on a key string
450 * Note that if reentry is enabled, duplicate calls ignore $expiry
453 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
454 * @param int $expiry Lock expiry [optional]; 1 day maximum
455 * @param string $rclass Allow reentry if set and the current lock used this value
456 * @return bool Success
458 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
459 // Avoid deadlocks and allow lock reentry if specified
460 if ( isset( $this->locks
[$key] ) ) {
461 if ( $rclass != '' && $this->locks
[$key]['class'] === $rclass ) {
462 ++
$this->locks
[$key]['depth'];
470 $expiry = min( $expiry ?
: INF
, self
::TTL_DAY
);
471 $loop = new WaitConditionLoop(
472 function () use ( $key, $expiry, $fname ) {
473 $this->clearLastError();
474 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
475 return WaitConditionLoop
::CONDITION_REACHED
; // locked!
476 } elseif ( $this->getLastError() ) {
477 $this->logger
->warning(
478 $fname . ' failed due to I/O error for {key}.',
482 return WaitConditionLoop
::CONDITION_ABORTED
; // network partition?
485 return WaitConditionLoop
::CONDITION_CONTINUE
;
490 $code = $loop->invoke();
491 $locked = ( $code === $loop::CONDITION_REACHED
);
493 $this->locks
[$key] = [ 'class' => $rclass, 'depth' => 1 ];
494 } elseif ( $code === $loop::CONDITION_TIMED_OUT
) {
495 $this->logger
->warning(
496 "$fname failed due to timeout for {key}.",
497 [ 'key' => $key, 'timeout' => $timeout ]
505 * Release an advisory lock on a key string
508 * @return bool Success
510 public function unlock( $key ) {
511 if ( !isset( $this->locks
[$key] ) ) {
515 if ( --$this->locks
[$key]['depth'] <= 0 ) {
516 unset( $this->locks
[$key] );
518 $ok = $this->doDelete( "{$key}:lock" );
520 $this->logger
->warning(
521 __METHOD__
. ' failed to release lock for {key}.',
533 * Delete all objects expiring before a certain date.
534 * @param string|int $timestamp The reference date in MW or TS_UNIX format
535 * @param callable|null $progress Optional, a function which will be called
536 * regularly during long-running operations with the percentage progress
537 * as the first parameter. [optional]
538 * @param int $limit Maximum number of keys to delete [default: INF]
540 * @return bool Success; false if unimplemented
542 public function deleteObjectsExpiringBefore(
544 callable
$progress = null,
551 * Get an associative array containing the item for each of the keys that have items.
552 * @param string[] $keys List of keys; can be a map of (unused => key) for convenience
553 * @param int $flags Bitfield; supports READ_LATEST [optional]
554 * @return mixed[] Map of (key => value) for existing keys; preserves the order of $keys
556 public function getMulti( array $keys, $flags = 0 ) {
557 $foundByKey = $this->doGetMulti( $keys, $flags );
560 foreach ( $keys as $key ) {
561 // Resolve one blob at a time (avoids too much I/O at once)
562 if ( array_key_exists( $key, $foundByKey ) ) {
563 // A value should not appear in the key if a segment is missing
564 $value = $this->resolveSegments( $key, $foundByKey[$key] );
565 if ( $value !== false ) {
575 * Get an associative array containing the item for each of the keys that have items.
576 * @param string[] $keys List of keys
577 * @param int $flags Bitfield; supports READ_LATEST [optional]
578 * @return array Map of (key => value) for existing keys
580 protected function doGetMulti( array $keys, $flags = 0 ) {
582 foreach ( $keys as $key ) {
583 $val = $this->doGet( $key, $flags );
584 if ( $val !== false ) {
593 * Batch insertion/replace
595 * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O
597 * @param mixed[] $data Map of (key => value)
598 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
599 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
600 * @return bool Success
603 public function setMulti( array $data, $exptime = 0, $flags = 0 ) {
604 if ( $this->fieldHasFlags( $flags, self
::WRITE_ALLOW_SEGMENTS
) ) {
605 throw new InvalidArgumentException( __METHOD__
. ' got WRITE_ALLOW_SEGMENTS' );
608 return $this->doSetMulti( $data, $exptime, $flags );
612 * @param mixed[] $data Map of (key => value)
613 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
614 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
615 * @return bool Success
617 protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
619 foreach ( $data as $key => $value ) {
620 $res = $this->doSet( $key, $value, $exptime, $flags ) && $res;
629 * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O
631 * @param string[] $keys List of keys
632 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
633 * @return bool Success
636 public function deleteMulti( array $keys, $flags = 0 ) {
637 if ( $this->fieldHasFlags( $flags, self
::WRITE_PRUNE_SEGMENTS
) ) {
638 throw new InvalidArgumentException( __METHOD__
. ' got WRITE_PRUNE_SEGMENTS' );
641 return $this->doDeleteMulti( $keys, $flags );
645 * @param string[] $keys List of keys
646 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
647 * @return bool Success
649 protected function doDeleteMulti( array $keys, $flags = 0 ) {
651 foreach ( $keys as $key ) {
652 $res = $this->doDelete( $key, $flags ) && $res;
658 * Change the expiration of multiple keys that exist
660 * @param string[] $keys List of keys
661 * @param int $exptime TTL or UNIX timestamp
662 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
663 * @return bool Success
664 * @see BagOStuff::changeTTL()
668 public function changeTTLMulti( array $keys, $exptime, $flags = 0 ) {
670 foreach ( $keys as $key ) {
671 $res = $this->doChangeTTL( $key, $exptime, $flags ) && $res;
677 public function incrWithInit( $key, $exptime, $value = 1, $init = null, $flags = 0 ) {
678 $init = is_int( $init ) ?
$init : $value;
679 $this->clearLastError();
680 $newValue = $this->incr( $key, $value, $flags );
681 if ( $newValue === false && !$this->getLastError() ) {
682 // No key set; initialize
683 $newValue = $this->add( $key, (int)$init, $exptime, $flags ) ?
$init : false;
684 if ( $newValue === false && !$this->getLastError() ) {
685 // Raced out initializing; increment
686 $newValue = $this->incr( $key, $value, $flags );
694 * Get and reassemble the chunks of blob at the given key
697 * @param mixed $mainValue
698 * @return string|null|bool The combined string, false if missing, null on error
700 final protected function resolveSegments( $key, $mainValue ) {
701 if ( SerializedValueContainer
::isUnified( $mainValue ) ) {
702 return $this->unserialize( $mainValue->{SerializedValueContainer
::UNIFIED_DATA
} );
705 if ( SerializedValueContainer
::isSegmented( $mainValue ) ) {
706 $orderedKeys = array_map(
707 function ( $segmentHash ) use ( $key ) {
708 return $this->makeGlobalKey( self
::SEGMENT_COMPONENT
, $key, $segmentHash );
710 $mainValue->{SerializedValueContainer
::SEGMENTED_HASHES
}
713 $segmentsByKey = $this->doGetMulti( $orderedKeys );
716 foreach ( $orderedKeys as $segmentKey ) {
717 if ( isset( $segmentsByKey[$segmentKey] ) ) {
718 $parts[] = $segmentsByKey[$segmentKey];
720 return false; // missing segment
724 return $this->unserialize( implode( '', $parts ) );
731 * Get the "last error" registered; clearLastError() should be called manually
732 * @return int ERR_* constant for the "last error" registry
735 public function getLastError() {
736 return $this->lastError
;
740 * Clear the "last error" registry
743 public function clearLastError() {
744 $this->lastError
= self
::ERR_NONE
;
748 * Set the "last error" registry
749 * @param int $err ERR_* constant
752 protected function setLastError( $err ) {
753 $this->lastError
= $err;
756 final public function addBusyCallback( callable
$workCallback ) {
757 $this->busyCallbacks
[] = $workCallback;
761 * Determine the entry (inline or segment list) to store under a key to save the value
764 * @param mixed $value
765 * @param int $exptime
767 * @return array (inline value or segment list, whether the entry is usable)
770 final protected function makeValueOrSegmentList( $key, $value, $exptime, $flags ) {
775 $this->fieldHasFlags( $flags, self
::WRITE_ALLOW_SEGMENTS
) &&
776 !is_int( $value ) && // avoid breaking incr()/decr()
777 is_finite( $this->segmentationSize
)
779 $segmentSize = $this->segmentationSize
;
780 $maxTotalSize = $this->segmentedValueMaxSize
;
782 $serialized = $this->serialize( $value );
783 $size = strlen( $serialized );
784 if ( $size > $maxTotalSize ) {
785 $this->logger
->warning(
786 "Value for {key} exceeds $maxTotalSize bytes; cannot segment.",
789 } elseif ( $size <= $segmentSize ) {
790 // The serialized value was already computed, so just use it inline
791 $entry = SerializedValueContainer
::newUnified( $serialized );
793 // Split the serialized value into chunks and store them at different keys
796 $count = intdiv( $size, $segmentSize ) +
( ( $size %
$segmentSize ) ?
1 : 0 );
797 for ( $i = 0; $i < $count; ++
$i ) {
798 $segment = substr( $serialized, $i * $segmentSize, $segmentSize );
799 $hash = sha1( $segment );
800 $chunkKey = $this->makeGlobalKey( self
::SEGMENT_COMPONENT
, $key, $hash );
801 $chunksByKey[$chunkKey] = $segment;
802 $segmentHashes[] = $hash;
804 $flags &= ~self
::WRITE_ALLOW_SEGMENTS
; // sanity
805 $usable = $this->setMulti( $chunksByKey, $exptime, $flags );
806 $entry = SerializedValueContainer
::newSegmented( $segmentHashes );
810 return [ $entry, $usable ];
814 * @param int|float $exptime
815 * @return bool Whether the expiry is non-infinite, and, negative or not a UNIX timestamp
818 final protected function isRelativeExpiration( $exptime ) {
819 return ( $exptime !== self
::TTL_INDEFINITE
&& $exptime < ( 10 * self
::TTL_YEAR
) );
823 * Convert an optionally relative timestamp to an absolute time
825 * The input value will be cast to an integer and interpreted as follows:
826 * - zero: no expiry; return zero (e.g. TTL_INDEFINITE)
827 * - negative: relative TTL; return UNIX timestamp offset by this value
828 * - positive (< 10 years): relative TTL; return UNIX timestamp offset by this value
829 * - positive (>= 10 years): absolute UNIX timestamp; return this value
831 * @param int $exptime
832 * @return int Expiration timestamp or TTL_INDEFINITE for indefinite
835 final protected function getExpirationAsTimestamp( $exptime ) {
836 if ( $exptime == self
::TTL_INDEFINITE
) {
840 return $this->isRelativeExpiration( $exptime )
841 ?
intval( $this->getCurrentTime() +
$exptime )
846 * Convert an optionally absolute expiry time to a relative time. If an
847 * absolute time is specified which is in the past, use a short expiry time.
849 * The input value will be cast to an integer and interpreted as follows:
850 * - zero: no expiry; return zero (e.g. TTL_INDEFINITE)
851 * - negative: relative TTL; return a short expiry time (1 second)
852 * - positive (< 10 years): relative TTL; return this value
853 * - positive (>= 10 years): absolute UNIX timestamp; return offset to current time
855 * @param int $exptime
856 * @return int Relative TTL or TTL_INDEFINITE for indefinite
859 final protected function getExpirationAsTTL( $exptime ) {
860 if ( $exptime == self
::TTL_INDEFINITE
) {
864 return $this->isRelativeExpiration( $exptime )
866 : (int)max( $exptime - $this->getCurrentTime(), 1 );
870 * Check if a value is an integer
872 * @param mixed $value
875 final protected function isInteger( $value ) {
876 if ( is_int( $value ) ) {
878 } elseif ( !is_string( $value ) ) {
882 $integer = (int)$value;
884 return ( $value === (string)$integer );
887 public function makeKeyInternal( $keyspace, $args ) {
889 foreach ( $args as $arg ) {
890 $key .= ':' . str_replace( ':', '%3A', $arg );
892 return strtr( $key, ' ', '_' );
896 * Make a global cache key.
898 * @param string $class Key class
899 * @param string ...$components Key components (starting with a key collection name)
900 * @return string Colon-delimited list of $keyspace followed by escaped components
903 public function makeGlobalKey( $class, ...$components ) {
904 return $this->makeKeyInternal( 'global', func_get_args() );
908 * Make a cache key, scoped to this instance's keyspace.
910 * @param string $class Key class
911 * @param string ...$components Key components (starting with a key collection name)
912 * @return string Colon-delimited list of $keyspace followed by escaped components
915 public function makeKey( $class, ...$components ) {
916 return $this->makeKeyInternal( $this->keyspace
, func_get_args() );
920 * @param int $flag ATTR_* class constant
921 * @return int QOS_* class constant
924 public function getQoS( $flag ) {
925 return $this->attrMap
[$flag] ?? self
::QOS_UNKNOWN
;
928 public function getSegmentationSize() {
929 return $this->segmentationSize
;
932 public function getSegmentedValueMaxSize() {
933 return $this->segmentedValueMaxSize
;
937 * @param mixed $value
938 * @return string|int String/integer representation
939 * @note Special handling is usually needed for integers so incr()/decr() work
941 protected function serialize( $value ) {
942 return is_int( $value ) ?
$value : serialize( $value );
946 * @param string|int $value
947 * @return mixed Original value or false on error
948 * @note Special handling is usually needed for integers so incr()/decr() work
950 protected function unserialize( $value ) {
951 return $this->isInteger( $value ) ?
(int)$value : unserialize( $value );
955 * @param string $text
957 protected function debug( $text ) {
958 if ( $this->debugMode
) {
959 $this->logger
->debug( "{class} debug: $text", [ 'class' => static::class ] );