Merge "Get timestamp from WikiPage, instead of Article"
[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 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 = [] ) {
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] = [ '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
401 return new ScopedCallback( function() use ( $key, $lSince, $expiry ) {
402 $latency = .050; // latency skew (err towards keeping lock present)
403 $age = ( microtime( true ) - $lSince + $latency );
404 if ( ( $age + $latency ) >= $expiry ) {
405 $this->logger->warning( "Lock for $key held too long ($age sec)." );
406 return; // expired; it's not "safe" to delete the key
407 }
408 $this->unlock( $key );
409 } );
410 }
411
412 /**
413 * Delete all objects expiring before a certain date.
414 * @param string $date The reference date in MW format
415 * @param callable|bool $progressCallback Optional, a function which will be called
416 * regularly during long-running operations with the percentage progress
417 * as the first parameter.
418 *
419 * @return bool Success, false if unimplemented
420 */
421 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
422 // stub
423 return false;
424 }
425
426 /**
427 * Get an associative array containing the item for each of the keys that have items.
428 * @param array $keys List of strings
429 * @param integer $flags Bitfield; supports READ_LATEST [optional]
430 * @return array
431 */
432 public function getMulti( array $keys, $flags = 0 ) {
433 $res = [];
434 foreach ( $keys as $key ) {
435 $val = $this->get( $key );
436 if ( $val !== false ) {
437 $res[$key] = $val;
438 }
439 }
440 return $res;
441 }
442
443 /**
444 * Batch insertion
445 * @param array $data $key => $value assoc array
446 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
447 * @return bool Success
448 * @since 1.24
449 */
450 public function setMulti( array $data, $exptime = 0 ) {
451 $res = true;
452 foreach ( $data as $key => $value ) {
453 if ( !$this->set( $key, $value, $exptime ) ) {
454 $res = false;
455 }
456 }
457 return $res;
458 }
459
460 /**
461 * @param string $key
462 * @param mixed $value
463 * @param int $exptime
464 * @return bool Success
465 */
466 public function add( $key, $value, $exptime = 0 ) {
467 if ( $this->get( $key ) === false ) {
468 return $this->set( $key, $value, $exptime );
469 }
470 return false; // key already set
471 }
472
473 /**
474 * Increase stored value of $key by $value while preserving its TTL
475 * @param string $key Key to increase
476 * @param int $value Value to add to $key (Default 1)
477 * @return int|bool New value or false on failure
478 */
479 public function incr( $key, $value = 1 ) {
480 if ( !$this->lock( $key ) ) {
481 return false;
482 }
483 $n = $this->get( $key );
484 if ( $this->isInteger( $n ) ) { // key exists?
485 $n += intval( $value );
486 $this->set( $key, max( 0, $n ) ); // exptime?
487 } else {
488 $n = false;
489 }
490 $this->unlock( $key );
491
492 return $n;
493 }
494
495 /**
496 * Decrease stored value of $key by $value while preserving its TTL
497 * @param string $key
498 * @param int $value
499 * @return int|bool New value or false on failure
500 */
501 public function decr( $key, $value = 1 ) {
502 return $this->incr( $key, - $value );
503 }
504
505 /**
506 * Increase stored value of $key by $value while preserving its TTL
507 *
508 * This will create the key with value $init and TTL $ttl instead if not present
509 *
510 * @param string $key
511 * @param int $ttl
512 * @param int $value
513 * @param int $init
514 * @return int|bool New value or false on failure
515 * @since 1.24
516 */
517 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
518 $newValue = $this->incr( $key, $value );
519 if ( $newValue === false ) {
520 // No key set; initialize
521 $newValue = $this->add( $key, (int)$init, $ttl ) ? $init : false;
522 }
523 if ( $newValue === false ) {
524 // Raced out initializing; increment
525 $newValue = $this->incr( $key, $value );
526 }
527
528 return $newValue;
529 }
530
531 /**
532 * Get the "last error" registered; clearLastError() should be called manually
533 * @return int ERR_* constant for the "last error" registry
534 * @since 1.23
535 */
536 public function getLastError() {
537 return $this->lastError;
538 }
539
540 /**
541 * Clear the "last error" registry
542 * @since 1.23
543 */
544 public function clearLastError() {
545 $this->lastError = self::ERR_NONE;
546 }
547
548 /**
549 * Set the "last error" registry
550 * @param int $err ERR_* constant
551 * @since 1.23
552 */
553 protected function setLastError( $err ) {
554 $this->lastError = $err;
555 }
556
557 /**
558 * Modify a cache update operation array for EventRelayer::notify()
559 *
560 * This is used for relayed writes, e.g. for broadcasting a change
561 * to multiple data-centers. If the array contains a 'val' field
562 * then the command involves setting a key to that value. Note that
563 * for simplicity, 'val' is always a simple scalar value. This method
564 * is used to possibly serialize the value and add any cache-specific
565 * key/values needed for the relayer daemon (e.g. memcached flags).
566 *
567 * @param array $event
568 * @return array
569 * @since 1.26
570 */
571 public function modifySimpleRelayEvent( array $event ) {
572 return $event;
573 }
574
575 /**
576 * @param string $text
577 */
578 protected function debug( $text ) {
579 if ( $this->debugMode ) {
580 $this->logger->debug( "{class} debug: $text", [
581 'class' => get_class( $this ),
582 ] );
583 }
584 }
585
586 /**
587 * Convert an optionally relative time to an absolute time
588 * @param int $exptime
589 * @return int
590 */
591 protected function convertExpiry( $exptime ) {
592 if ( $exptime != 0 && $exptime < ( 10 * self::TTL_YEAR ) ) {
593 return time() + $exptime;
594 } else {
595 return $exptime;
596 }
597 }
598
599 /**
600 * Convert an optionally absolute expiry time to a relative time. If an
601 * absolute time is specified which is in the past, use a short expiry time.
602 *
603 * @param int $exptime
604 * @return int
605 */
606 protected function convertToRelative( $exptime ) {
607 if ( $exptime >= ( 10 * self::TTL_YEAR ) ) {
608 $exptime -= time();
609 if ( $exptime <= 0 ) {
610 $exptime = 1;
611 }
612 return $exptime;
613 } else {
614 return $exptime;
615 }
616 }
617
618 /**
619 * Check if a value is an integer
620 *
621 * @param mixed $value
622 * @return bool
623 */
624 protected function isInteger( $value ) {
625 return ( is_int( $value ) || ctype_digit( $value ) );
626 }
627
628 /**
629 * Construct a cache key.
630 *
631 * @since 1.27
632 * @param string $keyspace
633 * @param array $args
634 * @return string
635 */
636 public function makeKeyInternal( $keyspace, $args ) {
637 $key = $keyspace;
638 foreach ( $args as $arg ) {
639 $arg = str_replace( ':', '%3A', $arg );
640 $key = $key . ':' . $arg;
641 }
642 return strtr( $key, ' ', '_' );
643 }
644
645 /**
646 * Make a global cache key.
647 *
648 * @since 1.27
649 * @param string ... Key component (variadic)
650 * @return string
651 */
652 public function makeGlobalKey() {
653 return $this->makeKeyInternal( 'global', func_get_args() );
654 }
655
656 /**
657 * Make a cache key, scoped to this instance's keyspace.
658 *
659 * @since 1.27
660 * @param string ... Key component (variadic)
661 * @return string
662 */
663 public function makeKey() {
664 return $this->makeKeyInternal( $this->keyspace, func_get_args() );
665 }
666 }