0ea57a1ea09121c3bc51a9bdb178da91a9f37dcb
[lhc/web/wiklou.git] / includes / libs / objectcache / BagOStuff.php
1 <?php
2 /**
3 * Copyright © 2003-2004 Brion Vibber <brion@pobox.com>
4 * https://www.mediawiki.org/
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @file
22 * @ingroup Cache
23 */
24
25 /**
26 * @defgroup Cache Cache
27 */
28
29 use Psr\Log\LoggerAwareInterface;
30 use Psr\Log\LoggerInterface;
31 use Psr\Log\NullLogger;
32 use Wikimedia\ScopedCallback;
33 use Wikimedia\WaitConditionLoop;
34
35 /**
36 * interface is intended to be more or less compatible with
37 * the PHP memcached client.
38 *
39 * backends for local hash array and SQL table included:
40 * @code
41 * $bag = new HashBagOStuff();
42 * $bag = new SqlBagOStuff(); # connect to db first
43 * @endcode
44 *
45 * @ingroup Cache
46 */
47 abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface {
48 /** @var array[] Lock tracking */
49 protected $locks = [];
50 /** @var int ERR_* class constant */
51 protected $lastError = self::ERR_NONE;
52 /** @var string */
53 protected $keyspace = 'local';
54 /** @var LoggerInterface */
55 protected $logger;
56 /** @var callback|null */
57 protected $asyncHandler;
58 /** @var int Seconds */
59 protected $syncTimeout;
60
61 /** @var bool */
62 private $debugMode = false;
63 /** @var array */
64 private $duplicateKeyLookups = [];
65 /** @var bool */
66 private $reportDupes = false;
67 /** @var bool */
68 private $dupeTrackScheduled = false;
69
70 /** @var callable[] */
71 protected $busyCallbacks = [];
72
73 /** @var float|null */
74 private $wallClockOverride;
75
76 /** @var int[] Map of (ATTR_* class constant => QOS_* class constant) */
77 protected $attrMap = [];
78
79 /** Possible values for getLastError() */
80 const ERR_NONE = 0; // no error
81 const ERR_NO_RESPONSE = 1; // no response
82 const ERR_UNREACHABLE = 2; // can't connect
83 const ERR_UNEXPECTED = 3; // response gave some error
84
85 /** Bitfield constants for get()/getMulti() */
86 const READ_LATEST = 1; // use latest data for replicated stores
87 const READ_VERIFIED = 2; // promise that caller can tell when keys are stale
88 /** Bitfield constants for set()/merge() */
89 const WRITE_SYNC = 1; // synchronously write to all locations for replicated stores
90 const WRITE_CACHE_ONLY = 2; // Only change state of the in-memory cache
91
92 /**
93 * $params include:
94 * - logger: Psr\Log\LoggerInterface instance
95 * - keyspace: Default keyspace for $this->makeKey()
96 * - asyncHandler: Callable to use for scheduling tasks after the web request ends.
97 * In CLI mode, it should run the task immediately.
98 * - reportDupes: Whether to emit warning log messages for all keys that were
99 * requested more than once (requires an asyncHandler).
100 * - syncTimeout: How long to wait with WRITE_SYNC in seconds.
101 * @param array $params
102 */
103 public function __construct( array $params = [] ) {
104 if ( isset( $params['logger'] ) ) {
105 $this->setLogger( $params['logger'] );
106 } else {
107 $this->setLogger( new NullLogger() );
108 }
109
110 if ( isset( $params['keyspace'] ) ) {
111 $this->keyspace = $params['keyspace'];
112 }
113
114 $this->asyncHandler = isset( $params['asyncHandler'] )
115 ? $params['asyncHandler']
116 : null;
117
118 if ( !empty( $params['reportDupes'] ) && is_callable( $this->asyncHandler ) ) {
119 $this->reportDupes = true;
120 }
121
122 $this->syncTimeout = isset( $params['syncTimeout'] ) ? $params['syncTimeout'] : 3;
123 }
124
125 /**
126 * @param LoggerInterface $logger
127 * @return null
128 */
129 public function setLogger( LoggerInterface $logger ) {
130 $this->logger = $logger;
131 }
132
133 /**
134 * @param bool $bool
135 */
136 public function setDebug( $bool ) {
137 $this->debugMode = $bool;
138 }
139
140 /**
141 * Get an item with the given key, regenerating and setting it if not found
142 *
143 * If the callback returns false, then nothing is stored.
144 *
145 * @param string $key
146 * @param int $ttl Time-to-live (seconds)
147 * @param callable $callback Callback that derives the new value
148 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
149 * @return mixed The cached value if found or the result of $callback otherwise
150 * @since 1.27
151 */
152 final public function getWithSetCallback( $key, $ttl, $callback, $flags = 0 ) {
153 $value = $this->get( $key, $flags );
154
155 if ( $value === false ) {
156 if ( !is_callable( $callback ) ) {
157 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
158 }
159 $value = call_user_func( $callback );
160 if ( $value !== false ) {
161 $this->set( $key, $value, $ttl );
162 }
163 }
164
165 return $value;
166 }
167
168 /**
169 * Get an item with the given key
170 *
171 * If the key includes a determistic input hash (e.g. the key can only have
172 * the correct value) or complete staleness checks are handled by the caller
173 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
174 * This lets tiered backends know they can safely upgrade a cached value to
175 * higher tiers using standard TTLs.
176 *
177 * @param string $key
178 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
179 * @param int $oldFlags [unused]
180 * @return mixed Returns false on failure and if the item does not exist
181 */
182 public function get( $key, $flags = 0, $oldFlags = null ) {
183 // B/C for ( $key, &$casToken = null, $flags = 0 )
184 $flags = is_int( $oldFlags ) ? $oldFlags : $flags;
185
186 $this->trackDuplicateKeys( $key );
187
188 return $this->doGet( $key, $flags );
189 }
190
191 /**
192 * Track the number of times that a given key has been used.
193 * @param string $key
194 */
195 private function trackDuplicateKeys( $key ) {
196 if ( !$this->reportDupes ) {
197 return;
198 }
199
200 if ( !isset( $this->duplicateKeyLookups[$key] ) ) {
201 // Track that we have seen this key. This N-1 counting style allows
202 // easy filtering with array_filter() later.
203 $this->duplicateKeyLookups[$key] = 0;
204 } else {
205 $this->duplicateKeyLookups[$key] += 1;
206
207 if ( $this->dupeTrackScheduled === false ) {
208 $this->dupeTrackScheduled = true;
209 // Schedule a callback that logs keys processed more than once by get().
210 call_user_func( $this->asyncHandler, function () {
211 $dups = array_filter( $this->duplicateKeyLookups );
212 foreach ( $dups as $key => $count ) {
213 $this->logger->warning(
214 'Duplicate get(): "{key}" fetched {count} times',
215 // Count is N-1 of the actual lookup count
216 [ 'key' => $key, 'count' => $count + 1, ]
217 );
218 }
219 } );
220 }
221 }
222 }
223
224 /**
225 * @param string $key
226 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
227 * @return mixed Returns false on failure and if the item does not exist
228 */
229 abstract protected function doGet( $key, $flags = 0 );
230
231 /**
232 * @note: This method is only needed if merge() uses mergeViaCas()
233 *
234 * @param string $key
235 * @param mixed &$casToken
236 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
237 * @return mixed Returns false on failure and if the item does not exist
238 * @throws Exception
239 */
240 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
241 throw new Exception( __METHOD__ . ' not implemented.' );
242 }
243
244 /**
245 * Set an item
246 *
247 * @param string $key
248 * @param mixed $value
249 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
250 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
251 * @return bool Success
252 */
253 abstract public function set( $key, $value, $exptime = 0, $flags = 0 );
254
255 /**
256 * Delete an item
257 *
258 * @param string $key
259 * @return bool True if the item was deleted or not found, false on failure
260 */
261 abstract public function delete( $key );
262
263 /**
264 * Merge changes into the existing cache value (possibly creating a new one)
265 *
266 * The callback function returns the new value given the current value
267 * (which will be false if not present), and takes the arguments:
268 * (this BagOStuff, cache key, current value, TTL).
269 * The TTL parameter is reference set to $exptime. It can be overriden in the callback.
270 *
271 * @param string $key
272 * @param callable $callback Callback method to be executed
273 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
274 * @param int $attempts The amount of times to attempt a merge in case of failure
275 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
276 * @return bool Success
277 * @throws InvalidArgumentException
278 */
279 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
280 return $this->mergeViaLock( $key, $callback, $exptime, $attempts, $flags );
281 }
282
283 /**
284 * @see BagOStuff::merge()
285 *
286 * @param string $key
287 * @param callable $callback Callback method to be executed
288 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
289 * @param int $attempts The amount of times to attempt a merge in case of failure
290 * @return bool Success
291 */
292 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
293 do {
294 $this->clearLastError();
295 $reportDupes = $this->reportDupes;
296 $this->reportDupes = false;
297 $casToken = null; // passed by reference
298 $currentValue = $this->getWithToken( $key, $casToken, self::READ_LATEST );
299 $this->reportDupes = $reportDupes;
300
301 if ( $this->getLastError() ) {
302 return false; // don't spam retries (retry only on races)
303 }
304
305 // Derive the new value from the old value
306 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
307
308 $this->clearLastError();
309 if ( $value === false ) {
310 $success = true; // do nothing
311 } elseif ( $currentValue === false ) {
312 // Try to create the key, failing if it gets created in the meantime
313 $success = $this->add( $key, $value, $exptime );
314 } else {
315 // Try to update the key, failing if it gets changed in the meantime
316 $success = $this->cas( $casToken, $key, $value, $exptime );
317 }
318 if ( $this->getLastError() ) {
319 return false; // IO error; don't spam retries
320 }
321 } while ( !$success && --$attempts );
322
323 return $success;
324 }
325
326 /**
327 * Check and set an item
328 *
329 * @param mixed $casToken
330 * @param string $key
331 * @param mixed $value
332 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
333 * @return bool Success
334 * @throws Exception
335 */
336 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
337 throw new Exception( "CAS is not implemented in " . __CLASS__ );
338 }
339
340 /**
341 * @see BagOStuff::merge()
342 *
343 * @param string $key
344 * @param callable $callback Callback method to be executed
345 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
346 * @param int $attempts The amount of times to attempt a merge in case of failure
347 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
348 * @return bool Success
349 */
350 protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
351 if ( !$this->lock( $key, 6 ) ) {
352 return false;
353 }
354
355 $this->clearLastError();
356 $reportDupes = $this->reportDupes;
357 $this->reportDupes = false;
358 $currentValue = $this->get( $key, self::READ_LATEST );
359 $this->reportDupes = $reportDupes;
360
361 if ( $this->getLastError() ) {
362 $success = false;
363 } else {
364 // Derive the new value from the old value
365 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
366 if ( $value === false ) {
367 $success = true; // do nothing
368 } else {
369 $success = $this->set( $key, $value, $exptime, $flags ); // set the new value
370 }
371 }
372
373 if ( !$this->unlock( $key ) ) {
374 // this should never happen
375 trigger_error( "Could not release lock for key '$key'." );
376 }
377
378 return $success;
379 }
380
381 /**
382 * Reset the TTL on a key if it exists
383 *
384 * @param string $key
385 * @param int $expiry
386 * @return bool Success Returns false if there is no key
387 * @since 1.28
388 */
389 public function changeTTL( $key, $expiry = 0 ) {
390 $value = $this->get( $key );
391
392 return ( $value === false ) ? false : $this->set( $key, $value, $expiry );
393 }
394
395 /**
396 * Acquire an advisory lock on a key string
397 *
398 * Note that if reentry is enabled, duplicate calls ignore $expiry
399 *
400 * @param string $key
401 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
402 * @param int $expiry Lock expiry [optional]; 1 day maximum
403 * @param string $rclass Allow reentry if set and the current lock used this value
404 * @return bool Success
405 */
406 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
407 // Avoid deadlocks and allow lock reentry if specified
408 if ( isset( $this->locks[$key] ) ) {
409 if ( $rclass != '' && $this->locks[$key]['class'] === $rclass ) {
410 ++$this->locks[$key]['depth'];
411 return true;
412 } else {
413 return false;
414 }
415 }
416
417 $expiry = min( $expiry ?: INF, self::TTL_DAY );
418 $loop = new WaitConditionLoop(
419 function () use ( $key, $timeout, $expiry ) {
420 $this->clearLastError();
421 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
422 return true; // locked!
423 } elseif ( $this->getLastError() ) {
424 return WaitConditionLoop::CONDITION_ABORTED; // network partition?
425 }
426
427 return WaitConditionLoop::CONDITION_CONTINUE;
428 },
429 $timeout
430 );
431
432 $locked = ( $loop->invoke() === $loop::CONDITION_REACHED );
433 if ( $locked ) {
434 $this->locks[$key] = [ 'class' => $rclass, 'depth' => 1 ];
435 }
436
437 return $locked;
438 }
439
440 /**
441 * Release an advisory lock on a key string
442 *
443 * @param string $key
444 * @return bool Success
445 */
446 public function unlock( $key ) {
447 if ( isset( $this->locks[$key] ) && --$this->locks[$key]['depth'] <= 0 ) {
448 unset( $this->locks[$key] );
449
450 return $this->delete( "{$key}:lock" );
451 }
452
453 return true;
454 }
455
456 /**
457 * Get a lightweight exclusive self-unlocking lock
458 *
459 * Note that the same lock cannot be acquired twice.
460 *
461 * This is useful for task de-duplication or to avoid obtrusive
462 * (though non-corrupting) DB errors like INSERT key conflicts
463 * or deadlocks when using LOCK IN SHARE MODE.
464 *
465 * @param string $key
466 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
467 * @param int $expiry Lock expiry [optional]; 1 day maximum
468 * @param string $rclass Allow reentry if set and the current lock used this value
469 * @return ScopedCallback|null Returns null on failure
470 * @since 1.26
471 */
472 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
473 $expiry = min( $expiry ?: INF, self::TTL_DAY );
474
475 if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
476 return null;
477 }
478
479 $lSince = $this->getCurrentTime(); // lock timestamp
480
481 return new ScopedCallback( function () use ( $key, $lSince, $expiry ) {
482 $latency = 0.050; // latency skew (err towards keeping lock present)
483 $age = ( $this->getCurrentTime() - $lSince + $latency );
484 if ( ( $age + $latency ) >= $expiry ) {
485 $this->logger->warning( "Lock for $key held too long ($age sec)." );
486 return; // expired; it's not "safe" to delete the key
487 }
488 $this->unlock( $key );
489 } );
490 }
491
492 /**
493 * Delete all objects expiring before a certain date.
494 * @param string $date The reference date in MW format
495 * @param callable|bool $progressCallback Optional, a function which will be called
496 * regularly during long-running operations with the percentage progress
497 * as the first parameter.
498 *
499 * @return bool Success, false if unimplemented
500 */
501 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
502 // stub
503 return false;
504 }
505
506 /**
507 * Get an associative array containing the item for each of the keys that have items.
508 * @param array $keys List of strings
509 * @param int $flags Bitfield; supports READ_LATEST [optional]
510 * @return array
511 */
512 public function getMulti( array $keys, $flags = 0 ) {
513 $res = [];
514 foreach ( $keys as $key ) {
515 $val = $this->get( $key );
516 if ( $val !== false ) {
517 $res[$key] = $val;
518 }
519 }
520 return $res;
521 }
522
523 /**
524 * Batch insertion
525 * @param array $data $key => $value assoc array
526 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
527 * @return bool Success
528 * @since 1.24
529 */
530 public function setMulti( array $data, $exptime = 0 ) {
531 $res = true;
532 foreach ( $data as $key => $value ) {
533 if ( !$this->set( $key, $value, $exptime ) ) {
534 $res = false;
535 }
536 }
537 return $res;
538 }
539
540 /**
541 * @param string $key
542 * @param mixed $value
543 * @param int $exptime
544 * @return bool Success
545 */
546 public function add( $key, $value, $exptime = 0 ) {
547 if ( $this->get( $key ) === false ) {
548 return $this->set( $key, $value, $exptime );
549 }
550 return false; // key already set
551 }
552
553 /**
554 * Increase stored value of $key by $value while preserving its TTL
555 * @param string $key Key to increase
556 * @param int $value Value to add to $key (Default 1)
557 * @return int|bool New value or false on failure
558 */
559 public function incr( $key, $value = 1 ) {
560 if ( !$this->lock( $key ) ) {
561 return false;
562 }
563 $n = $this->get( $key );
564 if ( $this->isInteger( $n ) ) { // key exists?
565 $n += intval( $value );
566 $this->set( $key, max( 0, $n ) ); // exptime?
567 } else {
568 $n = false;
569 }
570 $this->unlock( $key );
571
572 return $n;
573 }
574
575 /**
576 * Decrease stored value of $key by $value while preserving its TTL
577 * @param string $key
578 * @param int $value
579 * @return int|bool New value or false on failure
580 */
581 public function decr( $key, $value = 1 ) {
582 return $this->incr( $key, - $value );
583 }
584
585 /**
586 * Increase stored value of $key by $value while preserving its TTL
587 *
588 * This will create the key with value $init and TTL $ttl instead if not present
589 *
590 * @param string $key
591 * @param int $ttl
592 * @param int $value
593 * @param int $init
594 * @return int|bool New value or false on failure
595 * @since 1.24
596 */
597 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
598 $newValue = $this->incr( $key, $value );
599 if ( $newValue === false ) {
600 // No key set; initialize
601 $newValue = $this->add( $key, (int)$init, $ttl ) ? $init : false;
602 }
603 if ( $newValue === false ) {
604 // Raced out initializing; increment
605 $newValue = $this->incr( $key, $value );
606 }
607
608 return $newValue;
609 }
610
611 /**
612 * Get the "last error" registered; clearLastError() should be called manually
613 * @return int ERR_* constant for the "last error" registry
614 * @since 1.23
615 */
616 public function getLastError() {
617 return $this->lastError;
618 }
619
620 /**
621 * Clear the "last error" registry
622 * @since 1.23
623 */
624 public function clearLastError() {
625 $this->lastError = self::ERR_NONE;
626 }
627
628 /**
629 * Set the "last error" registry
630 * @param int $err ERR_* constant
631 * @since 1.23
632 */
633 protected function setLastError( $err ) {
634 $this->lastError = $err;
635 }
636
637 /**
638 * Let a callback be run to avoid wasting time on special blocking calls
639 *
640 * The callbacks may or may not be called ever, in any particular order.
641 * They are likely to be invoked when something WRITE_SYNC is used used.
642 * They should follow a caching pattern as shown below, so that any code
643 * using the word will get it's result no matter what happens.
644 * @code
645 * $result = null;
646 * $workCallback = function () use ( &$result ) {
647 * if ( !$result ) {
648 * $result = ....
649 * }
650 * return $result;
651 * }
652 * @endcode
653 *
654 * @param callable $workCallback
655 * @since 1.28
656 */
657 public function addBusyCallback( callable $workCallback ) {
658 $this->busyCallbacks[] = $workCallback;
659 }
660
661 /**
662 * Modify a cache update operation array for EventRelayer::notify()
663 *
664 * This is used for relayed writes, e.g. for broadcasting a change
665 * to multiple data-centers. If the array contains a 'val' field
666 * then the command involves setting a key to that value. Note that
667 * for simplicity, 'val' is always a simple scalar value. This method
668 * is used to possibly serialize the value and add any cache-specific
669 * key/values needed for the relayer daemon (e.g. memcached flags).
670 *
671 * @param array $event
672 * @return array
673 * @since 1.26
674 */
675 public function modifySimpleRelayEvent( array $event ) {
676 return $event;
677 }
678
679 /**
680 * @param string $text
681 */
682 protected function debug( $text ) {
683 if ( $this->debugMode ) {
684 $this->logger->debug( "{class} debug: $text", [
685 'class' => static::class,
686 ] );
687 }
688 }
689
690 /**
691 * Convert an optionally relative time to an absolute time
692 * @param int $exptime
693 * @return int
694 */
695 protected function convertExpiry( $exptime ) {
696 if ( $exptime != 0 && $exptime < ( 10 * self::TTL_YEAR ) ) {
697 return (int)$this->getCurrentTime() + $exptime;
698 } else {
699 return $exptime;
700 }
701 }
702
703 /**
704 * Convert an optionally absolute expiry time to a relative time. If an
705 * absolute time is specified which is in the past, use a short expiry time.
706 *
707 * @param int $exptime
708 * @return int
709 */
710 protected function convertToRelative( $exptime ) {
711 if ( $exptime >= ( 10 * self::TTL_YEAR ) ) {
712 $exptime -= (int)$this->getCurrentTime();
713 if ( $exptime <= 0 ) {
714 $exptime = 1;
715 }
716 return $exptime;
717 } else {
718 return $exptime;
719 }
720 }
721
722 /**
723 * Check if a value is an integer
724 *
725 * @param mixed $value
726 * @return bool
727 */
728 protected function isInteger( $value ) {
729 return ( is_int( $value ) || ctype_digit( $value ) );
730 }
731
732 /**
733 * Construct a cache key.
734 *
735 * @since 1.27
736 * @param string $keyspace
737 * @param array $args
738 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
739 */
740 public function makeKeyInternal( $keyspace, $args ) {
741 $key = $keyspace;
742 foreach ( $args as $arg ) {
743 $arg = str_replace( ':', '%3A', $arg );
744 $key = $key . ':' . $arg;
745 }
746 return strtr( $key, ' ', '_' );
747 }
748
749 /**
750 * Make a global cache key.
751 *
752 * @since 1.27
753 * @param string $class Key class
754 * @param string $component [optional] Key component (starting with a key collection name)
755 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
756 */
757 public function makeGlobalKey( $class, $component = null ) {
758 return $this->makeKeyInternal( 'global', func_get_args() );
759 }
760
761 /**
762 * Make a cache key, scoped to this instance's keyspace.
763 *
764 * @since 1.27
765 * @param string $class Key class
766 * @param string $component [optional] Key component (starting with a key collection name)
767 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
768 */
769 public function makeKey( $class, $component = null ) {
770 return $this->makeKeyInternal( $this->keyspace, func_get_args() );
771 }
772
773 /**
774 * @param int $flag ATTR_* class constant
775 * @return int QOS_* class constant
776 * @since 1.28
777 */
778 public function getQoS( $flag ) {
779 return isset( $this->attrMap[$flag] ) ? $this->attrMap[$flag] : self::QOS_UNKNOWN;
780 }
781
782 /**
783 * Merge the flag maps of one or more BagOStuff objects into a "lowest common denominator" map
784 *
785 * @param BagOStuff[] $bags
786 * @return int[] Resulting flag map (class ATTR_* constant => class QOS_* constant)
787 */
788 protected function mergeFlagMaps( array $bags ) {
789 $map = [];
790 foreach ( $bags as $bag ) {
791 foreach ( $bag->attrMap as $attr => $rank ) {
792 if ( isset( $map[$attr] ) ) {
793 $map[$attr] = min( $map[$attr], $rank );
794 } else {
795 $map[$attr] = $rank;
796 }
797 }
798 }
799
800 return $map;
801 }
802
803 /**
804 * @return float UNIX timestamp
805 * @codeCoverageIgnore
806 */
807 protected function getCurrentTime() {
808 return $this->wallClockOverride ?: microtime( true );
809 }
810
811 /**
812 * @param float|null &$time Mock UNIX timestamp for testing
813 * @codeCoverageIgnore
814 */
815 public function setMockTime( &$time ) {
816 $this->wallClockOverride =& $time;
817 }
818 }