Merge "Made Revision::newFromPageId avoid master queries like newFromTitle does"
[lhc/web/wiklou.git] / includes / objectcache / BagOStuff.php
1 <?php
2 /**
3 * Classes to cache objects in PHP accelerators, SQL database or DBA files
4 *
5 * Copyright © 2003-2004 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
7 *
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.
12 *
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.
17 *
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
22 *
23 * @file
24 * @ingroup Cache
25 */
26
27 /**
28 * @defgroup Cache Cache
29 */
30
31 use Psr\Log\LoggerAwareInterface;
32 use Psr\Log\LoggerInterface;
33 use Psr\Log\NullLogger;
34
35 /**
36 * interface is intended to be more or less compatible with
37 * the PHP memcached client.
38 *
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>
44 *
45 * @ingroup Cache
46 */
47 abstract class BagOStuff implements LoggerAwareInterface {
48 private $debugMode = false;
49
50 protected $lastError = self::ERR_NONE;
51
52 /**
53 * @var LoggerInterface
54 */
55 protected $logger;
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 public function __construct( array $params = array() ) {
64 if ( isset( $params['logger'] ) ) {
65 $this->setLogger( $params['logger'] );
66 } else {
67 $this->setLogger( new NullLogger() );
68 }
69 }
70
71 /**
72 * @param LoggerInterface $logger
73 * @return null
74 */
75 public function setLogger( LoggerInterface $logger ) {
76 $this->logger = $logger;
77 }
78
79 /**
80 * @param bool $bool
81 */
82 public function setDebug( $bool ) {
83 $this->debugMode = $bool;
84 }
85
86 /* *** THE GUTS OF THE OPERATION *** */
87 /* Override these with functional things in subclasses */
88
89 /**
90 * Get an item with the given key. Returns false if it does not exist.
91 * @param string $key
92 * @param mixed $casToken [optional]
93 * @return mixed Returns false on failure
94 */
95 abstract public function get( $key, &$casToken = null );
96
97 /**
98 * Set an item.
99 * @param string $key
100 * @param mixed $value
101 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
102 * @return bool Success
103 */
104 abstract public function set( $key, $value, $exptime = 0 );
105
106 /**
107 * Check and set an item.
108 * @param mixed $casToken
109 * @param string $key
110 * @param mixed $value
111 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
112 * @return bool Success
113 */
114 abstract public function cas( $casToken, $key, $value, $exptime = 0 );
115
116 /**
117 * Delete an item.
118 * @param string $key
119 * @param int $time Amount of time to delay the operation (mostly memcached-specific)
120 * @return bool True if the item was deleted or not found, false on failure
121 */
122 abstract public function delete( $key, $time = 0 );
123
124 /**
125 * Merge changes into the existing cache value (possibly creating a new one).
126 * The callback function returns the new value given the current value (possibly false),
127 * and takes the arguments: (this BagOStuff object, cache key, current value).
128 *
129 * @param string $key
130 * @param Closure $callback Callback method to be executed
131 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
132 * @param int $attempts The amount of times to attempt a merge in case of failure
133 * @return bool Success
134 */
135 public function merge( $key, Closure $callback, $exptime = 0, $attempts = 10 ) {
136 return $this->mergeViaCas( $key, $callback, $exptime, $attempts );
137 }
138
139 /**
140 * @see BagOStuff::merge()
141 *
142 * @param string $key
143 * @param Closure $callback Callback method to be executed
144 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
145 * @param int $attempts The amount of times to attempt a merge in case of failure
146 * @return bool Success
147 */
148 protected function mergeViaCas( $key, Closure $callback, $exptime = 0, $attempts = 10 ) {
149 do {
150 $casToken = null; // passed by reference
151 $currentValue = $this->get( $key, $casToken ); // get the old value
152 $value = $callback( $this, $key, $currentValue ); // derive the new value
153
154 if ( $value === false ) {
155 $success = true; // do nothing
156 } elseif ( $currentValue === false ) {
157 // Try to create the key, failing if it gets created in the meantime
158 $success = $this->add( $key, $value, $exptime );
159 } else {
160 // Try to update the key, failing if it gets changed in the meantime
161 $success = $this->cas( $casToken, $key, $value, $exptime );
162 }
163 } while ( !$success && --$attempts );
164
165 return $success;
166 }
167
168 /**
169 * @see BagOStuff::merge()
170 *
171 * @param string $key
172 * @param Closure $callback Callback method to be executed
173 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
174 * @param int $attempts The amount of times to attempt a merge in case of failure
175 * @return bool Success
176 */
177 protected function mergeViaLock( $key, Closure $callback, $exptime = 0, $attempts = 10 ) {
178 if ( !$this->lock( $key, 6 ) ) {
179 return false;
180 }
181
182 $currentValue = $this->get( $key ); // get the old value
183 $value = $callback( $this, $key, $currentValue ); // derive the new value
184
185 if ( $value === false ) {
186 $success = true; // do nothing
187 } else {
188 $success = $this->set( $key, $value, $exptime ); // set the new value
189 }
190
191 if ( !$this->unlock( $key ) ) {
192 // this should never happen
193 trigger_error( "Could not release lock for key '$key'." );
194 }
195
196 return $success;
197 }
198
199 /**
200 * @param string $key
201 * @param int $timeout Lock wait timeout [optional]
202 * @param int $expiry Lock expiry [optional]
203 * @return bool Success
204 */
205 public function lock( $key, $timeout = 6, $expiry = 6 ) {
206 $this->clearLastError();
207 $timestamp = microtime( true ); // starting UNIX timestamp
208 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
209 return true;
210 } elseif ( $this->getLastError() ) {
211 return false;
212 }
213
214 $uRTT = ceil( 1e6 * ( microtime( true ) - $timestamp ) ); // estimate RTT (us)
215 $sleep = 2 * $uRTT; // rough time to do get()+set()
216
217 $locked = false; // lock acquired
218 $attempts = 0; // failed attempts
219 do {
220 if ( ++$attempts >= 3 && $sleep <= 5e5 ) {
221 // Exponentially back off after failed attempts to avoid network spam.
222 // About 2*$uRTT*(2^n-1) us of "sleep" happen for the next n attempts.
223 $sleep *= 2;
224 }
225 usleep( $sleep ); // back off
226 $this->clearLastError();
227 $locked = $this->add( "{$key}:lock", 1, $expiry );
228 if ( $this->getLastError() ) {
229 return false;
230 }
231 } while ( !$locked && ( microtime( true ) - $timestamp ) < $timeout );
232
233 return $locked;
234 }
235
236 /**
237 * @param string $key
238 * @return bool Success
239 */
240 public function unlock( $key ) {
241 return $this->delete( "{$key}:lock" );
242 }
243
244 /**
245 * Delete all objects expiring before a certain date.
246 * @param string $date The reference date in MW format
247 * @param callable|bool $progressCallback Optional, a function which will be called
248 * regularly during long-running operations with the percentage progress
249 * as the first parameter.
250 *
251 * @return bool Success, false if unimplemented
252 */
253 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
254 // stub
255 return false;
256 }
257
258 /* *** Emulated functions *** */
259
260 /**
261 * Get an associative array containing the item for each of the keys that have items.
262 * @param array $keys List of strings
263 * @return array
264 */
265 public function getMulti( array $keys ) {
266 $res = array();
267 foreach ( $keys as $key ) {
268 $val = $this->get( $key );
269 if ( $val !== false ) {
270 $res[$key] = $val;
271 }
272 }
273 return $res;
274 }
275
276 /**
277 * Batch insertion
278 * @param array $data $key => $value assoc array
279 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
280 * @return bool Success
281 * @since 1.24
282 */
283 public function setMulti( array $data, $exptime = 0 ) {
284 $res = true;
285 foreach ( $data as $key => $value ) {
286 if ( !$this->set( $key, $value, $exptime ) ) {
287 $res = false;
288 }
289 }
290 return $res;
291 }
292
293 /**
294 * @param string $key
295 * @param mixed $value
296 * @param int $exptime
297 * @return bool Success
298 */
299 public function add( $key, $value, $exptime = 0 ) {
300 if ( $this->get( $key ) === false ) {
301 return $this->set( $key, $value, $exptime );
302 }
303 return false; // key already set
304 }
305
306 /**
307 * Increase stored value of $key by $value while preserving its TTL
308 * @param string $key Key to increase
309 * @param int $value Value to add to $key (Default 1)
310 * @return int|bool New value or false on failure
311 */
312 public function incr( $key, $value = 1 ) {
313 if ( !$this->lock( $key ) ) {
314 return false;
315 }
316 $n = $this->get( $key );
317 if ( $this->isInteger( $n ) ) { // key exists?
318 $n += intval( $value );
319 $this->set( $key, max( 0, $n ) ); // exptime?
320 } else {
321 $n = false;
322 }
323 $this->unlock( $key );
324
325 return $n;
326 }
327
328 /**
329 * Decrease stored value of $key by $value while preserving its TTL
330 * @param string $key
331 * @param int $value
332 * @return int
333 */
334 public function decr( $key, $value = 1 ) {
335 return $this->incr( $key, - $value );
336 }
337
338 /**
339 * Increase stored value of $key by $value while preserving its TTL
340 *
341 * This will create the key with value $init and TTL $ttl if not present
342 *
343 * @param string $key
344 * @param int $ttl
345 * @param int $value
346 * @param int $init
347 * @return bool
348 * @since 1.24
349 */
350 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
351 return $this->incr( $key, $value ) ||
352 $this->add( $key, (int)$init, $ttl ) || $this->incr( $key, $value );
353 }
354
355 /**
356 * Get the "last error" registered; clearLastError() should be called manually
357 * @return int ERR_* constant for the "last error" registry
358 * @since 1.23
359 */
360 public function getLastError() {
361 return $this->lastError;
362 }
363
364 /**
365 * Clear the "last error" registry
366 * @since 1.23
367 */
368 public function clearLastError() {
369 $this->lastError = self::ERR_NONE;
370 }
371
372 /**
373 * Set the "last error" registry
374 * @param int $err ERR_* constant
375 * @since 1.23
376 */
377 protected function setLastError( $err ) {
378 $this->lastError = $err;
379 }
380
381 /**
382 * @param string $text
383 */
384 public function debug( $text ) {
385 if ( $this->debugMode ) {
386 $this->logger->debug( "{class} debug: $text", array(
387 'class' => get_class( $this ),
388 ) );
389 }
390 }
391
392 /**
393 * Convert an optionally relative time to an absolute time
394 * @param int $exptime
395 * @return int
396 */
397 protected function convertExpiry( $exptime ) {
398 if ( ( $exptime != 0 ) && ( $exptime < 86400 * 3650 /* 10 years */ ) ) {
399 return time() + $exptime;
400 } else {
401 return $exptime;
402 }
403 }
404
405 /**
406 * Convert an optionally absolute expiry time to a relative time. If an
407 * absolute time is specified which is in the past, use a short expiry time.
408 *
409 * @param int $exptime
410 * @return int
411 */
412 protected function convertToRelative( $exptime ) {
413 if ( $exptime >= 86400 * 3650 /* 10 years */ ) {
414 $exptime -= time();
415 if ( $exptime <= 0 ) {
416 $exptime = 1;
417 }
418 return $exptime;
419 } else {
420 return $exptime;
421 }
422 }
423
424 /**
425 * Check if a value is an integer
426 *
427 * @param mixed $value
428 * @return bool
429 */
430 protected function isInteger( $value ) {
431 return ( is_int( $value ) || ctype_digit( $value ) );
432 }
433 }