Update Codex from v1.20.0 to v1.20.1
[mediawiki.git] / includes / libs / MapCacheLRU.php
blobcfe5e29ecf9ab13fd32df09b3bc48a399d01c58a
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
18 * @file
20 use Wikimedia\LightweightObjectStore\ExpirationAwareness;
22 /**
23 * Store key-value entries in a size-limited in-memory LRU cache.
25 * The last-modification timestamp of entries is internally tracked so that callers can
26 * specify the maximum acceptable age of entries in calls to the has() method. As a convenience,
27 * the hasField(), getField(), and setField() methods can be used for entries that are field/value
28 * maps themselves; such fields will have their own internally tracked last-modification timestamp.
30 * @ingroup Cache
31 * @since 1.23
33 class MapCacheLRU implements ExpirationAwareness {
34 /** @var array Map of (key => value) */
35 private $cache = [];
36 /** @var array Map of (key => (UNIX timestamp, (field => UNIX timestamp))) */
37 private $timestamps = [];
38 /** @var float Default entry timestamp if not specified */
39 private $epoch;
41 /** @var int Max number of entries */
42 private $maxCacheKeys;
44 /** @var float|null */
45 private $wallClockOverride;
47 /** @var float */
48 private const RANK_TOP = 1.0;
50 /** @var int Array key that holds the entry's main timestamp (flat key use) */
51 private const SIMPLE = 0;
52 /** @var int Array key that holds the entry's field timestamps (nested key use) */
53 private const FIELDS = 1;
55 /**
56 * @param int $maxKeys Maximum number of entries allowed (min 1)
58 public function __construct( int $maxKeys ) {
59 if ( $maxKeys <= 0 ) {
60 throw new InvalidArgumentException( '$maxKeys must be above zero' );
63 $this->maxCacheKeys = $maxKeys;
64 // Use the current time as the default "as of" timestamp of entries
65 $this->epoch = $this->getCurrentTime();
68 /**
69 * @param array $values Key/value map in order of increasingly recent access
70 * @param int $maxKeys
71 * @return MapCacheLRU
72 * @since 1.30
74 public static function newFromArray( array $values, $maxKeys ) {
75 $mapCache = new self( $maxKeys );
76 $mapCache->cache = ( count( $values ) > $maxKeys )
77 ? array_slice( $values, -$maxKeys, null, true )
78 : $values;
80 return $mapCache;
83 /**
84 * @return array Key/value map in order of increasingly recent access
85 * @since 1.30
87 public function toArray() {
88 return $this->cache;
91 /**
92 * Set a key/value pair.
93 * This will prune the cache if it gets too large based on LRU.
94 * If the item is already set, it will be pushed to the top of the cache.
96 * To reduce evictions due to one-off use of many new keys, $rank can be
97 * set to have keys start at the top of a bottom fraction of the list. A value
98 * of 3/8 means values start at the top of the bottom 3/8s of the list and are
99 * moved to the top of the list when accessed a second time.
101 * @param string $key
102 * @param mixed $value
103 * @param float $rank Bottom fraction of the list where keys start off [default: 1.0]
104 * @return void
106 public function set( $key, $value, $rank = self::RANK_TOP ) {
107 if ( $this->has( $key ) ) {
108 $this->ping( $key );
109 } elseif ( count( $this->cache ) >= $this->maxCacheKeys ) {
110 $evictKey = array_key_first( $this->cache );
111 unset( $this->cache[$evictKey] );
112 unset( $this->timestamps[$evictKey] );
115 if ( $rank < 1.0 && $rank > 0 ) {
116 $offset = intval( $rank * count( $this->cache ) );
117 $this->cache = array_slice( $this->cache, 0, $offset, true )
118 + [ $key => $value ]
119 + array_slice( $this->cache, $offset, null, true );
120 } else {
121 $this->cache[$key] = $value;
124 $this->timestamps[$key] = [
125 self::SIMPLE => $this->getCurrentTime(),
126 self::FIELDS => []
131 * Check if a key exists
133 * @param string|int $key
134 * @param float $maxAge Ignore items older than this many seconds [default: INF]
135 * @return bool
136 * @since 1.32 Added $maxAge
138 public function has( $key, $maxAge = INF ) {
139 if ( !is_int( $key ) && !is_string( $key ) ) {
140 throw new UnexpectedValueException(
141 __METHOD__ . ': invalid key; must be string or integer.' );
143 return array_key_exists( $key, $this->cache )
144 && (
145 // Optimization: Avoid expensive getAge/getCurrentTime for common case (T275673)
146 $maxAge === INF
147 || $maxAge <= 0
148 || $this->getKeyAge( $key ) <= $maxAge
153 * Get the value for a key.
154 * This returns null if the key is not set.
155 * If the item is already set, it will be pushed to the top of the cache.
157 * @param string $key
158 * @param float $maxAge Ignore items older than this many seconds [default: INF]
159 * @param mixed|null $default Value to return if no key is found [default: null]
160 * @return mixed Returns $default if the key was not found or is older than $maxAge
161 * @since 1.32 Added $maxAge
162 * @since 1.34 Added $default
164 * Although sometimes this can be tainted, taint-check doesn't distinguish separate instances
165 * of MapCacheLRU, so assume untainted to cut down on false positives. See T272134.
166 * @return-taint none
168 public function get( $key, $maxAge = INF, $default = null ) {
169 if ( !$this->has( $key, $maxAge ) ) {
170 return $default;
173 $this->ping( $key );
175 return $this->cache[$key];
179 * @param string|int $key
180 * @param string|int $field
181 * @param mixed $value
182 * @param float $initRank
184 public function setField( $key, $field, $value, $initRank = self::RANK_TOP ) {
185 if ( $this->has( $key ) ) {
186 $this->ping( $key );
188 if ( !is_array( $this->cache[$key] ) ) {
189 $type = get_debug_type( $this->cache[$key] );
190 throw new UnexpectedValueException( "Cannot add field to non-array value ('$key' is $type)" );
192 } else {
193 $this->set( $key, [], $initRank );
196 if ( !is_string( $field ) && !is_int( $field ) ) {
197 throw new UnexpectedValueException(
198 __METHOD__ . ": invalid field for '$key'; must be string or integer." );
201 $this->cache[$key][$field] = $value;
202 $this->timestamps[$key][self::FIELDS][$field] = $this->getCurrentTime();
206 * @param string|int $key
207 * @param string|int $field
208 * @param float $maxAge Ignore items older than this many seconds [default: INF]
209 * @return bool
210 * @since 1.32 Added $maxAge
212 public function hasField( $key, $field, $maxAge = INF ) {
213 $value = $this->get( $key );
215 if ( !is_int( $field ) && !is_string( $field ) ) {
216 throw new UnexpectedValueException(
217 __METHOD__ . ": invalid field for '$key'; must be string or integer." );
219 return is_array( $value )
220 && array_key_exists( $field, $value )
221 && (
222 $maxAge === INF
223 || $maxAge <= 0
224 || $this->getKeyFieldAge( $key, $field ) <= $maxAge
229 * @param string|int $key
230 * @param string|int $field
231 * @param float $maxAge Ignore items older than this many seconds [default: INF]
232 * @return mixed Returns null if the key was not found or is older than $maxAge
233 * @since 1.32 Added $maxAge
235 public function getField( $key, $field, $maxAge = INF ) {
236 if ( !$this->hasField( $key, $field, $maxAge ) ) {
237 return null;
240 return $this->cache[$key][$field];
244 * @return array
245 * @since 1.25
247 public function getAllKeys() {
248 return array_keys( $this->cache );
252 * Get an item with the given key, producing and setting it if not found.
254 * If the callback returns false, then nothing is stored.
256 * @since 1.28
257 * @param string $key
258 * @param callable $callback Callback that will produce the value
259 * @param float $rank Bottom fraction of the list where keys start off [default: 1.0]
260 * @param float $maxAge Ignore items older than this many seconds [default: INF]
261 * @return mixed The cached value if found or the result of $callback otherwise
262 * @since 1.32 Added $maxAge
264 public function getWithSetCallback(
265 $key, callable $callback, $rank = self::RANK_TOP, $maxAge = INF
267 if ( $this->has( $key, $maxAge ) ) {
268 $value = $this->get( $key );
269 } else {
270 $value = $callback();
271 if ( $value !== false ) {
272 $this->set( $key, $value, $rank );
276 return $value;
280 * Format a cache key string
282 * @since 1.41
283 * @param string|int ...$components Key components
284 * @return string
286 public function makeKey( ...$components ) {
287 // Based on BagOStuff::makeKeyInternal, except without a required
288 // $keygroup prefix. While MapCacheLRU can and is used as cache for
289 // multiple groups of keys, it is equally common for the instance itself
290 // to represent a single group, and thus have keys where the first component
291 // can directly be a user-controlled variable.
292 $key = '';
293 foreach ( $components as $i => $component ) {
294 if ( $i > 0 ) {
295 $key .= ':';
297 $key .= strtr( $component, [ '%' => '%25', ':' => '%3A' ] );
299 return $key;
303 * Clear one or several cache entries, or all cache entries
305 * @param string|int|array|null $keys
306 * @return void
308 public function clear( $keys = null ) {
309 if ( func_num_args() == 0 ) {
310 $this->cache = [];
311 $this->timestamps = [];
312 } else {
313 foreach ( (array)$keys as $key ) {
314 unset( $this->cache[$key] );
315 unset( $this->timestamps[$key] );
321 * Get the maximum number of keys allowed
323 * @return int
324 * @since 1.32
326 public function getMaxSize() {
327 return $this->maxCacheKeys;
331 * Resize the maximum number of cache entries, removing older entries as needed
333 * @param int $maxKeys Maximum number of entries allowed (min 1)
334 * @return void
335 * @since 1.32
337 public function setMaxSize( int $maxKeys ) {
338 if ( $maxKeys <= 0 ) {
339 throw new InvalidArgumentException( '$maxKeys must be above zero' );
342 $this->maxCacheKeys = $maxKeys;
343 while ( count( $this->cache ) > $this->maxCacheKeys ) {
344 $evictKey = array_key_first( $this->cache );
345 unset( $this->cache[$evictKey] );
346 unset( $this->timestamps[$evictKey] );
351 * Push an entry to the top of the cache
353 * @param string $key
355 private function ping( $key ) {
356 $item = $this->cache[$key];
357 unset( $this->cache[$key] );
358 $this->cache[$key] = $item;
362 * @param string|int $key
363 * @return float UNIX timestamp; the age of the given entry
365 private function getKeyAge( $key ) {
366 $mtime = $this->timestamps[$key][self::SIMPLE] ?? $this->epoch;
368 return ( $this->getCurrentTime() - $mtime );
372 * @param string|int $key
373 * @param string|int|null $field
374 * @return float UNIX timestamp; the age of the given entry field
376 private function getKeyFieldAge( $key, $field ) {
377 $mtime = $this->timestamps[$key][self::FIELDS][$field] ?? $this->epoch;
379 return ( $this->getCurrentTime() - $mtime );
382 public function __serialize() {
383 return [
384 'entries' => $this->cache,
385 'timestamps' => $this->timestamps,
386 'maxCacheKeys' => $this->maxCacheKeys,
390 public function __unserialize( $data ) {
391 $this->cache = $data['entries'] ?? [];
392 $this->timestamps = $data['timestamps'] ?? [];
393 // Fallback needed for serializations prior to T218511
394 $this->maxCacheKeys = $data['maxCacheKeys'] ?? ( count( $this->cache ) + 1 );
395 $this->epoch = $this->getCurrentTime();
399 * @return float UNIX timestamp
400 * @codeCoverageIgnore
402 protected function getCurrentTime() {
403 return $this->wallClockOverride ?: microtime( true );
407 * @param float|null &$time Mock UNIX timestamp for testing
408 * @codeCoverageIgnore
410 public function setMockTime( &$time ) {
411 $this->wallClockOverride =& $time;