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