MediaWiki master
MapCacheLRU.php
Go to the documentation of this file.
1<?php
8
9use InvalidArgumentException;
10use UnexpectedValueException;
12
26 private $cache = [];
28 private $timestamps = [];
30 private $epoch;
31
33 private $maxCacheKeys;
34
36 private $wallClockOverride;
37
39 private const RANK_TOP = 1.0;
40
42 private const SIMPLE = 0;
44 private const FIELDS = 1;
45
49 public function __construct( int $maxKeys ) {
50 if ( $maxKeys <= 0 ) {
51 throw new InvalidArgumentException( '$maxKeys must be above zero' );
52 }
53
54 $this->maxCacheKeys = $maxKeys;
55 // Use the current time as the default "as of" timestamp of entries
56 $this->epoch = $this->getCurrentTime();
57 }
58
65 public static function newFromArray( array $values, $maxKeys ) {
66 $mapCache = new self( $maxKeys );
67 $mapCache->cache = ( count( $values ) > $maxKeys )
68 ? array_slice( $values, -$maxKeys, null, true )
69 : $values;
70
71 return $mapCache;
72 }
73
78 public function toArray() {
79 return $this->cache;
80 }
81
97 public function set( $key, $value, $rank = self::RANK_TOP ) {
98 if ( $this->has( $key ) ) {
99 $this->ping( $key );
100 } elseif ( count( $this->cache ) >= $this->maxCacheKeys ) {
101 $evictKey = array_key_first( $this->cache );
102 unset( $this->cache[$evictKey] );
103 unset( $this->timestamps[$evictKey] );
104 }
105
106 if ( $rank < 1.0 && $rank > 0 ) {
107 $offset = intval( $rank * count( $this->cache ) );
108 $this->cache = array_slice( $this->cache, 0, $offset, true )
109 + [ $key => $value ]
110 + array_slice( $this->cache, $offset, null, true );
111 } else {
112 $this->cache[$key] = $value;
113 }
114
115 $this->timestamps[$key] = [
116 self::SIMPLE => $this->getCurrentTime(),
117 self::FIELDS => []
118 ];
119 }
120
129 public function has( $key, $maxAge = INF ) {
130 if ( !is_int( $key ) && !is_string( $key ) ) {
131 throw new UnexpectedValueException(
132 __METHOD__ . ': invalid key; must be string or integer.' );
133 }
134 return array_key_exists( $key, $this->cache )
135 && (
136 // Optimization: Avoid expensive getAge/getCurrentTime for common case (T275673)
137 $maxAge === INF
138 || $maxAge <= 0
139 || $this->getKeyAge( $key ) <= $maxAge
140 );
141 }
142
159 public function get( $key, $maxAge = INF, $default = null ) {
160 if ( !$this->has( $key, $maxAge ) ) {
161 return $default;
162 }
163
164 $this->ping( $key );
165
166 return $this->cache[$key];
167 }
168
175 public function setField( $key, $field, $value, $initRank = self::RANK_TOP ) {
176 if ( $this->has( $key ) ) {
177 $this->ping( $key );
178
179 if ( !is_array( $this->cache[$key] ) ) {
180 $type = get_debug_type( $this->cache[$key] );
181 throw new UnexpectedValueException( "Cannot add field to non-array value ('$key' is $type)" );
182 }
183 } else {
184 $this->set( $key, [], $initRank );
185 }
186
187 if ( !is_string( $field ) && !is_int( $field ) ) {
188 throw new UnexpectedValueException(
189 __METHOD__ . ": invalid field for '$key'; must be string or integer." );
190 }
191
192 $this->cache[$key][$field] = $value;
193 $this->timestamps[$key][self::FIELDS][$field] = $this->getCurrentTime();
194 }
195
203 public function hasField( $key, $field, $maxAge = INF ) {
204 $value = $this->get( $key );
205
206 if ( !is_int( $field ) && !is_string( $field ) ) {
207 throw new UnexpectedValueException(
208 __METHOD__ . ": invalid field for '$key'; must be string or integer." );
209 }
210 return is_array( $value )
211 && array_key_exists( $field, $value )
212 && (
213 $maxAge === INF
214 || $maxAge <= 0
215 || $this->getKeyFieldAge( $key, $field ) <= $maxAge
216 );
217 }
218
226 public function getField( $key, $field, $maxAge = INF ) {
227 if ( !$this->hasField( $key, $field, $maxAge ) ) {
228 return null;
229 }
230
231 return $this->cache[$key][$field];
232 }
233
238 public function getAllKeys() {
239 return array_keys( $this->cache );
240 }
241
255 public function getWithSetCallback(
256 $key, callable $callback, $rank = self::RANK_TOP, $maxAge = INF
257 ) {
258 if ( $this->has( $key, $maxAge ) ) {
259 $value = $this->get( $key );
260 } else {
261 $value = $callback();
262 if ( $value !== false ) {
263 $this->set( $key, $value, $rank );
264 }
265 }
266
267 return $value;
268 }
269
277 public function makeKey( ...$components ) {
278 // Based on BagOStuff::makeKeyInternal, except without a required
279 // $keygroup prefix. While MapCacheLRU can and is used as cache for
280 // multiple groups of keys, it is equally common for the instance itself
281 // to represent a single group, and thus have keys where the first component
282 // can directly be a user-controlled variable.
283 $key = '';
284 foreach ( $components as $i => $component ) {
285 if ( $i > 0 ) {
286 $key .= ':';
287 }
288 $key .= strtr( $component, [ '%' => '%25', ':' => '%3A' ] );
289 }
290 return $key;
291 }
292
299 public function clear( $keys = null ) {
300 if ( func_num_args() == 0 ) {
301 $this->cache = [];
302 $this->timestamps = [];
303 } else {
304 foreach ( (array)$keys as $key ) {
305 unset( $this->cache[$key] );
306 unset( $this->timestamps[$key] );
307 }
308 }
309 }
310
317 public function getMaxSize() {
318 return $this->maxCacheKeys;
319 }
320
328 public function setMaxSize( int $maxKeys ) {
329 if ( $maxKeys <= 0 ) {
330 throw new InvalidArgumentException( '$maxKeys must be above zero' );
331 }
332
333 $this->maxCacheKeys = $maxKeys;
334 while ( count( $this->cache ) > $this->maxCacheKeys ) {
335 $evictKey = array_key_first( $this->cache );
336 unset( $this->cache[$evictKey] );
337 unset( $this->timestamps[$evictKey] );
338 }
339 }
340
346 private function ping( $key ) {
347 $item = $this->cache[$key];
348 unset( $this->cache[$key] );
349 $this->cache[$key] = $item;
350 }
351
356 private function getKeyAge( $key ) {
357 $mtime = $this->timestamps[$key][self::SIMPLE] ?? $this->epoch;
358
359 return ( $this->getCurrentTime() - $mtime );
360 }
361
367 private function getKeyFieldAge( $key, $field ) {
368 $mtime = $this->timestamps[$key][self::FIELDS][$field] ?? $this->epoch;
369
370 return ( $this->getCurrentTime() - $mtime );
371 }
372
373 public function __serialize() {
374 return [
375 'entries' => $this->cache,
376 'timestamps' => $this->timestamps,
377 'maxCacheKeys' => $this->maxCacheKeys,
378 ];
379 }
380
381 public function __unserialize( $data ) {
382 $this->cache = $data['entries'] ?? [];
383 $this->timestamps = $data['timestamps'] ?? [];
384 // Fallback needed for serializations prior to T218511
385 $this->maxCacheKeys = $data['maxCacheKeys'] ?? ( count( $this->cache ) + 1 );
386 $this->epoch = $this->getCurrentTime();
387 }
388
393 protected function getCurrentTime() {
394 return $this->wallClockOverride ?: microtime( true );
395 }
396
401 public function setMockTime( &$time ) {
402 $this->wallClockOverride =& $time;
403 }
404}
405
407class_alias( MapCacheLRU::class, 'MapCacheLRU' );
Store key-value entries in a size-limited in-memory LRU cache.
setMaxSize(int $maxKeys)
Resize the maximum number of cache entries, removing older entries as needed.
static newFromArray(array $values, $maxKeys)
makeKey(... $components)
Format a cache key string.
getWithSetCallback( $key, callable $callback, $rank=self::RANK_TOP, $maxAge=INF)
Get an item with the given key, producing and setting it if not found.
clear( $keys=null)
Clear one or several cache entries, or all cache entries.
getMaxSize()
Get the maximum number of keys allowed.
setField( $key, $field, $value, $initRank=self::RANK_TOP)
has( $key, $maxAge=INF)
Check if a key exists.
hasField( $key, $field, $maxAge=INF)
getField( $key, $field, $maxAge=INF)
Generic interface providing Time-To-Live constants for expirable object storage.