objectcache: improve logging and error handling in BagOStuff
[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 callback|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 if ( isset( $params['logger'] ) ) {
116 $this->setLogger( $params['logger'] );
117 } else {
118 $this->setLogger( new NullLogger() );
119 }
120
121 if ( isset( $params['keyspace'] ) ) {
122 $this->keyspace = $params['keyspace'];
123 }
124
125 $this->asyncHandler = $params['asyncHandler'] ?? null;
126
127 if ( !empty( $params['reportDupes'] ) && is_callable( $this->asyncHandler ) ) {
128 $this->reportDupes = true;
129 }
130
131 $this->syncTimeout = $params['syncTimeout'] ?? 3;
132 }
133
134 /**
135 * @param LoggerInterface $logger
136 * @return void
137 */
138 public function setLogger( LoggerInterface $logger ) {
139 $this->logger = $logger;
140 }
141
142 /**
143 * @param bool $bool
144 */
145 public function setDebug( $bool ) {
146 $this->debugMode = $bool;
147 }
148
149 /**
150 * Get an item with the given key, regenerating and setting it if not found
151 *
152 * If the callback returns false, then nothing is stored.
153 *
154 * @param string $key
155 * @param int $ttl Time-to-live (seconds)
156 * @param callable $callback Callback that derives the new value
157 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
158 * @return mixed The cached value if found or the result of $callback otherwise
159 * @since 1.27
160 */
161 final public function getWithSetCallback( $key, $ttl, $callback, $flags = 0 ) {
162 $value = $this->get( $key, $flags );
163
164 if ( $value === false ) {
165 if ( !is_callable( $callback ) ) {
166 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
167 }
168 $value = call_user_func( $callback );
169 if ( $value !== false ) {
170 $this->set( $key, $value, $ttl );
171 }
172 }
173
174 return $value;
175 }
176
177 /**
178 * Get an item with the given key
179 *
180 * If the key includes a deterministic input hash (e.g. the key can only have
181 * the correct value) or complete staleness checks are handled by the caller
182 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
183 * This lets tiered backends know they can safely upgrade a cached value to
184 * higher tiers using standard TTLs.
185 *
186 * @param string $key
187 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
188 * @param int|null $oldFlags [unused]
189 * @return mixed Returns false on failure and if the item does not exist
190 */
191 public function get( $key, $flags = 0, $oldFlags = null ) {
192 // B/C for ( $key, &$casToken = null, $flags = 0 )
193 $flags = is_int( $oldFlags ) ? $oldFlags : $flags;
194
195 $this->trackDuplicateKeys( $key );
196
197 return $this->doGet( $key, $flags );
198 }
199
200 /**
201 * Track the number of times that a given key has been used.
202 * @param string $key
203 */
204 private function trackDuplicateKeys( $key ) {
205 if ( !$this->reportDupes ) {
206 return;
207 }
208
209 if ( !isset( $this->duplicateKeyLookups[$key] ) ) {
210 // Track that we have seen this key. This N-1 counting style allows
211 // easy filtering with array_filter() later.
212 $this->duplicateKeyLookups[$key] = 0;
213 } else {
214 $this->duplicateKeyLookups[$key] += 1;
215
216 if ( $this->dupeTrackScheduled === false ) {
217 $this->dupeTrackScheduled = true;
218 // Schedule a callback that logs keys processed more than once by get().
219 call_user_func( $this->asyncHandler, function () {
220 $dups = array_filter( $this->duplicateKeyLookups );
221 foreach ( $dups as $key => $count ) {
222 $this->logger->warning(
223 'Duplicate get(): "{key}" fetched {count} times',
224 // Count is N-1 of the actual lookup count
225 [ 'key' => $key, 'count' => $count + 1, ]
226 );
227 }
228 } );
229 }
230 }
231 }
232
233 /**
234 * @param string $key
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 */
238 abstract protected function doGet( $key, $flags = 0 );
239
240 /**
241 * @note: This method is only needed if merge() uses mergeViaCas()
242 *
243 * @param string $key
244 * @param mixed &$casToken
245 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
246 * @return mixed Returns false on failure and if the item does not exist
247 * @throws Exception
248 */
249 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
250 throw new Exception( __METHOD__ . ' not implemented.' );
251 }
252
253 /**
254 * Set an item
255 *
256 * @param string $key
257 * @param mixed $value
258 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
259 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
260 * @return bool Success
261 */
262 abstract public function set( $key, $value, $exptime = 0, $flags = 0 );
263
264 /**
265 * Delete an item
266 *
267 * @param string $key
268 * @return bool True if the item was deleted or not found, false on failure
269 */
270 abstract public function delete( $key );
271
272 /**
273 * Merge changes into the existing cache value (possibly creating a new one)
274 *
275 * The callback function returns the new value given the current value
276 * (which will be false if not present), and takes the arguments:
277 * (this BagOStuff, cache key, current value, TTL).
278 * The TTL parameter is reference set to $exptime. It can be overriden in the callback.
279 *
280 * @param string $key
281 * @param callable $callback Callback method to be executed
282 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
283 * @param int $attempts The amount of times to attempt a merge in case of failure
284 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
285 * @return bool Success
286 * @throws InvalidArgumentException
287 */
288 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
289 return $this->mergeViaLock( $key, $callback, $exptime, $attempts, $flags );
290 }
291
292 /**
293 * @see BagOStuff::merge()
294 *
295 * @param string $key
296 * @param callable $callback Callback method to be executed
297 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
298 * @param int $attempts The amount of times to attempt a merge in case of failure
299 * @return bool Success
300 */
301 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
302 do {
303 $this->clearLastError();
304 $reportDupes = $this->reportDupes;
305 $this->reportDupes = false;
306 $casToken = null; // passed by reference
307 $currentValue = $this->getWithToken( $key, $casToken, self::READ_LATEST );
308 $this->reportDupes = $reportDupes;
309
310 if ( $this->getLastError() ) {
311 $this->logger->warning(
312 __METHOD__ . ' failed due to I/O error on get() for {key}.',
313 [ 'key' => $key ]
314 );
315
316 return false; // don't spam retries (retry only on races)
317 }
318
319 // Derive the new value from the old value
320 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
321
322 $this->clearLastError();
323 if ( $value === false ) {
324 $success = true; // do nothing
325 } elseif ( $currentValue === false ) {
326 // Try to create the key, failing if it gets created in the meantime
327 $success = $this->add( $key, $value, $exptime );
328 } else {
329 // Try to update the key, failing if it gets changed in the meantime
330 $success = $this->cas( $casToken, $key, $value, $exptime );
331 }
332 if ( $this->getLastError() ) {
333 $this->logger->warning(
334 __METHOD__ . ' failed due to I/O error for {key}.',
335 [ 'key' => $key ]
336 );
337
338 return false; // IO error; don't spam retries
339 }
340 } while ( !$success && --$attempts );
341
342 return $success;
343 }
344
345 /**
346 * Check and set an item
347 *
348 * @param mixed $casToken
349 * @param string $key
350 * @param mixed $value
351 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
352 * @return bool Success
353 * @throws Exception
354 */
355 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
356 if ( !$this->lock( $key, 0 ) ) {
357 return false; // non-blocking
358 }
359
360 $curCasToken = null; // passed by reference
361 $this->getWithToken( $key, $curCasToken, self::READ_LATEST );
362 if ( $casToken === $curCasToken ) {
363 $success = $this->set( $key, $value, $exptime );
364 } else {
365 $this->logger->info(
366 __METHOD__ . ' failed due to race condition for {key}.',
367 [ 'key' => $key ]
368 );
369
370 $success = false; // mismatched or failed
371 }
372
373 $this->unlock( $key );
374
375 return $success;
376 }
377
378 /**
379 * @see BagOStuff::merge()
380 *
381 * @param string $key
382 * @param callable $callback Callback method to be executed
383 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
384 * @param int $attempts The amount of times to attempt a merge in case of failure
385 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
386 * @return bool Success
387 */
388 protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
389 if ( !$this->lock( $key, 6 ) ) {
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 * Reset the TTL on a key if it exists
426 *
427 * @param string $key
428 * @param int $expiry
429 * @return bool Success Returns false if there is no key
430 * @since 1.28
431 */
432 public function changeTTL( $key, $expiry = 0 ) {
433 $value = $this->get( $key );
434
435 return ( $value === false ) ? false : $this->set( $key, $value, $expiry );
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, $timeout, $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 array $keys List of strings
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 );
582 if ( $val !== false ) {
583 $res[$key] = $val;
584 }
585 }
586 return $res;
587 }
588
589 /**
590 * Batch insertion
591 * @param array $data $key => $value assoc array
592 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
593 * @return bool Success
594 * @since 1.24
595 */
596 public function setMulti( array $data, $exptime = 0 ) {
597 $res = true;
598 foreach ( $data as $key => $value ) {
599 if ( !$this->set( $key, $value, $exptime ) ) {
600 $res = false;
601 }
602 }
603 return $res;
604 }
605
606 /**
607 * @param string $key
608 * @param mixed $value
609 * @param int $exptime
610 * @return bool Success
611 */
612 public function add( $key, $value, $exptime = 0 ) {
613 // @note: avoid lock() here since that method uses *this* method by default
614 if ( $this->get( $key ) === false ) {
615 return $this->set( $key, $value, $exptime );
616 }
617 return false; // key already set
618 }
619
620 /**
621 * Increase stored value of $key by $value while preserving its TTL
622 * @param string $key Key to increase
623 * @param int $value Value to add to $key (Default 1)
624 * @return int|bool New value or false on failure
625 */
626 public function incr( $key, $value = 1 ) {
627 if ( !$this->lock( $key, 1 ) ) {
628 return false;
629 }
630 $n = $this->get( $key );
631 if ( $this->isInteger( $n ) ) { // key exists?
632 $n += intval( $value );
633 $this->set( $key, max( 0, $n ) ); // exptime?
634 } else {
635 $n = false;
636 }
637 $this->unlock( $key );
638
639 return $n;
640 }
641
642 /**
643 * Decrease stored value of $key by $value while preserving its TTL
644 * @param string $key
645 * @param int $value
646 * @return int|bool New value or false on failure
647 */
648 public function decr( $key, $value = 1 ) {
649 return $this->incr( $key, - $value );
650 }
651
652 /**
653 * Increase stored value of $key by $value while preserving its TTL
654 *
655 * This will create the key with value $init and TTL $ttl instead if not present
656 *
657 * @param string $key
658 * @param int $ttl
659 * @param int $value
660 * @param int $init
661 * @return int|bool New value or false on failure
662 * @since 1.24
663 */
664 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
665 $this->clearLastError();
666 $newValue = $this->incr( $key, $value );
667 if ( $newValue === false && !$this->getLastError() ) {
668 // No key set; initialize
669 $newValue = $this->add( $key, (int)$init, $ttl ) ? $init : false;
670 if ( $newValue === false && !$this->getLastError() ) {
671 // Raced out initializing; increment
672 $newValue = $this->incr( $key, $value );
673 }
674 }
675
676 return $newValue;
677 }
678
679 /**
680 * Get the "last error" registered; clearLastError() should be called manually
681 * @return int ERR_* constant for the "last error" registry
682 * @since 1.23
683 */
684 public function getLastError() {
685 return $this->lastError;
686 }
687
688 /**
689 * Clear the "last error" registry
690 * @since 1.23
691 */
692 public function clearLastError() {
693 $this->lastError = self::ERR_NONE;
694 }
695
696 /**
697 * Set the "last error" registry
698 * @param int $err ERR_* constant
699 * @since 1.23
700 */
701 protected function setLastError( $err ) {
702 $this->lastError = $err;
703 }
704
705 /**
706 * Let a callback be run to avoid wasting time on special blocking calls
707 *
708 * The callbacks may or may not be called ever, in any particular order.
709 * They are likely to be invoked when something WRITE_SYNC is used used.
710 * They should follow a caching pattern as shown below, so that any code
711 * using the word will get it's result no matter what happens.
712 * @code
713 * $result = null;
714 * $workCallback = function () use ( &$result ) {
715 * if ( !$result ) {
716 * $result = ....
717 * }
718 * return $result;
719 * }
720 * @endcode
721 *
722 * @param callable $workCallback
723 * @since 1.28
724 */
725 public function addBusyCallback( callable $workCallback ) {
726 $this->busyCallbacks[] = $workCallback;
727 }
728
729 /**
730 * Modify a cache update operation array for EventRelayer::notify()
731 *
732 * This is used for relayed writes, e.g. for broadcasting a change
733 * to multiple data-centers. If the array contains a 'val' field
734 * then the command involves setting a key to that value. Note that
735 * for simplicity, 'val' is always a simple scalar value. This method
736 * is used to possibly serialize the value and add any cache-specific
737 * key/values needed for the relayer daemon (e.g. memcached flags).
738 *
739 * @param array $event
740 * @return array
741 * @since 1.26
742 */
743 public function modifySimpleRelayEvent( array $event ) {
744 return $event;
745 }
746
747 /**
748 * @param string $text
749 */
750 protected function debug( $text ) {
751 if ( $this->debugMode ) {
752 $this->logger->debug( "{class} debug: $text", [
753 'class' => static::class,
754 ] );
755 }
756 }
757
758 /**
759 * Convert an optionally relative time to an absolute time
760 * @param int $exptime
761 * @return int
762 */
763 protected function convertExpiry( $exptime ) {
764 if ( $exptime != 0 && $exptime < ( 10 * self::TTL_YEAR ) ) {
765 return (int)$this->getCurrentTime() + $exptime;
766 } else {
767 return $exptime;
768 }
769 }
770
771 /**
772 * Convert an optionally absolute expiry time to a relative time. If an
773 * absolute time is specified which is in the past, use a short expiry time.
774 *
775 * @param int $exptime
776 * @return int
777 */
778 protected function convertToRelative( $exptime ) {
779 if ( $exptime >= ( 10 * self::TTL_YEAR ) ) {
780 $exptime -= (int)$this->getCurrentTime();
781 if ( $exptime <= 0 ) {
782 $exptime = 1;
783 }
784 return $exptime;
785 } else {
786 return $exptime;
787 }
788 }
789
790 /**
791 * Check if a value is an integer
792 *
793 * @param mixed $value
794 * @return bool
795 */
796 protected function isInteger( $value ) {
797 return ( is_int( $value ) || ctype_digit( $value ) );
798 }
799
800 /**
801 * Construct a cache key.
802 *
803 * @since 1.27
804 * @param string $keyspace
805 * @param array $args
806 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
807 */
808 public function makeKeyInternal( $keyspace, $args ) {
809 $key = $keyspace;
810 foreach ( $args as $arg ) {
811 $arg = str_replace( ':', '%3A', $arg );
812 $key = $key . ':' . $arg;
813 }
814 return strtr( $key, ' ', '_' );
815 }
816
817 /**
818 * Make a global cache key.
819 *
820 * @since 1.27
821 * @param string $class Key class
822 * @param string|null $component [optional] Key component (starting with a key collection name)
823 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
824 */
825 public function makeGlobalKey( $class, $component = null ) {
826 return $this->makeKeyInternal( 'global', func_get_args() );
827 }
828
829 /**
830 * Make a cache key, scoped to this instance's keyspace.
831 *
832 * @since 1.27
833 * @param string $class Key class
834 * @param string|null $component [optional] Key component (starting with a key collection name)
835 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
836 */
837 public function makeKey( $class, $component = null ) {
838 return $this->makeKeyInternal( $this->keyspace, func_get_args() );
839 }
840
841 /**
842 * @param int $flag ATTR_* class constant
843 * @return int QOS_* class constant
844 * @since 1.28
845 */
846 public function getQoS( $flag ) {
847 return $this->attrMap[$flag] ?? self::QOS_UNKNOWN;
848 }
849
850 /**
851 * Merge the flag maps of one or more BagOStuff objects into a "lowest common denominator" map
852 *
853 * @param BagOStuff[] $bags
854 * @return int[] Resulting flag map (class ATTR_* constant => class QOS_* constant)
855 */
856 protected function mergeFlagMaps( array $bags ) {
857 $map = [];
858 foreach ( $bags as $bag ) {
859 foreach ( $bag->attrMap as $attr => $rank ) {
860 if ( isset( $map[$attr] ) ) {
861 $map[$attr] = min( $map[$attr], $rank );
862 } else {
863 $map[$attr] = $rank;
864 }
865 }
866 }
867
868 return $map;
869 }
870
871 /**
872 * @return float UNIX timestamp
873 * @codeCoverageIgnore
874 */
875 protected function getCurrentTime() {
876 return $this->wallClockOverride ?: microtime( true );
877 }
878
879 /**
880 * @param float|null &$time Mock UNIX timestamp for testing
881 * @codeCoverageIgnore
882 */
883 public function setMockTime( &$time ) {
884 $this->wallClockOverride =& $time;
885 }
886 }