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