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