MediaWiki  master
MapCacheLRU.php
Go to the documentation of this file.
1 <?php
24 
36 class MapCacheLRU implements ExpirationAwareness, Serializable {
38  private $cache = [];
40  private $timestamps = [];
42  private $epoch;
43 
45  private $maxCacheKeys;
46 
49 
51  private const RANK_TOP = 1.0;
52 
54  private const SIMPLE = 0;
56  private const FIELDS = 1;
57 
61  public function __construct( int $maxKeys ) {
62  if ( $maxKeys <= 0 ) {
63  throw new InvalidArgumentException( '$maxKeys must be above zero' );
64  }
65 
66  $this->maxCacheKeys = $maxKeys;
67  // Use the current time as the default "as of" timestamp of entries
68  $this->epoch = $this->getCurrentTime();
69  }
70 
77  public static function newFromArray( array $values, $maxKeys ) {
78  $mapCache = new self( $maxKeys );
79  $mapCache->cache = ( count( $values ) > $maxKeys )
80  ? array_slice( $values, -$maxKeys, null, true )
81  : $values;
82 
83  return $mapCache;
84  }
85 
90  public function toArray() {
91  return $this->cache;
92  }
93 
109  public function set( $key, $value, $rank = self::RANK_TOP ) {
110  if ( $this->has( $key ) ) {
111  $this->ping( $key );
112  } elseif ( count( $this->cache ) >= $this->maxCacheKeys ) {
113  reset( $this->cache );
114  $evictKey = key( $this->cache );
115  unset( $this->cache[$evictKey] );
116  unset( $this->timestamps[$evictKey] );
117  }
118 
119  if ( $rank < 1.0 && $rank > 0 ) {
120  $offset = intval( $rank * count( $this->cache ) );
121  $this->cache = array_slice( $this->cache, 0, $offset, true )
122  + [ $key => $value ]
123  + array_slice( $this->cache, $offset, null, true );
124  } else {
125  $this->cache[$key] = $value;
126  }
127 
128  $this->timestamps[$key] = [
129  self::SIMPLE => $this->getCurrentTime(),
130  self::FIELDS => []
131  ];
132  }
133 
142  public function has( $key, $maxAge = INF ) {
143  if ( !is_int( $key ) && !is_string( $key ) ) {
144  throw new UnexpectedValueException(
145  __METHOD__ . ': invalid key; must be string or integer.' );
146  }
147  return array_key_exists( $key, $this->cache )
148  && (
149  // Optimization: Avoid expensive getAge/getCurrentTime for common case (T275673)
150  $maxAge === INF
151  || $maxAge <= 0
152  || $this->getKeyAge( $key ) <= $maxAge
153  );
154  }
155 
172  public function get( $key, $maxAge = INF, $default = null ) {
173  if ( !$this->has( $key, $maxAge ) ) {
174  return $default;
175  }
176 
177  $this->ping( $key );
178 
179  return $this->cache[$key];
180  }
181 
188  public function setField( $key, $field, $value, $initRank = self::RANK_TOP ) {
189  if ( $this->has( $key ) ) {
190  $this->ping( $key );
191 
192  if ( !is_array( $this->cache[$key] ) ) {
193  $type = gettype( $this->cache[$key] );
194  throw new UnexpectedValueException( "Cannot add field to non-array value ('$key' is $type)" );
195  }
196  } else {
197  $this->set( $key, [], $initRank );
198  }
199 
200  if ( !is_string( $field ) && !is_int( $field ) ) {
201  throw new UnexpectedValueException(
202  __METHOD__ . ": invalid field for '$key'; must be string or integer." );
203  }
204 
205  $this->cache[$key][$field] = $value;
206  $this->timestamps[$key][self::FIELDS][$field] = $this->getCurrentTime();
207  }
208 
216  public function hasField( $key, $field, $maxAge = INF ) {
217  $value = $this->get( $key );
218 
219  if ( !is_int( $field ) && !is_string( $field ) ) {
220  throw new UnexpectedValueException(
221  __METHOD__ . ": invalid field for '$key'; must be string or integer." );
222  }
223  return is_array( $value )
224  && array_key_exists( $field, $value )
225  && (
226  $maxAge === INF
227  || $maxAge <= 0
228  || $this->getKeyFieldAge( $key, $field ) <= $maxAge
229  );
230  }
231 
239  public function getField( $key, $field, $maxAge = INF ) {
240  if ( !$this->hasField( $key, $field, $maxAge ) ) {
241  return null;
242  }
243 
244  return $this->cache[$key][$field];
245  }
246 
251  public function getAllKeys() {
252  return array_keys( $this->cache );
253  }
254 
268  public function getWithSetCallback(
269  $key, callable $callback, $rank = self::RANK_TOP, $maxAge = INF
270  ) {
271  if ( $this->has( $key, $maxAge ) ) {
272  $value = $this->get( $key );
273  } else {
274  $value = $callback();
275  if ( $value !== false ) {
276  $this->set( $key, $value, $rank );
277  }
278  }
279 
280  return $value;
281  }
282 
289  public function clear( $keys = null ) {
290  if ( func_num_args() == 0 ) {
291  $this->cache = [];
292  $this->timestamps = [];
293  } else {
294  foreach ( (array)$keys as $key ) {
295  unset( $this->cache[$key] );
296  unset( $this->timestamps[$key] );
297  }
298  }
299  }
300 
307  public function getMaxSize() {
308  return $this->maxCacheKeys;
309  }
310 
318  public function setMaxSize( int $maxKeys ) {
319  if ( $maxKeys <= 0 ) {
320  throw new InvalidArgumentException( '$maxKeys must be above zero' );
321  }
322 
323  $this->maxCacheKeys = $maxKeys;
324  while ( count( $this->cache ) > $this->maxCacheKeys ) {
325  reset( $this->cache );
326  $evictKey = key( $this->cache );
327  unset( $this->cache[$evictKey] );
328  unset( $this->timestamps[$evictKey] );
329  }
330  }
331 
337  private function ping( $key ) {
338  $item = $this->cache[$key];
339  unset( $this->cache[$key] );
340  $this->cache[$key] = $item;
341  }
342 
347  private function getKeyAge( $key ) {
348  $mtime = $this->timestamps[$key][self::SIMPLE] ?? $this->epoch;
349 
350  return ( $this->getCurrentTime() - $mtime );
351  }
352 
358  private function getKeyFieldAge( $key, $field ) {
359  $mtime = $this->timestamps[$key][self::FIELDS][$field] ?? $this->epoch;
360 
361  return ( $this->getCurrentTime() - $mtime );
362  }
363 
364  public function serialize() {
365  return serialize( [
366  'entries' => $this->cache,
367  'timestamps' => $this->timestamps,
368  'maxCacheKeys' => $this->maxCacheKeys,
369  ] );
370  }
371 
372  public function unserialize( $serialized ) {
373  $data = unserialize( $serialized );
374  $this->cache = $data['entries'] ?? [];
375  $this->timestamps = $data['timestamps'] ?? [];
376  // Fallback needed for serializations prior to T218511
377  $this->maxCacheKeys = $data['maxCacheKeys'] ?? ( count( $this->cache ) + 1 );
378  $this->epoch = $this->getCurrentTime();
379  }
380 
385  protected function getCurrentTime() {
386  return $this->wallClockOverride ?: microtime( true );
387  }
388 
393  public function setMockTime( &$time ) {
394  $this->wallClockOverride =& $time;
395  }
396 }
MapCacheLRU\serialize
serialize()
Definition: MapCacheLRU.php:364
MapCacheLRU\$epoch
float $epoch
Default entry timestamp if not specified.
Definition: MapCacheLRU.php:42
MapCacheLRU\ping
ping( $key)
Push an entry to the top of the cache.
Definition: MapCacheLRU.php:337
MapCacheLRU\getField
getField( $key, $field, $maxAge=INF)
Definition: MapCacheLRU.php:239
Wikimedia\LightweightObjectStore\ExpirationAwareness
Generic interface providing Time-To-Live constants for expirable object storage.
Definition: ExpirationAwareness.php:32
$serialized
foreach( $res as $row) $serialized
Definition: testCompression.php:88
MapCacheLRU\getAllKeys
getAllKeys()
Definition: MapCacheLRU.php:251
MapCacheLRU\has
has( $key, $maxAge=INF)
Check if a key exists.
Definition: MapCacheLRU.php:142
MapCacheLRU\unserialize
unserialize( $serialized)
Definition: MapCacheLRU.php:372
MapCacheLRU\$cache
array $cache
Map of (key => value)
Definition: MapCacheLRU.php:38
MapCacheLRU\getKeyFieldAge
getKeyFieldAge( $key, $field)
Definition: MapCacheLRU.php:358
MapCacheLRU\hasField
hasField( $key, $field, $maxAge=INF)
Definition: MapCacheLRU.php:216
MapCacheLRU\getKeyAge
getKeyAge( $key)
Definition: MapCacheLRU.php:347
MapCacheLRU\newFromArray
static newFromArray(array $values, $maxKeys)
Definition: MapCacheLRU.php:77
MapCacheLRU\$maxCacheKeys
int $maxCacheKeys
Max number of entries.
Definition: MapCacheLRU.php:45
MapCacheLRU
Handles a simple LRU key/value map with a maximum number of entries.
Definition: MapCacheLRU.php:36
MapCacheLRU\setMaxSize
setMaxSize(int $maxKeys)
Resize the maximum number of cache entries, removing older entries as needed.
Definition: MapCacheLRU.php:318
MapCacheLRU\$timestamps
array $timestamps
Map of (key => (UNIX timestamp, (field => UNIX timestamp)))
Definition: MapCacheLRU.php:40
MapCacheLRU\getWithSetCallback
getWithSetCallback( $key, callable $callback, $rank=self::RANK_TOP, $maxAge=INF)
Get an item with the given key, producing and setting it if not found.
Definition: MapCacheLRU.php:268
MapCacheLRU\getMaxSize
getMaxSize()
Get the maximum number of keys allowed.
Definition: MapCacheLRU.php:307
MapCacheLRU\$wallClockOverride
float null $wallClockOverride
Definition: MapCacheLRU.php:48
MapCacheLRU\setField
setField( $key, $field, $value, $initRank=self::RANK_TOP)
Definition: MapCacheLRU.php:188
$keys
$keys
Definition: testCompression.php:72
MapCacheLRU\clear
clear( $keys=null)
Clear one or several cache entries, or all cache entries.
Definition: MapCacheLRU.php:289
MapCacheLRU\setMockTime
setMockTime(&$time)
Definition: MapCacheLRU.php:393
MapCacheLRU\toArray
toArray()
Definition: MapCacheLRU.php:90
MapCacheLRU\__construct
__construct(int $maxKeys)
Definition: MapCacheLRU.php:61
MapCacheLRU\getCurrentTime
getCurrentTime()
Definition: MapCacheLRU.php:385
$type
$type
Definition: testCompression.php:52