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( int $maxKeys ) {
64  Assert::parameter( $maxKeys > 0, '$maxKeys', 'must be above zero' );
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 
148  if ( !array_key_exists( $key, $this->cache ) ) {
149  return false;
150  }
151 
152  return ( $maxAge <= 0 || $this->getAge( $key ) <= $maxAge );
153  }
154 
171  public function get( $key, $maxAge = INF, $default = null ) {
172  if ( !$this->has( $key, $maxAge ) ) {
173  return $default;
174  }
175 
176  $this->ping( $key );
177 
178  return $this->cache[$key];
179  }
180 
187  public function setField( $key, $field, $value, $initRank = self::RANK_TOP ) {
188  if ( $this->has( $key ) ) {
189  $this->ping( $key );
190  } else {
191  $this->set( $key, [], $initRank );
192  }
193 
194  if ( !is_int( $field ) && !is_string( $field ) ) {
195  throw new UnexpectedValueException(
196  __METHOD__ . ": invalid field for '$key'; must be string or integer." );
197  }
198 
199  if ( !is_array( $this->cache[$key] ) ) {
200  $type = gettype( $this->cache[$key] );
201 
202  throw new UnexpectedValueException( "The value of '$key' ($type) is not an array." );
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 
224  if ( !is_array( $value ) || !array_key_exists( $field, $value ) ) {
225  return false;
226  }
227 
228  return ( $maxAge <= 0 || $this->getAge( $key, $field ) <= $maxAge );
229  }
230 
238  public function getField( $key, $field, $maxAge = INF ) {
239  if ( !$this->hasField( $key, $field, $maxAge ) ) {
240  return null;
241  }
242 
243  return $this->cache[$key][$field];
244  }
245 
250  public function getAllKeys() {
251  return array_keys( $this->cache );
252  }
253 
267  public function getWithSetCallback(
268  $key, callable $callback, $rank = self::RANK_TOP, $maxAge = INF
269  ) {
270  if ( $this->has( $key, $maxAge ) ) {
271  $value = $this->get( $key );
272  } else {
273  $value = call_user_func( $callback );
274  if ( $value !== false ) {
275  $this->set( $key, $value, $rank );
276  }
277  }
278 
279  return $value;
280  }
281 
288  public function clear( $keys = null ) {
289  if ( func_num_args() == 0 ) {
290  $this->cache = [];
291  $this->timestamps = [];
292  } else {
293  foreach ( (array)$keys as $key ) {
294  unset( $this->cache[$key] );
295  unset( $this->timestamps[$key] );
296  }
297  }
298  }
299 
306  public function getMaxSize() {
307  return $this->maxCacheKeys;
308  }
309 
318  public function setMaxSize( int $maxKeys ) {
319  Assert::parameter( $maxKeys > 0, '$maxKeys', 'must be above zero' );
320 
321  $this->maxCacheKeys = $maxKeys;
322  while ( count( $this->cache ) > $this->maxCacheKeys ) {
323  reset( $this->cache );
324  $evictKey = key( $this->cache );
325  unset( $this->cache[$evictKey] );
326  unset( $this->timestamps[$evictKey] );
327  }
328  }
329 
335  private function ping( $key ) {
336  $item = $this->cache[$key];
337  unset( $this->cache[$key] );
338  $this->cache[$key] = $item;
339  }
340 
346  private function getAge( $key, $field = null ) {
347  if ( $field !== null ) {
348  $mtime = $this->timestamps[$key][self::FIELDS][$field] ?? $this->epoch;
349  } else {
350  $mtime = $this->timestamps[$key][self::SIMPLE] ?? $this->epoch;
351  }
352 
353  return ( $this->getCurrentTime() - $mtime );
354  }
355 
356  public function serialize() {
357  return serialize( [
358  'entries' => $this->cache,
359  'timestamps' => $this->timestamps,
360  'maxCacheKeys' => $this->maxCacheKeys,
361  ] );
362  }
363 
364  public function unserialize( $serialized ) {
365  $data = unserialize( $serialized );
366  $this->cache = $data['entries'] ?? [];
367  $this->timestamps = $data['timestamps'] ?? [];
368  // Fallback needed for serializations prior to T218511
369  $this->maxCacheKeys = $data['maxCacheKeys'] ?? ( count( $this->cache ) + 1 );
370  $this->epoch = $this->getCurrentTime();
371  }
372 
377  protected function getCurrentTime() {
378  return $this->wallClockOverride ?: microtime( true );
379  }
380 
385  public function setMockTime( &$time ) {
386  $this->wallClockOverride =& $time;
387  }
388 }
MapCacheLRU\serialize
serialize()
Definition: MapCacheLRU.php:356
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:335
MapCacheLRU\getField
getField( $key, $field, $maxAge=INF)
Definition: MapCacheLRU.php:238
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:250
MapCacheLRU\has
has( $key, $maxAge=INF)
Check if a key exists.
Definition: MapCacheLRU.php:142
MapCacheLRU\unserialize
unserialize( $serialized)
Definition: MapCacheLRU.php:364
MapCacheLRU\$cache
array $cache
Map of (key => value)
Definition: MapCacheLRU.php:39
MapCacheLRU\getAge
getAge( $key, $field=null)
Definition: MapCacheLRU.php:346
MapCacheLRU\hasField
hasField( $key, $field, $maxAge=INF)
Definition: MapCacheLRU.php:216
MapCacheLRU\newFromArray
static newFromArray(array $values, $maxKeys)
Definition: MapCacheLRU.php:77
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\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: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:267
MapCacheLRU\getMaxSize
getMaxSize()
Get the maximum number of keys allowed.
Definition: MapCacheLRU.php:306
MapCacheLRU\$wallClockOverride
float null $wallClockOverride
Definition: MapCacheLRU.php:49
MapCacheLRU\setField
setField( $key, $field, $value, $initRank=self::RANK_TOP)
Definition: MapCacheLRU.php:187
$keys
$keys
Definition: testCompression.php:72
MapCacheLRU\clear
clear( $keys=null)
Clear one or several cache entries, or all cache entries.
Definition: MapCacheLRU.php:288
MapCacheLRU\setMockTime
setMockTime(&$time)
Definition: MapCacheLRU.php:385
MapCacheLRU\toArray
toArray()
Definition: MapCacheLRU.php:90
MapCacheLRU\__construct
__construct(int $maxKeys)
Definition: MapCacheLRU.php:63
MapCacheLRU\getCurrentTime
getCurrentTime()
Definition: MapCacheLRU.php:377
$type
$type
Definition: testCompression.php:52