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