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