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