MediaWiki  master
MapCacheLRU.php
Go to the documentation of this file.
1 <?php
23 use Wikimedia\Assert\Assert;
25 
37 class MapCacheLRU implements ExpirationAwareness, Serializable {
39  private $cache = [];
41  private $timestamps = [];
43  private $epoch;
44 
46  private $maxCacheKeys;
47 
50 
52  private const RANK_TOP = 1.0;
53 
55  private const SIMPLE = 0;
57  private const FIELDS = 1;
58 
63  public function __construct( $maxKeys ) {
64  Assert::parameterType( 'integer', $maxKeys, '$maxKeys' );
65  Assert::parameter( $maxKeys > 0, '$maxKeys', 'must be above zero' );
66 
67  $this->maxCacheKeys = $maxKeys;
68  // Use the current time as the default "as of" timestamp of entries
69  $this->epoch = $this->getCurrentTime();
70  }
71 
78  public static function newFromArray( array $values, $maxKeys ) {
79  $mapCache = new self( $maxKeys );
80  $mapCache->cache = ( count( $values ) > $maxKeys )
81  ? array_slice( $values, -$maxKeys, null, true )
82  : $values;
83 
84  return $mapCache;
85  }
86 
91  public function toArray() {
92  return $this->cache;
93  }
94 
110  public function set( $key, $value, $rank = self::RANK_TOP ) {
111  if ( $this->has( $key ) ) {
112  $this->ping( $key );
113  } elseif ( count( $this->cache ) >= $this->maxCacheKeys ) {
114  reset( $this->cache );
115  $evictKey = key( $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 
149  if ( !array_key_exists( $key, $this->cache ) ) {
150  return false;
151  }
152 
153  return ( $maxAge <= 0 || $this->getAge( $key ) <= $maxAge );
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  } else {
192  $this->set( $key, [], $initRank );
193  }
194 
195  if ( !is_int( $field ) && !is_string( $field ) ) {
196  throw new UnexpectedValueException(
197  __METHOD__ . ": invalid field for '$key'; must be string or integer." );
198  }
199 
200  if ( !is_array( $this->cache[$key] ) ) {
201  $type = gettype( $this->cache[$key] );
202 
203  throw new UnexpectedValueException( "The value of '$key' ($type) is not an array." );
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 
225  if ( !is_array( $value ) || !array_key_exists( $field, $value ) ) {
226  return false;
227  }
228 
229  return ( $maxAge <= 0 || $this->getAge( $key, $field ) <= $maxAge );
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 = call_user_func( $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 
319  public function setMaxSize( $maxKeys ) {
320  Assert::parameterType( 'integer', $maxKeys, '$maxKeys' );
321  Assert::parameter( $maxKeys > 0, '$maxKeys', 'must be above zero' );
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 
348  private function getAge( $key, $field = null ) {
349  if ( $field !== null ) {
350  $mtime = $this->timestamps[$key][self::FIELDS][$field] ?? $this->epoch;
351  } else {
352  $mtime = $this->timestamps[$key][self::SIMPLE] ?? $this->epoch;
353  }
354 
355  return ( $this->getCurrentTime() - $mtime );
356  }
357 
358  public function serialize() {
359  return serialize( [
360  'entries' => $this->cache,
361  'timestamps' => $this->timestamps,
362  'maxCacheKeys' => $this->maxCacheKeys,
363  ] );
364  }
365 
366  public function unserialize( $serialized ) {
367  $data = unserialize( $serialized );
368  $this->cache = $data['entries'] ?? [];
369  $this->timestamps = $data['timestamps'] ?? [];
370  // Fallback needed for serializations prior to T218511
371  $this->maxCacheKeys = $data['maxCacheKeys'] ?? ( count( $this->cache ) + 1 );
372  $this->epoch = $this->getCurrentTime();
373  }
374 
379  protected function getCurrentTime() {
380  return $this->wallClockOverride ?: microtime( true );
381  }
382 
387  public function setMockTime( &$time ) {
388  $this->wallClockOverride =& $time;
389  }
390 }
MapCacheLRU\serialize
serialize()
Definition: MapCacheLRU.php:358
MapCacheLRU\$epoch
float $epoch
Default entry timestamp if not specified.
Definition: MapCacheLRU.php:43
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:143
MapCacheLRU\unserialize
unserialize( $serialized)
Definition: MapCacheLRU.php:366
MapCacheLRU\$cache
array $cache
Map of (key => value)
Definition: MapCacheLRU.php:39
MapCacheLRU\getAge
getAge( $key, $field=null)
Definition: MapCacheLRU.php:348
MapCacheLRU\__construct
__construct( $maxKeys)
Definition: MapCacheLRU.php:63
MapCacheLRU\hasField
hasField( $key, $field, $maxAge=INF)
Definition: MapCacheLRU.php:217
MapCacheLRU\newFromArray
static newFromArray(array $values, $maxKeys)
Definition: MapCacheLRU.php:78
MapCacheLRU\$maxCacheKeys
int $maxCacheKeys
Max number of entries.
Definition: MapCacheLRU.php:46
MapCacheLRU
Handles a simple LRU key/value map with a maximum number of entries.
Definition: MapCacheLRU.php:37
MapCacheLRU\$timestamps
array $timestamps
Map of (key => (UNIX timestamp, (field => UNIX timestamp)))
Definition: MapCacheLRU.php:41
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:49
MapCacheLRU\setField
setField( $key, $field, $value, $initRank=self::RANK_TOP)
Definition: MapCacheLRU.php:188
MapCacheLRU\setMaxSize
setMaxSize( $maxKeys)
Resize the maximum number of cache entries, removing older entries as needed.
Definition: MapCacheLRU.php:319
$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:387
MapCacheLRU\toArray
toArray()
Definition: MapCacheLRU.php:91
MapCacheLRU\getCurrentTime
getCurrentTime()
Definition: MapCacheLRU.php:379
$type
$type
Definition: testCompression.php:52