Merge "Improve docs for Title::getInternalURL/getCanonicalURL"
[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 callable|null */
68 protected $asyncHandler;
69 /** @var int Seconds */
70 protected $syncTimeout;
71
72 /** @var bool */
73 private $debugMode = false;
74 /** @var array */
75 private $duplicateKeyLookups = [];
76 /** @var bool */
77 private $reportDupes = false;
78 /** @var bool */
79 private $dupeTrackScheduled = false;
80
81 /** @var callable[] */
82 protected $busyCallbacks = [];
83
84 /** @var float|null */
85 private $wallClockOverride;
86
87 /** @var int[] Map of (ATTR_* class constant => QOS_* class constant) */
88 protected $attrMap = [];
89
90 /** Bitfield constants for get()/getMulti() */
91 const READ_LATEST = 1; // use latest data for replicated stores
92 const READ_VERIFIED = 2; // promise that caller can tell when keys are stale
93 /** Bitfield constants for set()/merge() */
94 const WRITE_SYNC = 4; // synchronously write to all locations for replicated stores
95 const WRITE_CACHE_ONLY = 8; // Only change state of the in-memory cache
96
97 /**
98 * $params include:
99 * - logger: Psr\Log\LoggerInterface instance
100 * - keyspace: Default keyspace for $this->makeKey()
101 * - asyncHandler: Callable to use for scheduling tasks after the web request ends.
102 * In CLI mode, it should run the task immediately.
103 * - reportDupes: Whether to emit warning log messages for all keys that were
104 * requested more than once (requires an asyncHandler).
105 * - syncTimeout: How long to wait with WRITE_SYNC in seconds.
106 * @param array $params
107 */
108 public function __construct( array $params = [] ) {
109 $this->setLogger( $params['logger'] ?? new NullLogger() );
110
111 if ( isset( $params['keyspace'] ) ) {
112 $this->keyspace = $params['keyspace'];
113 }
114
115 $this->asyncHandler = $params['asyncHandler'] ?? null;
116
117 if ( !empty( $params['reportDupes'] ) && is_callable( $this->asyncHandler ) ) {
118 $this->reportDupes = true;
119 }
120
121 $this->syncTimeout = $params['syncTimeout'] ?? 3;
122 }
123
124 /**
125 * @param LoggerInterface $logger
126 * @return void
127 */
128 public function setLogger( LoggerInterface $logger ) {
129 $this->logger = $logger;
130 }
131
132 /**
133 * @param bool $bool
134 */
135 public function setDebug( $bool ) {
136 $this->debugMode = $bool;
137 }
138
139 /**
140 * Get an item with the given key, regenerating and setting it if not found
141 *
142 * Nothing is stored nor deleted if the callback returns false
143 *
144 * @param string $key
145 * @param int $ttl Time-to-live (seconds)
146 * @param callable $callback Callback that derives the new value
147 * @param int $flags Bitfield of BagOStuff::READ_* or BagOStuff::WRITE_* constants [optional]
148 * @return mixed The cached value if found or the result of $callback otherwise
149 * @since 1.27
150 */
151 final public function getWithSetCallback( $key, $ttl, $callback, $flags = 0 ) {
152 $value = $this->get( $key, $flags );
153
154 if ( $value === false ) {
155 if ( !is_callable( $callback ) ) {
156 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
157 }
158 $value = call_user_func( $callback );
159 if ( $value !== false ) {
160 $this->set( $key, $value, $ttl, $flags );
161 }
162 }
163
164 return $value;
165 }
166
167 /**
168 * Get an item with the given key
169 *
170 * If the key includes a deterministic input hash (e.g. the key can only have
171 * the correct value) or complete staleness checks are handled by the caller
172 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
173 * This lets tiered backends know they can safely upgrade a cached value to
174 * higher tiers using standard TTLs.
175 *
176 * @param string $key
177 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
178 * @return mixed Returns false on failure or if the item does not exist
179 */
180 public function get( $key, $flags = 0 ) {
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 int $flags Bitfield of BagOStuff::READ_* constants [optional]
222 * @param mixed|null &$casToken Token to use for check-and-set comparisons
223 * @return mixed Returns false on failure or if the item does not exist
224 */
225 abstract protected function doGet( $key, $flags = 0, &$casToken = null );
226
227 /**
228 * Set an item
229 *
230 * @param string $key
231 * @param mixed $value
232 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
233 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
234 * @return bool Success
235 */
236 abstract public function set( $key, $value, $exptime = 0, $flags = 0 );
237
238 /**
239 * Delete an item
240 *
241 * @param string $key
242 * @return bool True if the item was deleted or not found, false on failure
243 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
244 */
245 abstract public function delete( $key, $flags = 0 );
246
247 /**
248 * Insert an item if it does not already exist
249 *
250 * @param string $key
251 * @param mixed $value
252 * @param int $exptime
253 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
254 * @return bool Success
255 */
256 abstract public function add( $key, $value, $exptime = 0, $flags = 0 );
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 * Nothing is stored nor deleted if the callback returns false.
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->mergeViaCas( $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 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
287 * @return bool Success
288 */
289 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
290 do {
291 $casToken = null; // passed by reference
292 // Get the old value and CAS token from cache
293 $this->clearLastError();
294 $currentValue = $this->doGet( $key, self::READ_LATEST, $casToken );
295 if ( $this->getLastError() ) {
296 $this->logger->warning(
297 __METHOD__ . ' failed due to I/O error on get() for {key}.',
298 [ 'key' => $key ]
299 );
300
301 return false; // don't spam retries (retry only on races)
302 }
303
304 // Derive the new value from the old value
305 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
306 $hadNoCurrentValue = ( $currentValue === false );
307 unset( $currentValue ); // free RAM in case the value is large
308
309 $this->clearLastError();
310 if ( $value === false ) {
311 $success = true; // do nothing
312 } elseif ( $hadNoCurrentValue ) {
313 // Try to create the key, failing if it gets created in the meantime
314 $success = $this->add( $key, $value, $exptime, $flags );
315 } else {
316 // Try to update the key, failing if it gets changed in the meantime
317 $success = $this->cas( $casToken, $key, $value, $exptime, $flags );
318 }
319 if ( $this->getLastError() ) {
320 $this->logger->warning(
321 __METHOD__ . ' failed due to I/O error for {key}.',
322 [ 'key' => $key ]
323 );
324
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 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
340 * @return bool Success
341 * @throws Exception
342 */
343 protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
344 if ( !$this->lock( $key, 0 ) ) {
345 return false; // non-blocking
346 }
347
348 $curCasToken = null; // passed by reference
349 $this->doGet( $key, self::READ_LATEST, $curCasToken );
350 if ( $casToken === $curCasToken ) {
351 $success = $this->set( $key, $value, $exptime, $flags );
352 } else {
353 $this->logger->info(
354 __METHOD__ . ' failed due to race condition for {key}.',
355 [ 'key' => $key ]
356 );
357
358 $success = false; // mismatched or failed
359 }
360
361 $this->unlock( $key );
362
363 return $success;
364 }
365
366 /**
367 * Change the expiration on a key if it exists
368 *
369 * If an expiry in the past is given then the key will immediately be expired
370 *
371 * @param string $key
372 * @param int $expiry TTL or UNIX timestamp
373 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
374 * @return bool Success Returns false on failure or if the item does not exist
375 * @since 1.28
376 */
377 public function changeTTL( $key, $expiry = 0, $flags = 0 ) {
378 $found = false;
379
380 $ok = $this->merge(
381 $key,
382 function ( $cache, $ttl, $currentValue ) use ( &$found ) {
383 $found = ( $currentValue !== false );
384
385 return $currentValue; // nothing is written if this is false
386 },
387 $expiry,
388 1, // 1 attempt
389 $flags
390 );
391
392 return ( $ok && $found );
393 }
394
395 /**
396 * Acquire an advisory lock on a key string
397 *
398 * Note that if reentry is enabled, duplicate calls ignore $expiry
399 *
400 * @param string $key
401 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
402 * @param int $expiry Lock expiry [optional]; 1 day maximum
403 * @param string $rclass Allow reentry if set and the current lock used this value
404 * @return bool Success
405 */
406 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
407 // Avoid deadlocks and allow lock reentry if specified
408 if ( isset( $this->locks[$key] ) ) {
409 if ( $rclass != '' && $this->locks[$key]['class'] === $rclass ) {
410 ++$this->locks[$key]['depth'];
411 return true;
412 } else {
413 return false;
414 }
415 }
416
417 $fname = __METHOD__;
418 $expiry = min( $expiry ?: INF, self::TTL_DAY );
419 $loop = new WaitConditionLoop(
420 function () use ( $key, $expiry, $fname ) {
421 $this->clearLastError();
422 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
423 return WaitConditionLoop::CONDITION_REACHED; // locked!
424 } elseif ( $this->getLastError() ) {
425 $this->logger->warning(
426 $fname . ' failed due to I/O error for {key}.',
427 [ 'key' => $key ]
428 );
429
430 return WaitConditionLoop::CONDITION_ABORTED; // network partition?
431 }
432
433 return WaitConditionLoop::CONDITION_CONTINUE;
434 },
435 $timeout
436 );
437
438 $code = $loop->invoke();
439 $locked = ( $code === $loop::CONDITION_REACHED );
440 if ( $locked ) {
441 $this->locks[$key] = [ 'class' => $rclass, 'depth' => 1 ];
442 } elseif ( $code === $loop::CONDITION_TIMED_OUT ) {
443 $this->logger->warning(
444 "$fname failed due to timeout for {key}.",
445 [ 'key' => $key, 'timeout' => $timeout ]
446 );
447 }
448
449 return $locked;
450 }
451
452 /**
453 * Release an advisory lock on a key string
454 *
455 * @param string $key
456 * @return bool Success
457 */
458 public function unlock( $key ) {
459 if ( isset( $this->locks[$key] ) && --$this->locks[$key]['depth'] <= 0 ) {
460 unset( $this->locks[$key] );
461
462 $ok = $this->delete( "{$key}:lock" );
463 if ( !$ok ) {
464 $this->logger->warning(
465 __METHOD__ . ' failed to release lock for {key}.',
466 [ 'key' => $key ]
467 );
468 }
469
470 return $ok;
471 }
472
473 return true;
474 }
475
476 /**
477 * Get a lightweight exclusive self-unlocking lock
478 *
479 * Note that the same lock cannot be acquired twice.
480 *
481 * This is useful for task de-duplication or to avoid obtrusive
482 * (though non-corrupting) DB errors like INSERT key conflicts
483 * or deadlocks when using LOCK IN SHARE MODE.
484 *
485 * @param string $key
486 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
487 * @param int $expiry Lock expiry [optional]; 1 day maximum
488 * @param string $rclass Allow reentry if set and the current lock used this value
489 * @return ScopedCallback|null Returns null on failure
490 * @since 1.26
491 */
492 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
493 $expiry = min( $expiry ?: INF, self::TTL_DAY );
494
495 if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
496 return null;
497 }
498
499 $lSince = $this->getCurrentTime(); // lock timestamp
500
501 return new ScopedCallback( function () use ( $key, $lSince, $expiry ) {
502 $latency = 0.050; // latency skew (err towards keeping lock present)
503 $age = ( $this->getCurrentTime() - $lSince + $latency );
504 if ( ( $age + $latency ) >= $expiry ) {
505 $this->logger->warning(
506 "Lock for {key} held too long ({age} sec).",
507 [ 'key' => $key, 'age' => $age ]
508 );
509 return; // expired; it's not "safe" to delete the key
510 }
511 $this->unlock( $key );
512 } );
513 }
514
515 /**
516 * Delete all objects expiring before a certain date.
517 * @param string $date The reference date in MW format
518 * @param callable|bool $progressCallback Optional, a function which will be called
519 * regularly during long-running operations with the percentage progress
520 * as the first parameter.
521 *
522 * @return bool Success, false if unimplemented
523 */
524 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
525 // stub
526 return false;
527 }
528
529 /**
530 * Get an associative array containing the item for each of the keys that have items.
531 * @param string[] $keys List of keys
532 * @param int $flags Bitfield; supports READ_LATEST [optional]
533 * @return array
534 */
535 public function getMulti( array $keys, $flags = 0 ) {
536 $res = [];
537 foreach ( $keys as $key ) {
538 $val = $this->get( $key, $flags );
539 if ( $val !== false ) {
540 $res[$key] = $val;
541 }
542 }
543
544 return $res;
545 }
546
547 /**
548 * Batch insertion/replace
549 * @param mixed[] $data Map of (key => value)
550 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
551 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
552 * @return bool Success
553 * @since 1.24
554 */
555 public function setMulti( array $data, $exptime = 0, $flags = 0 ) {
556 $res = true;
557 foreach ( $data as $key => $value ) {
558 if ( !$this->set( $key, $value, $exptime, $flags ) ) {
559 $res = false;
560 }
561 }
562
563 return $res;
564 }
565
566 /**
567 * Batch deletion
568 * @param string[] $keys List of keys
569 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
570 * @return bool Success
571 * @since 1.33
572 */
573 public function deleteMulti( array $keys, $flags = 0 ) {
574 $res = true;
575 foreach ( $keys as $key ) {
576 $res = $this->delete( $key, $flags ) && $res;
577 }
578
579 return $res;
580 }
581
582 /**
583 * Increase stored value of $key by $value while preserving its TTL
584 * @param string $key Key to increase
585 * @param int $value Value to add to $key (default: 1) [optional]
586 * @return int|bool New value or false on failure
587 */
588 abstract public function incr( $key, $value = 1 );
589
590 /**
591 * Decrease stored value of $key by $value while preserving its TTL
592 * @param string $key
593 * @param int $value Value to subtract from $key (default: 1) [optional]
594 * @return int|bool New value or false on failure
595 */
596 public function decr( $key, $value = 1 ) {
597 return $this->incr( $key, - $value );
598 }
599
600 /**
601 * Increase stored value of $key by $value while preserving its TTL
602 *
603 * This will create the key with value $init and TTL $ttl instead if not present
604 *
605 * @param string $key
606 * @param int $ttl
607 * @param int $value
608 * @param int $init
609 * @return int|bool New value or false on failure
610 * @since 1.24
611 */
612 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
613 $this->clearLastError();
614 $newValue = $this->incr( $key, $value );
615 if ( $newValue === false && !$this->getLastError() ) {
616 // No key set; initialize
617 $newValue = $this->add( $key, (int)$init, $ttl ) ? $init : false;
618 if ( $newValue === false && !$this->getLastError() ) {
619 // Raced out initializing; increment
620 $newValue = $this->incr( $key, $value );
621 }
622 }
623
624 return $newValue;
625 }
626
627 /**
628 * Get the "last error" registered; clearLastError() should be called manually
629 * @return int ERR_* constant for the "last error" registry
630 * @since 1.23
631 */
632 public function getLastError() {
633 return $this->lastError;
634 }
635
636 /**
637 * Clear the "last error" registry
638 * @since 1.23
639 */
640 public function clearLastError() {
641 $this->lastError = self::ERR_NONE;
642 }
643
644 /**
645 * Set the "last error" registry
646 * @param int $err ERR_* constant
647 * @since 1.23
648 */
649 protected function setLastError( $err ) {
650 $this->lastError = $err;
651 }
652
653 /**
654 * Let a callback be run to avoid wasting time on special blocking calls
655 *
656 * The callbacks may or may not be called ever, in any particular order.
657 * They are likely to be invoked when something WRITE_SYNC is used used.
658 * They should follow a caching pattern as shown below, so that any code
659 * using the work will get it's result no matter what happens.
660 * @code
661 * $result = null;
662 * $workCallback = function () use ( &$result ) {
663 * if ( !$result ) {
664 * $result = ....
665 * }
666 * return $result;
667 * }
668 * @endcode
669 *
670 * @param callable $workCallback
671 * @since 1.28
672 */
673 public function addBusyCallback( callable $workCallback ) {
674 $this->busyCallbacks[] = $workCallback;
675 }
676
677 /**
678 * @param string $text
679 */
680 protected function debug( $text ) {
681 if ( $this->debugMode ) {
682 $this->logger->debug( "{class} debug: $text", [
683 'class' => static::class,
684 ] );
685 }
686 }
687
688 /**
689 * @param int $exptime
690 * @return bool
691 */
692 protected function expiryIsRelative( $exptime ) {
693 return ( $exptime != 0 && $exptime < ( 10 * self::TTL_YEAR ) );
694 }
695
696 /**
697 * Convert an optionally relative time to an absolute time
698 * @param int $exptime
699 * @return int
700 */
701 protected function convertToExpiry( $exptime ) {
702 if ( $this->expiryIsRelative( $exptime ) ) {
703 return (int)$this->getCurrentTime() + $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 -= (int)$this->getCurrentTime();
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 $key .= ':' . str_replace( ':', '%3A', $arg );
750 }
751 return strtr( $key, ' ', '_' );
752 }
753
754 /**
755 * Make a global cache key.
756 *
757 * @since 1.27
758 * @param string $class Key class
759 * @param string|null $component [optional] Key component (starting with a key collection name)
760 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
761 */
762 public function makeGlobalKey( $class, $component = null ) {
763 return $this->makeKeyInternal( 'global', func_get_args() );
764 }
765
766 /**
767 * Make a cache key, scoped to this instance's keyspace.
768 *
769 * @since 1.27
770 * @param string $class Key class
771 * @param string|null $component [optional] Key component (starting with a key collection name)
772 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
773 */
774 public function makeKey( $class, $component = null ) {
775 return $this->makeKeyInternal( $this->keyspace, func_get_args() );
776 }
777
778 /**
779 * @param int $flag ATTR_* class constant
780 * @return int QOS_* class constant
781 * @since 1.28
782 */
783 public function getQoS( $flag ) {
784 return $this->attrMap[$flag] ?? self::QOS_UNKNOWN;
785 }
786
787 /**
788 * Merge the flag maps of one or more BagOStuff objects into a "lowest common denominator" map
789 *
790 * @param BagOStuff[] $bags
791 * @return int[] Resulting flag map (class ATTR_* constant => class QOS_* constant)
792 */
793 protected function mergeFlagMaps( array $bags ) {
794 $map = [];
795 foreach ( $bags as $bag ) {
796 foreach ( $bag->attrMap as $attr => $rank ) {
797 if ( isset( $map[$attr] ) ) {
798 $map[$attr] = min( $map[$attr], $rank );
799 } else {
800 $map[$attr] = $rank;
801 }
802 }
803 }
804
805 return $map;
806 }
807
808 /**
809 * @return float UNIX timestamp
810 * @codeCoverageIgnore
811 */
812 protected function getCurrentTime() {
813 return $this->wallClockOverride ?: microtime( true );
814 }
815
816 /**
817 * @param float|null &$time Mock UNIX timestamp for testing
818 * @codeCoverageIgnore
819 */
820 public function setMockTime( &$time ) {
821 $this->wallClockOverride =& $time;
822 }
823 }