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