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