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