Merge "Remove array_unique() on expected classes in checkAutoLoadConf()"
[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 /** Possible values for getLastError() */
91 const ERR_NONE = 0; // no error
92 const ERR_NO_RESPONSE = 1; // no response
93 const ERR_UNREACHABLE = 2; // can't connect
94 const ERR_UNEXPECTED = 3; // response gave some error
95
96 /** Bitfield constants for get()/getMulti() */
97 const READ_LATEST = 1; // use latest data for replicated stores
98 const READ_VERIFIED = 2; // promise that caller can tell when keys are stale
99 /** Bitfield constants for set()/merge() */
100 const WRITE_SYNC = 1; // synchronously write to all locations for replicated stores
101 const WRITE_CACHE_ONLY = 2; // Only change state of the in-memory cache
102
103 /**
104 * $params include:
105 * - logger: Psr\Log\LoggerInterface instance
106 * - keyspace: Default keyspace for $this->makeKey()
107 * - asyncHandler: Callable to use for scheduling tasks after the web request ends.
108 * In CLI mode, it should run the task immediately.
109 * - reportDupes: Whether to emit warning log messages for all keys that were
110 * requested more than once (requires an asyncHandler).
111 * - syncTimeout: How long to wait with WRITE_SYNC in seconds.
112 * @param array $params
113 */
114 public function __construct( array $params = [] ) {
115 $this->setLogger( $params['logger'] ?? new NullLogger() );
116
117 if ( isset( $params['keyspace'] ) ) {
118 $this->keyspace = $params['keyspace'];
119 }
120
121 $this->asyncHandler = $params['asyncHandler'] ?? null;
122
123 if ( !empty( $params['reportDupes'] ) && is_callable( $this->asyncHandler ) ) {
124 $this->reportDupes = true;
125 }
126
127 $this->syncTimeout = $params['syncTimeout'] ?? 3;
128 }
129
130 /**
131 * @param LoggerInterface $logger
132 * @return void
133 */
134 public function setLogger( LoggerInterface $logger ) {
135 $this->logger = $logger;
136 }
137
138 /**
139 * @param bool $bool
140 */
141 public function setDebug( $bool ) {
142 $this->debugMode = $bool;
143 }
144
145 /**
146 * Get an item with the given key, regenerating and setting it if not found
147 *
148 * If the callback returns false, then nothing is stored.
149 *
150 * @param string $key
151 * @param int $ttl Time-to-live (seconds)
152 * @param callable $callback Callback that derives the new value
153 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
154 * @return mixed The cached value if found or the result of $callback otherwise
155 * @since 1.27
156 */
157 final public function getWithSetCallback( $key, $ttl, $callback, $flags = 0 ) {
158 $value = $this->get( $key, $flags );
159
160 if ( $value === false ) {
161 if ( !is_callable( $callback ) ) {
162 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
163 }
164 $value = call_user_func( $callback );
165 if ( $value !== false ) {
166 $this->set( $key, $value, $ttl );
167 }
168 }
169
170 return $value;
171 }
172
173 /**
174 * Get an item with the given key
175 *
176 * If the key includes a deterministic input hash (e.g. the key can only have
177 * the correct value) or complete staleness checks are handled by the caller
178 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
179 * This lets tiered backends know they can safely upgrade a cached value to
180 * higher tiers using standard TTLs.
181 *
182 * @param string $key
183 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
184 * @param int|null $oldFlags [unused]
185 * @return mixed Returns false on failure and if the item does not exist
186 */
187 public function get( $key, $flags = 0, $oldFlags = null ) {
188 // B/C for ( $key, &$casToken = null, $flags = 0 )
189 $flags = is_int( $oldFlags ) ? $oldFlags : $flags;
190
191 $this->trackDuplicateKeys( $key );
192
193 return $this->doGet( $key, $flags );
194 }
195
196 /**
197 * Track the number of times that a given key has been used.
198 * @param string $key
199 */
200 private function trackDuplicateKeys( $key ) {
201 if ( !$this->reportDupes ) {
202 return;
203 }
204
205 if ( !isset( $this->duplicateKeyLookups[$key] ) ) {
206 // Track that we have seen this key. This N-1 counting style allows
207 // easy filtering with array_filter() later.
208 $this->duplicateKeyLookups[$key] = 0;
209 } else {
210 $this->duplicateKeyLookups[$key] += 1;
211
212 if ( $this->dupeTrackScheduled === false ) {
213 $this->dupeTrackScheduled = true;
214 // Schedule a callback that logs keys processed more than once by get().
215 call_user_func( $this->asyncHandler, function () {
216 $dups = array_filter( $this->duplicateKeyLookups );
217 foreach ( $dups as $key => $count ) {
218 $this->logger->warning(
219 'Duplicate get(): "{key}" fetched {count} times',
220 // Count is N-1 of the actual lookup count
221 [ 'key' => $key, 'count' => $count + 1, ]
222 );
223 }
224 } );
225 }
226 }
227 }
228
229 /**
230 * @param string $key
231 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
232 * @return mixed Returns false on failure and if the item does not exist
233 */
234 abstract protected function doGet( $key, $flags = 0 );
235
236 /**
237 * @note This method is only needed if merge() uses mergeViaCas()
238 *
239 * @param string $key
240 * @param mixed &$casToken
241 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
242 * @return mixed Returns false on failure and if the item does not exist
243 * @throws Exception
244 */
245 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
246 throw new Exception( __METHOD__ . ' not implemented.' );
247 }
248
249 /**
250 * Set an item
251 *
252 * @param string $key
253 * @param mixed $value
254 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
255 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
256 * @return bool Success
257 */
258 abstract public function set( $key, $value, $exptime = 0, $flags = 0 );
259
260 /**
261 * Delete an item
262 *
263 * @param string $key
264 * @return bool True if the item was deleted or not found, false on failure
265 */
266 abstract public function delete( $key );
267
268 /**
269 * Merge changes into the existing cache value (possibly creating a new one)
270 *
271 * The callback function returns the new value given the current value
272 * (which will be false if not present), and takes the arguments:
273 * (this BagOStuff, cache key, current value, TTL).
274 * The TTL parameter is reference set to $exptime. It can be overriden in the callback.
275 *
276 * @param string $key
277 * @param callable $callback Callback method to be executed
278 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
279 * @param int $attempts The amount of times to attempt a merge in case of failure
280 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
281 * @return bool Success
282 * @throws InvalidArgumentException
283 */
284 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
285 return $this->mergeViaLock( $key, $callback, $exptime, $attempts, $flags );
286 }
287
288 /**
289 * @see BagOStuff::merge()
290 *
291 * @param string $key
292 * @param callable $callback Callback method to be executed
293 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
294 * @param int $attempts The amount of times to attempt a merge in case of failure
295 * @return bool Success
296 */
297 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
298 do {
299 $this->clearLastError();
300 $reportDupes = $this->reportDupes;
301 $this->reportDupes = false;
302 $casToken = null; // passed by reference
303 $currentValue = $this->getWithToken( $key, $casToken, self::READ_LATEST );
304 $this->reportDupes = $reportDupes;
305
306 if ( $this->getLastError() ) {
307 $this->logger->warning(
308 __METHOD__ . ' failed due to I/O error on get() for {key}.',
309 [ 'key' => $key ]
310 );
311
312 return false; // don't spam retries (retry only on races)
313 }
314
315 // Derive the new value from the old value
316 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
317
318 $this->clearLastError();
319 if ( $value === false ) {
320 $success = true; // do nothing
321 } elseif ( $currentValue === false ) {
322 // Try to create the key, failing if it gets created in the meantime
323 $success = $this->add( $key, $value, $exptime );
324 } else {
325 // Try to update the key, failing if it gets changed in the meantime
326 $success = $this->cas( $casToken, $key, $value, $exptime );
327 }
328 if ( $this->getLastError() ) {
329 $this->logger->warning(
330 __METHOD__ . ' failed due to I/O error for {key}.',
331 [ 'key' => $key ]
332 );
333
334 return false; // IO error; don't spam retries
335 }
336 } while ( !$success && --$attempts );
337
338 return $success;
339 }
340
341 /**
342 * Check and set an item
343 *
344 * @param mixed $casToken
345 * @param string $key
346 * @param mixed $value
347 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
348 * @return bool Success
349 * @throws Exception
350 */
351 protected function cas( $casToken, $key, $value, $exptime = 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 );
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 * @see BagOStuff::merge()
376 *
377 * @param string $key
378 * @param callable $callback Callback method to be executed
379 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
380 * @param int $attempts The amount of times to attempt a merge in case of failure
381 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
382 * @return bool Success
383 */
384 protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
385 if ( $attempts <= 1 ) {
386 $timeout = 0; // clearly intended to be "non-blocking"
387 } else {
388 $timeout = 3;
389 }
390
391 if ( !$this->lock( $key, $timeout ) ) {
392 return false;
393 }
394
395 $this->clearLastError();
396 $reportDupes = $this->reportDupes;
397 $this->reportDupes = false;
398 $currentValue = $this->get( $key, self::READ_LATEST );
399 $this->reportDupes = $reportDupes;
400
401 if ( $this->getLastError() ) {
402 $this->logger->warning(
403 __METHOD__ . ' failed due to I/O error on get() for {key}.',
404 [ 'key' => $key ]
405 );
406
407 $success = false;
408 } else {
409 // Derive the new value from the old value
410 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
411 if ( $value === false ) {
412 $success = true; // do nothing
413 } else {
414 $success = $this->set( $key, $value, $exptime, $flags ); // set the new value
415 }
416 }
417
418 if ( !$this->unlock( $key ) ) {
419 // this should never happen
420 trigger_error( "Could not release lock for key '$key'." );
421 }
422
423 return $success;
424 }
425
426 /**
427 * Reset the TTL on a key if it exists
428 *
429 * @param string $key
430 * @param int $expiry
431 * @return bool Success Returns false if there is no key
432 * @since 1.28
433 */
434 public function changeTTL( $key, $expiry = 0 ) {
435 $value = $this->get( $key );
436
437 return ( $value === false ) ? false : $this->set( $key, $value, $expiry );
438 }
439
440 /**
441 * Acquire an advisory lock on a key string
442 *
443 * Note that if reentry is enabled, duplicate calls ignore $expiry
444 *
445 * @param string $key
446 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
447 * @param int $expiry Lock expiry [optional]; 1 day maximum
448 * @param string $rclass Allow reentry if set and the current lock used this value
449 * @return bool Success
450 */
451 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
452 // Avoid deadlocks and allow lock reentry if specified
453 if ( isset( $this->locks[$key] ) ) {
454 if ( $rclass != '' && $this->locks[$key]['class'] === $rclass ) {
455 ++$this->locks[$key]['depth'];
456 return true;
457 } else {
458 return false;
459 }
460 }
461
462 $fname = __METHOD__;
463 $expiry = min( $expiry ?: INF, self::TTL_DAY );
464 $loop = new WaitConditionLoop(
465 function () use ( $key, $expiry, $fname ) {
466 $this->clearLastError();
467 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
468 return true; // locked!
469 } elseif ( $this->getLastError() ) {
470 $this->logger->warning(
471 $fname . ' failed due to I/O error for {key}.',
472 [ 'key' => $key ]
473 );
474
475 return WaitConditionLoop::CONDITION_ABORTED; // network partition?
476 }
477
478 return WaitConditionLoop::CONDITION_CONTINUE;
479 },
480 $timeout
481 );
482
483 $code = $loop->invoke();
484 $locked = ( $code === $loop::CONDITION_REACHED );
485 if ( $locked ) {
486 $this->locks[$key] = [ 'class' => $rclass, 'depth' => 1 ];
487 } elseif ( $code === $loop::CONDITION_TIMED_OUT ) {
488 $this->logger->warning(
489 "$fname failed due to timeout for {key}.",
490 [ 'key' => $key, 'timeout' => $timeout ]
491 );
492 }
493
494 return $locked;
495 }
496
497 /**
498 * Release an advisory lock on a key string
499 *
500 * @param string $key
501 * @return bool Success
502 */
503 public function unlock( $key ) {
504 if ( isset( $this->locks[$key] ) && --$this->locks[$key]['depth'] <= 0 ) {
505 unset( $this->locks[$key] );
506
507 $ok = $this->delete( "{$key}:lock" );
508 if ( !$ok ) {
509 $this->logger->warning(
510 __METHOD__ . ' failed to release lock for {key}.',
511 [ 'key' => $key ]
512 );
513 }
514
515 return $ok;
516 }
517
518 return true;
519 }
520
521 /**
522 * Get a lightweight exclusive self-unlocking lock
523 *
524 * Note that the same lock cannot be acquired twice.
525 *
526 * This is useful for task de-duplication or to avoid obtrusive
527 * (though non-corrupting) DB errors like INSERT key conflicts
528 * or deadlocks when using LOCK IN SHARE MODE.
529 *
530 * @param string $key
531 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
532 * @param int $expiry Lock expiry [optional]; 1 day maximum
533 * @param string $rclass Allow reentry if set and the current lock used this value
534 * @return ScopedCallback|null Returns null on failure
535 * @since 1.26
536 */
537 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
538 $expiry = min( $expiry ?: INF, self::TTL_DAY );
539
540 if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
541 return null;
542 }
543
544 $lSince = $this->getCurrentTime(); // lock timestamp
545
546 return new ScopedCallback( function () use ( $key, $lSince, $expiry ) {
547 $latency = 0.050; // latency skew (err towards keeping lock present)
548 $age = ( $this->getCurrentTime() - $lSince + $latency );
549 if ( ( $age + $latency ) >= $expiry ) {
550 $this->logger->warning(
551 "Lock for {key} held too long ({age} sec).",
552 [ 'key' => $key, 'age' => $age ]
553 );
554 return; // expired; it's not "safe" to delete the key
555 }
556 $this->unlock( $key );
557 } );
558 }
559
560 /**
561 * Delete all objects expiring before a certain date.
562 * @param string $date The reference date in MW format
563 * @param callable|bool $progressCallback Optional, a function which will be called
564 * regularly during long-running operations with the percentage progress
565 * as the first parameter.
566 *
567 * @return bool Success, false if unimplemented
568 */
569 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
570 // stub
571 return false;
572 }
573
574 /**
575 * Get an associative array containing the item for each of the keys that have items.
576 * @param array $keys List of strings
577 * @param int $flags Bitfield; supports READ_LATEST [optional]
578 * @return array
579 */
580 public function getMulti( array $keys, $flags = 0 ) {
581 $res = [];
582 foreach ( $keys as $key ) {
583 $val = $this->get( $key );
584 if ( $val !== false ) {
585 $res[$key] = $val;
586 }
587 }
588 return $res;
589 }
590
591 /**
592 * Batch insertion
593 * @param array $data $key => $value assoc array
594 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
595 * @return bool Success
596 * @since 1.24
597 */
598 public function setMulti( array $data, $exptime = 0 ) {
599 $res = true;
600 foreach ( $data as $key => $value ) {
601 if ( !$this->set( $key, $value, $exptime ) ) {
602 $res = false;
603 }
604 }
605 return $res;
606 }
607
608 /**
609 * @param string $key
610 * @param mixed $value
611 * @param int $exptime
612 * @return bool Success
613 */
614 public function add( $key, $value, $exptime = 0 ) {
615 // @note: avoid lock() here since that method uses *this* method by default
616 if ( $this->get( $key ) === false ) {
617 return $this->set( $key, $value, $exptime );
618 }
619 return false; // key already set
620 }
621
622 /**
623 * Increase stored value of $key by $value while preserving its TTL
624 * @param string $key Key to increase
625 * @param int $value Value to add to $key (Default 1)
626 * @return int|bool New value or false on failure
627 */
628 public function incr( $key, $value = 1 ) {
629 if ( !$this->lock( $key, 1 ) ) {
630 return false;
631 }
632 $n = $this->get( $key );
633 if ( $this->isInteger( $n ) ) { // key exists?
634 $n += intval( $value );
635 $this->set( $key, max( 0, $n ) ); // exptime?
636 } else {
637 $n = false;
638 }
639 $this->unlock( $key );
640
641 return $n;
642 }
643
644 /**
645 * Decrease stored value of $key by $value while preserving its TTL
646 * @param string $key
647 * @param int $value
648 * @return int|bool New value or false on failure
649 */
650 public function decr( $key, $value = 1 ) {
651 return $this->incr( $key, - $value );
652 }
653
654 /**
655 * Increase stored value of $key by $value while preserving its TTL
656 *
657 * This will create the key with value $init and TTL $ttl instead if not present
658 *
659 * @param string $key
660 * @param int $ttl
661 * @param int $value
662 * @param int $init
663 * @return int|bool New value or false on failure
664 * @since 1.24
665 */
666 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
667 $this->clearLastError();
668 $newValue = $this->incr( $key, $value );
669 if ( $newValue === false && !$this->getLastError() ) {
670 // No key set; initialize
671 $newValue = $this->add( $key, (int)$init, $ttl ) ? $init : false;
672 if ( $newValue === false && !$this->getLastError() ) {
673 // Raced out initializing; increment
674 $newValue = $this->incr( $key, $value );
675 }
676 }
677
678 return $newValue;
679 }
680
681 /**
682 * Get the "last error" registered; clearLastError() should be called manually
683 * @return int ERR_* constant for the "last error" registry
684 * @since 1.23
685 */
686 public function getLastError() {
687 return $this->lastError;
688 }
689
690 /**
691 * Clear the "last error" registry
692 * @since 1.23
693 */
694 public function clearLastError() {
695 $this->lastError = self::ERR_NONE;
696 }
697
698 /**
699 * Set the "last error" registry
700 * @param int $err ERR_* constant
701 * @since 1.23
702 */
703 protected function setLastError( $err ) {
704 $this->lastError = $err;
705 }
706
707 /**
708 * Let a callback be run to avoid wasting time on special blocking calls
709 *
710 * The callbacks may or may not be called ever, in any particular order.
711 * They are likely to be invoked when something WRITE_SYNC is used used.
712 * They should follow a caching pattern as shown below, so that any code
713 * using the word will get it's result no matter what happens.
714 * @code
715 * $result = null;
716 * $workCallback = function () use ( &$result ) {
717 * if ( !$result ) {
718 * $result = ....
719 * }
720 * return $result;
721 * }
722 * @endcode
723 *
724 * @param callable $workCallback
725 * @since 1.28
726 */
727 public function addBusyCallback( callable $workCallback ) {
728 $this->busyCallbacks[] = $workCallback;
729 }
730
731 /**
732 * Modify a cache update operation array for EventRelayer::notify()
733 *
734 * This is used for relayed writes, e.g. for broadcasting a change
735 * to multiple data-centers. If the array contains a 'val' field
736 * then the command involves setting a key to that value. Note that
737 * for simplicity, 'val' is always a simple scalar value. This method
738 * is used to possibly serialize the value and add any cache-specific
739 * key/values needed for the relayer daemon (e.g. memcached flags).
740 *
741 * @param array $event
742 * @return array
743 * @since 1.26
744 */
745 public function modifySimpleRelayEvent( array $event ) {
746 return $event;
747 }
748
749 /**
750 * @param string $text
751 */
752 protected function debug( $text ) {
753 if ( $this->debugMode ) {
754 $this->logger->debug( "{class} debug: $text", [
755 'class' => static::class,
756 ] );
757 }
758 }
759
760 /**
761 * Convert an optionally relative time to an absolute time
762 * @param int $exptime
763 * @return int
764 */
765 protected function convertExpiry( $exptime ) {
766 if ( $exptime != 0 && $exptime < ( 10 * self::TTL_YEAR ) ) {
767 return (int)$this->getCurrentTime() + $exptime;
768 } else {
769 return $exptime;
770 }
771 }
772
773 /**
774 * Convert an optionally absolute expiry time to a relative time. If an
775 * absolute time is specified which is in the past, use a short expiry time.
776 *
777 * @param int $exptime
778 * @return int
779 */
780 protected function convertToRelative( $exptime ) {
781 if ( $exptime >= ( 10 * self::TTL_YEAR ) ) {
782 $exptime -= (int)$this->getCurrentTime();
783 if ( $exptime <= 0 ) {
784 $exptime = 1;
785 }
786 return $exptime;
787 } else {
788 return $exptime;
789 }
790 }
791
792 /**
793 * Check if a value is an integer
794 *
795 * @param mixed $value
796 * @return bool
797 */
798 protected function isInteger( $value ) {
799 return ( is_int( $value ) || ctype_digit( $value ) );
800 }
801
802 /**
803 * Construct a cache key.
804 *
805 * @since 1.27
806 * @param string $keyspace
807 * @param array $args
808 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
809 */
810 public function makeKeyInternal( $keyspace, $args ) {
811 $key = $keyspace;
812 foreach ( $args as $arg ) {
813 $arg = str_replace( ':', '%3A', $arg );
814 $key = $key . ':' . $arg;
815 }
816 return strtr( $key, ' ', '_' );
817 }
818
819 /**
820 * Make a global cache key.
821 *
822 * @since 1.27
823 * @param string $class Key class
824 * @param string|null $component [optional] Key component (starting with a key collection name)
825 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
826 */
827 public function makeGlobalKey( $class, $component = null ) {
828 return $this->makeKeyInternal( 'global', func_get_args() );
829 }
830
831 /**
832 * Make a cache key, scoped to this instance's keyspace.
833 *
834 * @since 1.27
835 * @param string $class Key class
836 * @param string|null $component [optional] Key component (starting with a key collection name)
837 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
838 */
839 public function makeKey( $class, $component = null ) {
840 return $this->makeKeyInternal( $this->keyspace, func_get_args() );
841 }
842
843 /**
844 * @param int $flag ATTR_* class constant
845 * @return int QOS_* class constant
846 * @since 1.28
847 */
848 public function getQoS( $flag ) {
849 return $this->attrMap[$flag] ?? self::QOS_UNKNOWN;
850 }
851
852 /**
853 * Merge the flag maps of one or more BagOStuff objects into a "lowest common denominator" map
854 *
855 * @param BagOStuff[] $bags
856 * @return int[] Resulting flag map (class ATTR_* constant => class QOS_* constant)
857 */
858 protected function mergeFlagMaps( array $bags ) {
859 $map = [];
860 foreach ( $bags as $bag ) {
861 foreach ( $bag->attrMap as $attr => $rank ) {
862 if ( isset( $map[$attr] ) ) {
863 $map[$attr] = min( $map[$attr], $rank );
864 } else {
865 $map[$attr] = $rank;
866 }
867 }
868 }
869
870 return $map;
871 }
872
873 /**
874 * @return float UNIX timestamp
875 * @codeCoverageIgnore
876 */
877 protected function getCurrentTime() {
878 return $this->wallClockOverride ?: microtime( true );
879 }
880
881 /**
882 * @param float|null &$time Mock UNIX timestamp for testing
883 * @codeCoverageIgnore
884 */
885 public function setMockTime( &$time ) {
886 $this->wallClockOverride =& $time;
887 }
888 }