Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / objectcache / BagOStuff.php
blob2c10742c260979b40fb16ff6bc835cc39429e5c8
1 <?php
2 /**
3 * Classes to cache objects in PHP accelerators, SQL database or DBA files
5 * Copyright © 2003-2004 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
23 * @file
24 * @ingroup Cache
27 /**
28 * @defgroup Cache Cache
31 use Psr\Log\LoggerAwareInterface;
32 use Psr\Log\LoggerInterface;
33 use Psr\Log\NullLogger;
35 /**
36 * interface is intended to be more or less compatible with
37 * the PHP memcached client.
39 * backends for local hash array and SQL table included:
40 * <code>
41 * $bag = new HashBagOStuff();
42 * $bag = new SqlBagOStuff(); # connect to db first
43 * </code>
45 * @ingroup Cache
47 abstract class BagOStuff implements LoggerAwareInterface {
48 private $debugMode = false;
50 protected $lastError = self::ERR_NONE;
52 /**
53 * @var LoggerInterface
55 protected $logger;
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
63 public function __construct( array $params = array() ) {
64 if ( isset( $params['logger'] ) ) {
65 $this->setLogger( $params['logger'] );
66 } else {
67 $this->setLogger( new NullLogger() );
71 /**
72 * @param LoggerInterface $logger
73 * @return null
75 public function setLogger( LoggerInterface $logger ) {
76 $this->logger = $logger;
79 /**
80 * @param bool $bool
82 public function setDebug( $bool ) {
83 $this->debugMode = $bool;
86 /**
87 * Get an item with the given key. Returns false if it does not exist.
88 * @param string $key
89 * @param mixed $casToken [optional]
90 * @return mixed Returns false on failure
92 abstract public function get( $key, &$casToken = null );
94 /**
95 * Set an item.
96 * @param string $key
97 * @param mixed $value
98 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
99 * @return bool Success
101 abstract public function set( $key, $value, $exptime = 0 );
104 * Delete an item.
105 * @param string $key
106 * @return bool True if the item was deleted or not found, false on failure
108 abstract public function delete( $key );
111 * Merge changes into the existing cache value (possibly creating a new one).
112 * The callback function returns the new value given the current value (possibly false),
113 * and takes the arguments: (this BagOStuff object, cache key, current value).
115 * @param string $key
116 * @param callable $callback Callback method to be executed
117 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
118 * @param int $attempts The amount of times to attempt a merge in case of failure
119 * @return bool Success
121 public function merge( $key, $callback, $exptime = 0, $attempts = 10 ) {
122 if ( !is_callable( $callback ) ) {
123 throw new Exception( "Got invalid callback." );
126 return $this->mergeViaCas( $key, $callback, $exptime, $attempts );
130 * @see BagOStuff::merge()
132 * @param string $key
133 * @param callable $callback Callback method to be executed
134 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
135 * @param int $attempts The amount of times to attempt a merge in case of failure
136 * @return bool Success
138 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
139 do {
140 $casToken = null; // passed by reference
141 $currentValue = $this->get( $key, $casToken );
142 // Derive the new value from the old value
143 $value = call_user_func( $callback, $this, $key, $currentValue );
145 if ( $value === false ) {
146 $success = true; // do nothing
147 } elseif ( $currentValue === false ) {
148 // Try to create the key, failing if it gets created in the meantime
149 $success = $this->add( $key, $value, $exptime );
150 } else {
151 // Try to update the key, failing if it gets changed in the meantime
152 $success = $this->cas( $casToken, $key, $value, $exptime );
154 } while ( !$success && --$attempts );
156 return $success;
160 * Check and set an item.
161 * @param mixed $casToken
162 * @param string $key
163 * @param mixed $value
164 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
165 * @return bool Success
167 abstract protected function cas( $casToken, $key, $value, $exptime = 0 );
170 * @see BagOStuff::merge()
172 * @param string $key
173 * @param callable $callback Callback method to be executed
174 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
175 * @param int $attempts The amount of times to attempt a merge in case of failure
176 * @return bool Success
178 protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10 ) {
179 if ( !$this->lock( $key, 6 ) ) {
180 return false;
183 $currentValue = $this->get( $key );
184 // Derive the new value from the old value
185 $value = call_user_func( $callback, $this, $key, $currentValue );
187 if ( $value === false ) {
188 $success = true; // do nothing
189 } else {
190 $success = $this->set( $key, $value, $exptime ); // set the new value
193 if ( !$this->unlock( $key ) ) {
194 // this should never happen
195 trigger_error( "Could not release lock for key '$key'." );
198 return $success;
202 * @param string $key
203 * @param int $timeout Lock wait timeout [optional]
204 * @param int $expiry Lock expiry [optional]
205 * @return bool Success
207 public function lock( $key, $timeout = 6, $expiry = 6 ) {
208 $this->clearLastError();
209 $timestamp = microtime( true ); // starting UNIX timestamp
210 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
211 return true;
212 } elseif ( $this->getLastError() ) {
213 return false;
216 $uRTT = ceil( 1e6 * ( microtime( true ) - $timestamp ) ); // estimate RTT (us)
217 $sleep = 2 * $uRTT; // rough time to do get()+set()
219 $locked = false; // lock acquired
220 $attempts = 0; // failed attempts
221 do {
222 if ( ++$attempts >= 3 && $sleep <= 5e5 ) {
223 // Exponentially back off after failed attempts to avoid network spam.
224 // About 2*$uRTT*(2^n-1) us of "sleep" happen for the next n attempts.
225 $sleep *= 2;
227 usleep( $sleep ); // back off
228 $this->clearLastError();
229 $locked = $this->add( "{$key}:lock", 1, $expiry );
230 if ( $this->getLastError() ) {
231 return false;
233 } while ( !$locked && ( microtime( true ) - $timestamp ) < $timeout );
235 return $locked;
239 * @param string $key
240 * @return bool Success
242 public function unlock( $key ) {
243 return $this->delete( "{$key}:lock" );
247 * Delete all objects expiring before a certain date.
248 * @param string $date The reference date in MW format
249 * @param callable|bool $progressCallback Optional, a function which will be called
250 * regularly during long-running operations with the percentage progress
251 * as the first parameter.
253 * @return bool Success, false if unimplemented
255 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
256 // stub
257 return false;
260 /* *** Emulated functions *** */
263 * Get an associative array containing the item for each of the keys that have items.
264 * @param array $keys List of strings
265 * @return array
267 public function getMulti( array $keys ) {
268 $res = array();
269 foreach ( $keys as $key ) {
270 $val = $this->get( $key );
271 if ( $val !== false ) {
272 $res[$key] = $val;
275 return $res;
279 * Batch insertion
280 * @param array $data $key => $value assoc array
281 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
282 * @return bool Success
283 * @since 1.24
285 public function setMulti( array $data, $exptime = 0 ) {
286 $res = true;
287 foreach ( $data as $key => $value ) {
288 if ( !$this->set( $key, $value, $exptime ) ) {
289 $res = false;
292 return $res;
296 * @param string $key
297 * @param mixed $value
298 * @param int $exptime
299 * @return bool Success
301 public function add( $key, $value, $exptime = 0 ) {
302 if ( $this->get( $key ) === false ) {
303 return $this->set( $key, $value, $exptime );
305 return false; // key already set
309 * Increase stored value of $key by $value while preserving its TTL
310 * @param string $key Key to increase
311 * @param int $value Value to add to $key (Default 1)
312 * @return int|bool New value or false on failure
314 public function incr( $key, $value = 1 ) {
315 if ( !$this->lock( $key ) ) {
316 return false;
318 $n = $this->get( $key );
319 if ( $this->isInteger( $n ) ) { // key exists?
320 $n += intval( $value );
321 $this->set( $key, max( 0, $n ) ); // exptime?
322 } else {
323 $n = false;
325 $this->unlock( $key );
327 return $n;
331 * Decrease stored value of $key by $value while preserving its TTL
332 * @param string $key
333 * @param int $value
334 * @return int
336 public function decr( $key, $value = 1 ) {
337 return $this->incr( $key, - $value );
341 * Increase stored value of $key by $value while preserving its TTL
343 * This will create the key with value $init and TTL $ttl if not present
345 * @param string $key
346 * @param int $ttl
347 * @param int $value
348 * @param int $init
349 * @return bool
350 * @since 1.24
352 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
353 return $this->incr( $key, $value ) ||
354 $this->add( $key, (int)$init, $ttl ) || $this->incr( $key, $value );
358 * Get the "last error" registered; clearLastError() should be called manually
359 * @return int ERR_* constant for the "last error" registry
360 * @since 1.23
362 public function getLastError() {
363 return $this->lastError;
367 * Clear the "last error" registry
368 * @since 1.23
370 public function clearLastError() {
371 $this->lastError = self::ERR_NONE;
375 * Set the "last error" registry
376 * @param int $err ERR_* constant
377 * @since 1.23
379 protected function setLastError( $err ) {
380 $this->lastError = $err;
384 * @param string $text
386 protected function debug( $text ) {
387 if ( $this->debugMode ) {
388 $this->logger->debug( "{class} debug: $text", array(
389 'class' => get_class( $this ),
390 ) );
395 * Convert an optionally relative time to an absolute time
396 * @param int $exptime
397 * @return int
399 protected function convertExpiry( $exptime ) {
400 if ( ( $exptime != 0 ) && ( $exptime < 86400 * 3650 /* 10 years */ ) ) {
401 return time() + $exptime;
402 } else {
403 return $exptime;
408 * Convert an optionally absolute expiry time to a relative time. If an
409 * absolute time is specified which is in the past, use a short expiry time.
411 * @param int $exptime
412 * @return int
414 protected function convertToRelative( $exptime ) {
415 if ( $exptime >= 86400 * 3650 /* 10 years */ ) {
416 $exptime -= time();
417 if ( $exptime <= 0 ) {
418 $exptime = 1;
420 return $exptime;
421 } else {
422 return $exptime;
427 * Check if a value is an integer
429 * @param mixed $value
430 * @return bool
432 protected function isInteger( $value ) {
433 return ( is_int( $value ) || ctype_digit( $value ) );