Merge "Override momentjs's digit transform logic with MW's"
[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
33 /**
34 * interface is intended to be more or less compatible with
35 * the PHP memcached client.
36 *
37 * backends for local hash array and SQL table included:
38 * @code
39 * $bag = new HashBagOStuff();
40 * $bag = new SqlBagOStuff(); # connect to db first
41 * @endcode
42 *
43 * @ingroup Cache
44 */
45 abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface {
46 /** @var array[] Lock tracking */
47 protected $locks = [];
48
49 /** @var integer */
50 protected $lastError = self::ERR_NONE;
51
52 /** @var string */
53 protected $keyspace = 'local';
54
55 /** @var LoggerInterface */
56 protected $logger;
57
58 /** @var callback|null */
59 protected $asyncHandler;
60
61 /** @var bool */
62 private $debugMode = false;
63
64 /** @var array */
65 private $duplicateKeyLookups = [];
66
67 /** @var bool */
68 private $reportDupes = false;
69
70 /** @var bool */
71 private $dupeTrackScheduled = false;
72
73 /** Possible values for getLastError() */
74 const ERR_NONE = 0; // no error
75 const ERR_NO_RESPONSE = 1; // no response
76 const ERR_UNREACHABLE = 2; // can't connect
77 const ERR_UNEXPECTED = 3; // response gave some error
78
79 /** Bitfield constants for get()/getMulti() */
80 const READ_LATEST = 1; // use latest data for replicated stores
81 const READ_VERIFIED = 2; // promise that caller can tell when keys are stale
82 /** Bitfield constants for set()/merge() */
83 const WRITE_SYNC = 1; // synchronously write to all locations for replicated stores
84 const WRITE_CACHE_ONLY = 2; // Only change state of the in-memory cache
85
86 /**
87 * $params include:
88 * - logger: Psr\Log\LoggerInterface instance
89 * - keyspace: Default keyspace for $this->makeKey()
90 * - asyncHandler: Callable to use for scheduling tasks after the web request ends.
91 * In CLI mode, it should run the task immediately.
92 * - reportDupes: Whether to emit warning log messages for all keys that were
93 * requested more than once (requires an asyncHandler).
94 * @param array $params
95 */
96 public function __construct( array $params = [] ) {
97 if ( isset( $params['logger'] ) ) {
98 $this->setLogger( $params['logger'] );
99 } else {
100 $this->setLogger( new NullLogger() );
101 }
102
103 if ( isset( $params['keyspace'] ) ) {
104 $this->keyspace = $params['keyspace'];
105 }
106
107 $this->asyncHandler = isset( $params['asyncHandler'] )
108 ? $params['asyncHandler']
109 : null;
110
111 if ( !empty( $params['reportDupes'] ) && is_callable( $this->asyncHandler ) ) {
112 $this->reportDupes = true;
113 }
114 }
115
116 /**
117 * @param LoggerInterface $logger
118 * @return null
119 */
120 public function setLogger( LoggerInterface $logger ) {
121 $this->logger = $logger;
122 }
123
124 /**
125 * @param bool $bool
126 */
127 public function setDebug( $bool ) {
128 $this->debugMode = $bool;
129 }
130
131 /**
132 * Get an item with the given key, regenerating and setting it if not found
133 *
134 * If the callback returns false, then nothing is stored.
135 *
136 * @param string $key
137 * @param int $ttl Time-to-live (seconds)
138 * @param callable $callback Callback that derives the new value
139 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
140 * @return mixed The cached value if found or the result of $callback otherwise
141 * @since 1.27
142 */
143 final public function getWithSetCallback( $key, $ttl, $callback, $flags = 0 ) {
144 $value = $this->get( $key, $flags );
145
146 if ( $value === false ) {
147 if ( !is_callable( $callback ) ) {
148 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
149 }
150 $value = call_user_func( $callback );
151 if ( $value !== false ) {
152 $this->set( $key, $value, $ttl );
153 }
154 }
155
156 return $value;
157 }
158
159 /**
160 * Get an item with the given key
161 *
162 * If the key includes a determistic input hash (e.g. the key can only have
163 * the correct value) or complete staleness checks are handled by the caller
164 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
165 * This lets tiered backends know they can safely upgrade a cached value to
166 * higher tiers using standard TTLs.
167 *
168 * @param string $key
169 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
170 * @param integer $oldFlags [unused]
171 * @return mixed Returns false on failure and if the item does not exist
172 */
173 public function get( $key, $flags = 0, $oldFlags = null ) {
174 // B/C for ( $key, &$casToken = null, $flags = 0 )
175 $flags = is_int( $oldFlags ) ? $oldFlags : $flags;
176
177 $this->trackDuplicateKeys( $key );
178
179 return $this->doGet( $key, $flags );
180 }
181
182 /**
183 * Track the number of times that a given key has been used.
184 * @param string $key
185 */
186 private function trackDuplicateKeys( $key ) {
187 if ( !$this->reportDupes ) {
188 return;
189 }
190
191 if ( !isset( $this->duplicateKeyLookups[$key] ) ) {
192 // Track that we have seen this key. This N-1 counting style allows
193 // easy filtering with array_filter() later.
194 $this->duplicateKeyLookups[$key] = 0;
195 } else {
196 $this->duplicateKeyLookups[$key] += 1;
197
198 if ( $this->dupeTrackScheduled === false ) {
199 $this->dupeTrackScheduled = true;
200 // Schedule a callback that logs keys processed more than once by get().
201 call_user_func( $this->asyncHandler, function () {
202 $dups = array_filter( $this->duplicateKeyLookups );
203 foreach ( $dups as $key => $count ) {
204 $this->logger->warning(
205 'Duplicate get(): "{key}" fetched {count} times',
206 // Count is N-1 of the actual lookup count
207 [ 'key' => $key, 'count' => $count + 1, ]
208 );
209 }
210 } );
211 }
212 }
213 }
214
215 /**
216 * @param string $key
217 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
218 * @return mixed Returns false on failure and if the item does not exist
219 */
220 abstract protected function doGet( $key, $flags = 0 );
221
222 /**
223 * @note: This method is only needed if merge() uses mergeViaCas()
224 *
225 * @param string $key
226 * @param mixed $casToken
227 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
228 * @return mixed Returns false on failure and if the item does not exist
229 * @throws Exception
230 */
231 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
232 throw new Exception( __METHOD__ . ' not implemented.' );
233 }
234
235 /**
236 * Set an item
237 *
238 * @param string $key
239 * @param mixed $value
240 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
241 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
242 * @return bool Success
243 */
244 abstract public function set( $key, $value, $exptime = 0, $flags = 0 );
245
246 /**
247 * Delete an item
248 *
249 * @param string $key
250 * @return bool True if the item was deleted or not found, false on failure
251 */
252 abstract public function delete( $key );
253
254 /**
255 * Merge changes into the existing cache value (possibly creating a new one).
256 * The callback function returns the new value given the current value
257 * (which will be false if not present), and takes the arguments:
258 * (this BagOStuff, cache key, current value).
259 *
260 * @param string $key
261 * @param callable $callback Callback method to be executed
262 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
263 * @param int $attempts The amount of times to attempt a merge in case of failure
264 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
265 * @return bool Success
266 * @throws InvalidArgumentException
267 */
268 public function merge( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
269 if ( !is_callable( $callback ) ) {
270 throw new InvalidArgumentException( "Got invalid callback." );
271 }
272
273 return $this->mergeViaLock( $key, $callback, $exptime, $attempts, $flags );
274 }
275
276 /**
277 * @see BagOStuff::merge()
278 *
279 * @param string $key
280 * @param callable $callback Callback method to be executed
281 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
282 * @param int $attempts The amount of times to attempt a merge in case of failure
283 * @return bool Success
284 */
285 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
286 do {
287 $this->clearLastError();
288 $casToken = null; // passed by reference
289 $currentValue = $this->getWithToken( $key, $casToken, self::READ_LATEST );
290 if ( $this->getLastError() ) {
291 return false; // don't spam retries (retry only on races)
292 }
293
294 // Derive the new value from the old value
295 $value = call_user_func( $callback, $this, $key, $currentValue );
296
297 $this->clearLastError();
298 if ( $value === false ) {
299 $success = true; // do nothing
300 } elseif ( $currentValue === false ) {
301 // Try to create the key, failing if it gets created in the meantime
302 $success = $this->add( $key, $value, $exptime );
303 } else {
304 // Try to update the key, failing if it gets changed in the meantime
305 $success = $this->cas( $casToken, $key, $value, $exptime );
306 }
307 if ( $this->getLastError() ) {
308 return false; // IO error; don't spam retries
309 }
310 } while ( !$success && --$attempts );
311
312 return $success;
313 }
314
315 /**
316 * Check and set an item
317 *
318 * @param mixed $casToken
319 * @param string $key
320 * @param mixed $value
321 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
322 * @return bool Success
323 * @throws Exception
324 */
325 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
326 throw new Exception( "CAS is not implemented in " . __CLASS__ );
327 }
328
329 /**
330 * @see BagOStuff::merge()
331 *
332 * @param string $key
333 * @param callable $callback Callback method to be executed
334 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
335 * @param int $attempts The amount of times to attempt a merge in case of failure
336 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
337 * @return bool Success
338 */
339 protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
340 if ( !$this->lock( $key, 6 ) ) {
341 return false;
342 }
343
344 $this->clearLastError();
345 $currentValue = $this->get( $key, self::READ_LATEST );
346 if ( $this->getLastError() ) {
347 $success = false;
348 } else {
349 // Derive the new value from the old value
350 $value = call_user_func( $callback, $this, $key, $currentValue );
351 if ( $value === false ) {
352 $success = true; // do nothing
353 } else {
354 $success = $this->set( $key, $value, $exptime, $flags ); // set the new value
355 }
356 }
357
358 if ( !$this->unlock( $key ) ) {
359 // this should never happen
360 trigger_error( "Could not release lock for key '$key'." );
361 }
362
363 return $success;
364 }
365
366 /**
367 * Acquire an advisory lock on a key string
368 *
369 * Note that if reentry is enabled, duplicate calls ignore $expiry
370 *
371 * @param string $key
372 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
373 * @param int $expiry Lock expiry [optional]; 1 day maximum
374 * @param string $rclass Allow reentry if set and the current lock used this value
375 * @return bool Success
376 */
377 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
378 // Avoid deadlocks and allow lock reentry if specified
379 if ( isset( $this->locks[$key] ) ) {
380 if ( $rclass != '' && $this->locks[$key]['class'] === $rclass ) {
381 ++$this->locks[$key]['depth'];
382 return true;
383 } else {
384 return false;
385 }
386 }
387
388 $expiry = min( $expiry ?: INF, self::TTL_DAY );
389
390 $this->clearLastError();
391 $timestamp = microtime( true ); // starting UNIX timestamp
392 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
393 $locked = true;
394 } elseif ( $this->getLastError() || $timeout <= 0 ) {
395 $locked = false; // network partition or non-blocking
396 } else {
397 // Estimate the RTT (us); use 1ms minimum for sanity
398 $uRTT = max( 1e3, ceil( 1e6 * ( microtime( true ) - $timestamp ) ) );
399 $sleep = 2 * $uRTT; // rough time to do get()+set()
400
401 $attempts = 0; // failed attempts
402 do {
403 if ( ++$attempts >= 3 && $sleep <= 5e5 ) {
404 // Exponentially back off after failed attempts to avoid network spam.
405 // About 2*$uRTT*(2^n-1) us of "sleep" happen for the next n attempts.
406 $sleep *= 2;
407 }
408 usleep( $sleep ); // back off
409 $this->clearLastError();
410 $locked = $this->add( "{$key}:lock", 1, $expiry );
411 if ( $this->getLastError() ) {
412 $locked = false; // network partition
413 break;
414 }
415 } while ( !$locked && ( microtime( true ) - $timestamp ) < $timeout );
416 }
417
418 if ( $locked ) {
419 $this->locks[$key] = [ 'class' => $rclass, 'depth' => 1 ];
420 }
421
422 return $locked;
423 }
424
425 /**
426 * Release an advisory lock on a key string
427 *
428 * @param string $key
429 * @return bool Success
430 */
431 public function unlock( $key ) {
432 if ( isset( $this->locks[$key] ) && --$this->locks[$key]['depth'] <= 0 ) {
433 unset( $this->locks[$key] );
434
435 return $this->delete( "{$key}:lock" );
436 }
437
438 return true;
439 }
440
441 /**
442 * Get a lightweight exclusive self-unlocking lock
443 *
444 * Note that the same lock cannot be acquired twice.
445 *
446 * This is useful for task de-duplication or to avoid obtrusive
447 * (though non-corrupting) DB errors like INSERT key conflicts
448 * or deadlocks when using LOCK IN SHARE MODE.
449 *
450 * @param string $key
451 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
452 * @param int $expiry Lock expiry [optional]; 1 day maximum
453 * @param string $rclass Allow reentry if set and the current lock used this value
454 * @return ScopedCallback|null Returns null on failure
455 * @since 1.26
456 */
457 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
458 $expiry = min( $expiry ?: INF, self::TTL_DAY );
459
460 if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
461 return null;
462 }
463
464 $lSince = microtime( true ); // lock timestamp
465
466 return new ScopedCallback( function() use ( $key, $lSince, $expiry ) {
467 $latency = .050; // latency skew (err towards keeping lock present)
468 $age = ( microtime( true ) - $lSince + $latency );
469 if ( ( $age + $latency ) >= $expiry ) {
470 $this->logger->warning( "Lock for $key held too long ($age sec)." );
471 return; // expired; it's not "safe" to delete the key
472 }
473 $this->unlock( $key );
474 } );
475 }
476
477 /**
478 * Delete all objects expiring before a certain date.
479 * @param string $date The reference date in MW format
480 * @param callable|bool $progressCallback Optional, a function which will be called
481 * regularly during long-running operations with the percentage progress
482 * as the first parameter.
483 *
484 * @return bool Success, false if unimplemented
485 */
486 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
487 // stub
488 return false;
489 }
490
491 /**
492 * Get an associative array containing the item for each of the keys that have items.
493 * @param array $keys List of strings
494 * @param integer $flags Bitfield; supports READ_LATEST [optional]
495 * @return array
496 */
497 public function getMulti( array $keys, $flags = 0 ) {
498 $res = [];
499 foreach ( $keys as $key ) {
500 $val = $this->get( $key );
501 if ( $val !== false ) {
502 $res[$key] = $val;
503 }
504 }
505 return $res;
506 }
507
508 /**
509 * Batch insertion
510 * @param array $data $key => $value assoc array
511 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
512 * @return bool Success
513 * @since 1.24
514 */
515 public function setMulti( array $data, $exptime = 0 ) {
516 $res = true;
517 foreach ( $data as $key => $value ) {
518 if ( !$this->set( $key, $value, $exptime ) ) {
519 $res = false;
520 }
521 }
522 return $res;
523 }
524
525 /**
526 * @param string $key
527 * @param mixed $value
528 * @param int $exptime
529 * @return bool Success
530 */
531 public function add( $key, $value, $exptime = 0 ) {
532 if ( $this->get( $key ) === false ) {
533 return $this->set( $key, $value, $exptime );
534 }
535 return false; // key already set
536 }
537
538 /**
539 * Increase stored value of $key by $value while preserving its TTL
540 * @param string $key Key to increase
541 * @param int $value Value to add to $key (Default 1)
542 * @return int|bool New value or false on failure
543 */
544 public function incr( $key, $value = 1 ) {
545 if ( !$this->lock( $key ) ) {
546 return false;
547 }
548 $n = $this->get( $key );
549 if ( $this->isInteger( $n ) ) { // key exists?
550 $n += intval( $value );
551 $this->set( $key, max( 0, $n ) ); // exptime?
552 } else {
553 $n = false;
554 }
555 $this->unlock( $key );
556
557 return $n;
558 }
559
560 /**
561 * Decrease stored value of $key by $value while preserving its TTL
562 * @param string $key
563 * @param int $value
564 * @return int|bool New value or false on failure
565 */
566 public function decr( $key, $value = 1 ) {
567 return $this->incr( $key, - $value );
568 }
569
570 /**
571 * Increase stored value of $key by $value while preserving its TTL
572 *
573 * This will create the key with value $init and TTL $ttl instead if not present
574 *
575 * @param string $key
576 * @param int $ttl
577 * @param int $value
578 * @param int $init
579 * @return int|bool New value or false on failure
580 * @since 1.24
581 */
582 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
583 $newValue = $this->incr( $key, $value );
584 if ( $newValue === false ) {
585 // No key set; initialize
586 $newValue = $this->add( $key, (int)$init, $ttl ) ? $init : false;
587 }
588 if ( $newValue === false ) {
589 // Raced out initializing; increment
590 $newValue = $this->incr( $key, $value );
591 }
592
593 return $newValue;
594 }
595
596 /**
597 * Get the "last error" registered; clearLastError() should be called manually
598 * @return int ERR_* constant for the "last error" registry
599 * @since 1.23
600 */
601 public function getLastError() {
602 return $this->lastError;
603 }
604
605 /**
606 * Clear the "last error" registry
607 * @since 1.23
608 */
609 public function clearLastError() {
610 $this->lastError = self::ERR_NONE;
611 }
612
613 /**
614 * Set the "last error" registry
615 * @param int $err ERR_* constant
616 * @since 1.23
617 */
618 protected function setLastError( $err ) {
619 $this->lastError = $err;
620 }
621
622 /**
623 * Modify a cache update operation array for EventRelayer::notify()
624 *
625 * This is used for relayed writes, e.g. for broadcasting a change
626 * to multiple data-centers. If the array contains a 'val' field
627 * then the command involves setting a key to that value. Note that
628 * for simplicity, 'val' is always a simple scalar value. This method
629 * is used to possibly serialize the value and add any cache-specific
630 * key/values needed for the relayer daemon (e.g. memcached flags).
631 *
632 * @param array $event
633 * @return array
634 * @since 1.26
635 */
636 public function modifySimpleRelayEvent( array $event ) {
637 return $event;
638 }
639
640 /**
641 * @param string $text
642 */
643 protected function debug( $text ) {
644 if ( $this->debugMode ) {
645 $this->logger->debug( "{class} debug: $text", [
646 'class' => get_class( $this ),
647 ] );
648 }
649 }
650
651 /**
652 * Convert an optionally relative time to an absolute time
653 * @param int $exptime
654 * @return int
655 */
656 protected function convertExpiry( $exptime ) {
657 if ( $exptime != 0 && $exptime < ( 10 * self::TTL_YEAR ) ) {
658 return time() + $exptime;
659 } else {
660 return $exptime;
661 }
662 }
663
664 /**
665 * Convert an optionally absolute expiry time to a relative time. If an
666 * absolute time is specified which is in the past, use a short expiry time.
667 *
668 * @param int $exptime
669 * @return int
670 */
671 protected function convertToRelative( $exptime ) {
672 if ( $exptime >= ( 10 * self::TTL_YEAR ) ) {
673 $exptime -= time();
674 if ( $exptime <= 0 ) {
675 $exptime = 1;
676 }
677 return $exptime;
678 } else {
679 return $exptime;
680 }
681 }
682
683 /**
684 * Check if a value is an integer
685 *
686 * @param mixed $value
687 * @return bool
688 */
689 protected function isInteger( $value ) {
690 return ( is_int( $value ) || ctype_digit( $value ) );
691 }
692
693 /**
694 * Construct a cache key.
695 *
696 * @since 1.27
697 * @param string $keyspace
698 * @param array $args
699 * @return string
700 */
701 public function makeKeyInternal( $keyspace, $args ) {
702 $key = $keyspace;
703 foreach ( $args as $arg ) {
704 $arg = str_replace( ':', '%3A', $arg );
705 $key = $key . ':' . $arg;
706 }
707 return strtr( $key, ' ', '_' );
708 }
709
710 /**
711 * Make a global cache key.
712 *
713 * @since 1.27
714 * @param string ... Key component (variadic)
715 * @return string
716 */
717 public function makeGlobalKey() {
718 return $this->makeKeyInternal( 'global', func_get_args() );
719 }
720
721 /**
722 * Make a cache key, scoped to this instance's keyspace.
723 *
724 * @since 1.27
725 * @param string ... Key component (variadic)
726 * @return string
727 */
728 public function makeKey() {
729 return $this->makeKeyInternal( $this->keyspace, func_get_args() );
730 }
731 }