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