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