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