MediaWiki master
MapCacheLRU.php
Go to the documentation of this file.
1<?php
22
23use InvalidArgumentException;
24use UnexpectedValueException;
26
40 private $cache = [];
42 private $timestamps = [];
44 private $epoch;
45
47 private $maxCacheKeys;
48
50 private $wallClockOverride;
51
53 private const RANK_TOP = 1.0;
54
56 private const SIMPLE = 0;
58 private const FIELDS = 1;
59
63 public function __construct( int $maxKeys ) {
64 if ( $maxKeys <= 0 ) {
65 throw new InvalidArgumentException( '$maxKeys must be above zero' );
66 }
67
68 $this->maxCacheKeys = $maxKeys;
69 // Use the current time as the default "as of" timestamp of entries
70 $this->epoch = $this->getCurrentTime();
71 }
72
79 public static function newFromArray( array $values, $maxKeys ) {
80 $mapCache = new self( $maxKeys );
81 $mapCache->cache = ( count( $values ) > $maxKeys )
82 ? array_slice( $values, -$maxKeys, null, true )
83 : $values;
84
85 return $mapCache;
86 }
87
92 public function toArray() {
93 return $this->cache;
94 }
95
111 public function set( $key, $value, $rank = self::RANK_TOP ) {
112 if ( $this->has( $key ) ) {
113 $this->ping( $key );
114 } elseif ( count( $this->cache ) >= $this->maxCacheKeys ) {
115 $evictKey = array_key_first( $this->cache );
116 unset( $this->cache[$evictKey] );
117 unset( $this->timestamps[$evictKey] );
118 }
119
120 if ( $rank < 1.0 && $rank > 0 ) {
121 $offset = intval( $rank * count( $this->cache ) );
122 $this->cache = array_slice( $this->cache, 0, $offset, true )
123 + [ $key => $value ]
124 + array_slice( $this->cache, $offset, null, true );
125 } else {
126 $this->cache[$key] = $value;
127 }
128
129 $this->timestamps[$key] = [
130 self::SIMPLE => $this->getCurrentTime(),
131 self::FIELDS => []
132 ];
133 }
134
143 public function has( $key, $maxAge = INF ) {
144 if ( !is_int( $key ) && !is_string( $key ) ) {
145 throw new UnexpectedValueException(
146 __METHOD__ . ': invalid key; must be string or integer.' );
147 }
148 return array_key_exists( $key, $this->cache )
149 && (
150 // Optimization: Avoid expensive getAge/getCurrentTime for common case (T275673)
151 $maxAge === INF
152 || $maxAge <= 0
153 || $this->getKeyAge( $key ) <= $maxAge
154 );
155 }
156
173 public function get( $key, $maxAge = INF, $default = null ) {
174 if ( !$this->has( $key, $maxAge ) ) {
175 return $default;
176 }
177
178 $this->ping( $key );
179
180 return $this->cache[$key];
181 }
182
189 public function setField( $key, $field, $value, $initRank = self::RANK_TOP ) {
190 if ( $this->has( $key ) ) {
191 $this->ping( $key );
192
193 if ( !is_array( $this->cache[$key] ) ) {
194 $type = get_debug_type( $this->cache[$key] );
195 throw new UnexpectedValueException( "Cannot add field to non-array value ('$key' is $type)" );
196 }
197 } else {
198 $this->set( $key, [], $initRank );
199 }
200
201 if ( !is_string( $field ) && !is_int( $field ) ) {
202 throw new UnexpectedValueException(
203 __METHOD__ . ": invalid field for '$key'; must be string or integer." );
204 }
205
206 $this->cache[$key][$field] = $value;
207 $this->timestamps[$key][self::FIELDS][$field] = $this->getCurrentTime();
208 }
209
217 public function hasField( $key, $field, $maxAge = INF ) {
218 $value = $this->get( $key );
219
220 if ( !is_int( $field ) && !is_string( $field ) ) {
221 throw new UnexpectedValueException(
222 __METHOD__ . ": invalid field for '$key'; must be string or integer." );
223 }
224 return is_array( $value )
225 && array_key_exists( $field, $value )
226 && (
227 $maxAge === INF
228 || $maxAge <= 0
229 || $this->getKeyFieldAge( $key, $field ) <= $maxAge
230 );
231 }
232
240 public function getField( $key, $field, $maxAge = INF ) {
241 if ( !$this->hasField( $key, $field, $maxAge ) ) {
242 return null;
243 }
244
245 return $this->cache[$key][$field];
246 }
247
252 public function getAllKeys() {
253 return array_keys( $this->cache );
254 }
255
269 public function getWithSetCallback(
270 $key, callable $callback, $rank = self::RANK_TOP, $maxAge = INF
271 ) {
272 if ( $this->has( $key, $maxAge ) ) {
273 $value = $this->get( $key );
274 } else {
275 $value = $callback();
276 if ( $value !== false ) {
277 $this->set( $key, $value, $rank );
278 }
279 }
280
281 return $value;
282 }
283
291 public function makeKey( ...$components ) {
292 // Based on BagOStuff::makeKeyInternal, except without a required
293 // $keygroup prefix. While MapCacheLRU can and is used as cache for
294 // multiple groups of keys, it is equally common for the instance itself
295 // to represent a single group, and thus have keys where the first component
296 // can directly be a user-controlled variable.
297 $key = '';
298 foreach ( $components as $i => $component ) {
299 if ( $i > 0 ) {
300 $key .= ':';
301 }
302 $key .= strtr( $component, [ '%' => '%25', ':' => '%3A' ] );
303 }
304 return $key;
305 }
306
313 public function clear( $keys = null ) {
314 if ( func_num_args() == 0 ) {
315 $this->cache = [];
316 $this->timestamps = [];
317 } else {
318 foreach ( (array)$keys as $key ) {
319 unset( $this->cache[$key] );
320 unset( $this->timestamps[$key] );
321 }
322 }
323 }
324
331 public function getMaxSize() {
332 return $this->maxCacheKeys;
333 }
334
342 public function setMaxSize( int $maxKeys ) {
343 if ( $maxKeys <= 0 ) {
344 throw new InvalidArgumentException( '$maxKeys must be above zero' );
345 }
346
347 $this->maxCacheKeys = $maxKeys;
348 while ( count( $this->cache ) > $this->maxCacheKeys ) {
349 $evictKey = array_key_first( $this->cache );
350 unset( $this->cache[$evictKey] );
351 unset( $this->timestamps[$evictKey] );
352 }
353 }
354
360 private function ping( $key ) {
361 $item = $this->cache[$key];
362 unset( $this->cache[$key] );
363 $this->cache[$key] = $item;
364 }
365
370 private function getKeyAge( $key ) {
371 $mtime = $this->timestamps[$key][self::SIMPLE] ?? $this->epoch;
372
373 return ( $this->getCurrentTime() - $mtime );
374 }
375
381 private function getKeyFieldAge( $key, $field ) {
382 $mtime = $this->timestamps[$key][self::FIELDS][$field] ?? $this->epoch;
383
384 return ( $this->getCurrentTime() - $mtime );
385 }
386
387 public function __serialize() {
388 return [
389 'entries' => $this->cache,
390 'timestamps' => $this->timestamps,
391 'maxCacheKeys' => $this->maxCacheKeys,
392 ];
393 }
394
395 public function __unserialize( $data ) {
396 $this->cache = $data['entries'] ?? [];
397 $this->timestamps = $data['timestamps'] ?? [];
398 // Fallback needed for serializations prior to T218511
399 $this->maxCacheKeys = $data['maxCacheKeys'] ?? ( count( $this->cache ) + 1 );
400 $this->epoch = $this->getCurrentTime();
401 }
402
407 protected function getCurrentTime() {
408 return $this->wallClockOverride ?: microtime( true );
409 }
410
415 public function setMockTime( &$time ) {
416 $this->wallClockOverride =& $time;
417 }
418}
419
421class_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.