MediaWiki master
MapCacheLRU.php
Go to the documentation of this file.
1<?php
21
35 private $cache = [];
37 private $timestamps = [];
39 private $epoch;
40
42 private $maxCacheKeys;
43
45 private $wallClockOverride;
46
48 private const RANK_TOP = 1.0;
49
51 private const SIMPLE = 0;
53 private const FIELDS = 1;
54
58 public function __construct( int $maxKeys ) {
59 if ( $maxKeys <= 0 ) {
60 throw new InvalidArgumentException( '$maxKeys must be above zero' );
61 }
62
63 $this->maxCacheKeys = $maxKeys;
64 // Use the current time as the default "as of" timestamp of entries
65 $this->epoch = $this->getCurrentTime();
66 }
67
74 public static function newFromArray( array $values, $maxKeys ) {
75 $mapCache = new self( $maxKeys );
76 $mapCache->cache = ( count( $values ) > $maxKeys )
77 ? array_slice( $values, -$maxKeys, null, true )
78 : $values;
79
80 return $mapCache;
81 }
82
87 public function toArray() {
88 return $this->cache;
89 }
90
106 public function set( $key, $value, $rank = self::RANK_TOP ) {
107 if ( $this->has( $key ) ) {
108 $this->ping( $key );
109 } elseif ( count( $this->cache ) >= $this->maxCacheKeys ) {
110 $evictKey = array_key_first( $this->cache );
111 unset( $this->cache[$evictKey] );
112 unset( $this->timestamps[$evictKey] );
113 }
114
115 if ( $rank < 1.0 && $rank > 0 ) {
116 $offset = intval( $rank * count( $this->cache ) );
117 $this->cache = array_slice( $this->cache, 0, $offset, true )
118 + [ $key => $value ]
119 + array_slice( $this->cache, $offset, null, true );
120 } else {
121 $this->cache[$key] = $value;
122 }
123
124 $this->timestamps[$key] = [
125 self::SIMPLE => $this->getCurrentTime(),
126 self::FIELDS => []
127 ];
128 }
129
138 public function has( $key, $maxAge = INF ) {
139 if ( !is_int( $key ) && !is_string( $key ) ) {
140 throw new UnexpectedValueException(
141 __METHOD__ . ': invalid key; must be string or integer.' );
142 }
143 return array_key_exists( $key, $this->cache )
144 && (
145 // Optimization: Avoid expensive getAge/getCurrentTime for common case (T275673)
146 $maxAge === INF
147 || $maxAge <= 0
148 || $this->getKeyAge( $key ) <= $maxAge
149 );
150 }
151
168 public function get( $key, $maxAge = INF, $default = null ) {
169 if ( !$this->has( $key, $maxAge ) ) {
170 return $default;
171 }
172
173 $this->ping( $key );
174
175 return $this->cache[$key];
176 }
177
184 public function setField( $key, $field, $value, $initRank = self::RANK_TOP ) {
185 if ( $this->has( $key ) ) {
186 $this->ping( $key );
187
188 if ( !is_array( $this->cache[$key] ) ) {
189 $type = get_debug_type( $this->cache[$key] );
190 throw new UnexpectedValueException( "Cannot add field to non-array value ('$key' is $type)" );
191 }
192 } else {
193 $this->set( $key, [], $initRank );
194 }
195
196 if ( !is_string( $field ) && !is_int( $field ) ) {
197 throw new UnexpectedValueException(
198 __METHOD__ . ": invalid field for '$key'; must be string or integer." );
199 }
200
201 $this->cache[$key][$field] = $value;
202 $this->timestamps[$key][self::FIELDS][$field] = $this->getCurrentTime();
203 }
204
212 public function hasField( $key, $field, $maxAge = INF ) {
213 $value = $this->get( $key );
214
215 if ( !is_int( $field ) && !is_string( $field ) ) {
216 throw new UnexpectedValueException(
217 __METHOD__ . ": invalid field for '$key'; must be string or integer." );
218 }
219 return is_array( $value )
220 && array_key_exists( $field, $value )
221 && (
222 $maxAge === INF
223 || $maxAge <= 0
224 || $this->getKeyFieldAge( $key, $field ) <= $maxAge
225 );
226 }
227
235 public function getField( $key, $field, $maxAge = INF ) {
236 if ( !$this->hasField( $key, $field, $maxAge ) ) {
237 return null;
238 }
239
240 return $this->cache[$key][$field];
241 }
242
247 public function getAllKeys() {
248 return array_keys( $this->cache );
249 }
250
264 public function getWithSetCallback(
265 $key, callable $callback, $rank = self::RANK_TOP, $maxAge = INF
266 ) {
267 if ( $this->has( $key, $maxAge ) ) {
268 $value = $this->get( $key );
269 } else {
270 $value = $callback();
271 if ( $value !== false ) {
272 $this->set( $key, $value, $rank );
273 }
274 }
275
276 return $value;
277 }
278
286 public function makeKey( ...$components ) {
287 // Based on BagOStuff::makeKeyInternal, except without a required
288 // $keygroup prefix. While MapCacheLRU can and is used as cache for
289 // multiple groups of keys, it is equally common for the instance itself
290 // to represent a single group, and thus have keys where the first component
291 // can directly be a user-controlled variable.
292 $key = '';
293 foreach ( $components as $i => $component ) {
294 if ( $i > 0 ) {
295 $key .= ':';
296 }
297 $key .= strtr( $component, [ '%' => '%25', ':' => '%3A' ] );
298 }
299 return $key;
300 }
301
308 public function clear( $keys = null ) {
309 if ( func_num_args() == 0 ) {
310 $this->cache = [];
311 $this->timestamps = [];
312 } else {
313 foreach ( (array)$keys as $key ) {
314 unset( $this->cache[$key] );
315 unset( $this->timestamps[$key] );
316 }
317 }
318 }
319
326 public function getMaxSize() {
327 return $this->maxCacheKeys;
328 }
329
337 public function setMaxSize( int $maxKeys ) {
338 if ( $maxKeys <= 0 ) {
339 throw new InvalidArgumentException( '$maxKeys must be above zero' );
340 }
341
342 $this->maxCacheKeys = $maxKeys;
343 while ( count( $this->cache ) > $this->maxCacheKeys ) {
344 $evictKey = array_key_first( $this->cache );
345 unset( $this->cache[$evictKey] );
346 unset( $this->timestamps[$evictKey] );
347 }
348 }
349
355 private function ping( $key ) {
356 $item = $this->cache[$key];
357 unset( $this->cache[$key] );
358 $this->cache[$key] = $item;
359 }
360
365 private function getKeyAge( $key ) {
366 $mtime = $this->timestamps[$key][self::SIMPLE] ?? $this->epoch;
367
368 return ( $this->getCurrentTime() - $mtime );
369 }
370
376 private function getKeyFieldAge( $key, $field ) {
377 $mtime = $this->timestamps[$key][self::FIELDS][$field] ?? $this->epoch;
378
379 return ( $this->getCurrentTime() - $mtime );
380 }
381
382 public function __serialize() {
383 return [
384 'entries' => $this->cache,
385 'timestamps' => $this->timestamps,
386 'maxCacheKeys' => $this->maxCacheKeys,
387 ];
388 }
389
390 public function __unserialize( $data ) {
391 $this->cache = $data['entries'] ?? [];
392 $this->timestamps = $data['timestamps'] ?? [];
393 // Fallback needed for serializations prior to T218511
394 $this->maxCacheKeys = $data['maxCacheKeys'] ?? ( count( $this->cache ) + 1 );
395 $this->epoch = $this->getCurrentTime();
396 }
397
402 protected function getCurrentTime() {
403 return $this->wallClockOverride ?: microtime( true );
404 }
405
410 public function setMockTime( &$time ) {
411 $this->wallClockOverride =& $time;
412 }
413}
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.
has( $key, $maxAge=INF)
Check if a key exists.
__unserialize( $data)
static newFromArray(array $values, $maxKeys)
getField( $key, $field, $maxAge=INF)
setMockTime(&$time)
hasField( $key, $field, $maxAge=INF)
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)
makeKey(... $components)
Format a cache key string.
__construct(int $maxKeys)
getWithSetCallback( $key, callable $callback, $rank=self::RANK_TOP, $maxAge=INF)
Get an item with the given key, producing and setting it if not found.
Generic interface providing Time-To-Live constants for expirable object storage.