Merge "refreshLinks.php: Fix deletion of link entries from nonexistent pages"
[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 private $debugMode = false;
47
48 /** @var integer */
49 protected $lastError = self::ERR_NONE;
50
51 /**
52 * @var LoggerInterface
53 */
54 protected $logger;
55
56 /** Possible values for getLastError() */
57 const ERR_NONE = 0; // no error
58 const ERR_NO_RESPONSE = 1; // no response
59 const ERR_UNREACHABLE = 2; // can't connect
60 const ERR_UNEXPECTED = 3; // response gave some error
61
62 /** Bitfield constants for get()/getMulti() */
63 const READ_LATEST = 1; // use latest data for replicated stores
64
65 public function __construct( array $params = array() ) {
66 if ( isset( $params['logger'] ) ) {
67 $this->setLogger( $params['logger'] );
68 } else {
69 $this->setLogger( new NullLogger() );
70 }
71 }
72
73 /**
74 * @param LoggerInterface $logger
75 * @return null
76 */
77 public function setLogger( LoggerInterface $logger ) {
78 $this->logger = $logger;
79 }
80
81 /**
82 * @param bool $bool
83 */
84 public function setDebug( $bool ) {
85 $this->debugMode = $bool;
86 }
87
88 /**
89 * Get an item with the given key. Returns false if it does not exist.
90 * @param string $key
91 * @param mixed $casToken [optional]
92 * @param integer $flags Bitfield; supports READ_LATEST [optional]
93 * @return mixed Returns false on failure
94 */
95 abstract public function get( $key, &$casToken = null, $flags = 0 );
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 * Delete an item.
108 * @param string $key
109 * @return bool True if the item was deleted or not found, false on failure
110 */
111 abstract public function delete( $key );
112
113 /**
114 * Merge changes into the existing cache value (possibly creating a new one).
115 * The callback function returns the new value given the current value
116 * (which will be false if not present), and takes the arguments:
117 * (this BagOStuff, cache key, current value).
118 *
119 * @param string $key
120 * @param callable $callback Callback method to be executed
121 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
122 * @param int $attempts The amount of times to attempt a merge in case of failure
123 * @return bool Success
124 * @throws InvalidArgumentException
125 */
126 public function merge( $key, $callback, $exptime = 0, $attempts = 10 ) {
127 if ( !is_callable( $callback ) ) {
128 throw new InvalidArgumentException( "Got invalid callback." );
129 }
130
131 return $this->mergeViaLock( $key, $callback, $exptime, $attempts );
132 }
133
134 /**
135 * @see BagOStuff::merge()
136 *
137 * @param string $key
138 * @param callable $callback Callback method to be executed
139 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
140 * @param int $attempts The amount of times to attempt a merge in case of failure
141 * @return bool Success
142 */
143 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
144 do {
145 $casToken = null; // passed by reference
146 $currentValue = $this->get( $key, $casToken );
147 // Derive the new value from the old value
148 $value = call_user_func( $callback, $this, $key, $currentValue );
149
150 if ( $value === false ) {
151 $success = true; // do nothing
152 } elseif ( $currentValue === false ) {
153 // Try to create the key, failing if it gets created in the meantime
154 $success = $this->add( $key, $value, $exptime );
155 } else {
156 // Try to update the key, failing if it gets changed in the meantime
157 $success = $this->cas( $casToken, $key, $value, $exptime );
158 }
159 } while ( !$success && --$attempts );
160
161 return $success;
162 }
163
164 /**
165 * Check and set an item
166 *
167 * @param mixed $casToken
168 * @param string $key
169 * @param mixed $value
170 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
171 * @return bool Success
172 * @throws Exception
173 */
174 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
175 throw new Exception( "CAS is not implemented in " . __CLASS__ );
176 }
177
178 /**
179 * @see BagOStuff::merge()
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 */
187 protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10 ) {
188 if ( !$this->lock( $key, 6 ) ) {
189 return false;
190 }
191
192 $currentValue = $this->get( $key );
193 // Derive the new value from the old value
194 $value = call_user_func( $callback, $this, $key, $currentValue );
195
196 if ( $value === false ) {
197 $success = true; // do nothing
198 } else {
199 $success = $this->set( $key, $value, $exptime ); // set the new value
200 }
201
202 if ( !$this->unlock( $key ) ) {
203 // this should never happen
204 trigger_error( "Could not release lock for key '$key'." );
205 }
206
207 return $success;
208 }
209
210 /**
211 * @param string $key
212 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
213 * @param int $expiry Lock expiry [optional]
214 * @return bool Success
215 */
216 public function lock( $key, $timeout = 6, $expiry = 6 ) {
217 $this->clearLastError();
218 $timestamp = microtime( true ); // starting UNIX timestamp
219 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
220 return true;
221 } elseif ( $this->getLastError() ) {
222 return false;
223 }
224
225 $uRTT = ceil( 1e6 * ( microtime( true ) - $timestamp ) ); // estimate RTT (us)
226 $sleep = 2 * $uRTT; // rough time to do get()+set()
227
228 $locked = false; // lock acquired
229 $attempts = 0; // failed attempts
230 do {
231 if ( ++$attempts >= 3 && $sleep <= 5e5 ) {
232 // Exponentially back off after failed attempts to avoid network spam.
233 // About 2*$uRTT*(2^n-1) us of "sleep" happen for the next n attempts.
234 $sleep *= 2;
235 }
236 usleep( $sleep ); // back off
237 $this->clearLastError();
238 $locked = $this->add( "{$key}:lock", 1, $expiry );
239 if ( $this->getLastError() ) {
240 return false;
241 }
242 } while ( !$locked && ( microtime( true ) - $timestamp ) < $timeout );
243
244 return $locked;
245 }
246
247 /**
248 * @param string $key
249 * @return bool Success
250 */
251 public function unlock( $key ) {
252 return $this->delete( "{$key}:lock" );
253 }
254
255 /**
256 * Delete all objects expiring before a certain date.
257 * @param string $date The reference date in MW format
258 * @param callable|bool $progressCallback Optional, a function which will be called
259 * regularly during long-running operations with the percentage progress
260 * as the first parameter.
261 *
262 * @return bool Success, false if unimplemented
263 */
264 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
265 // stub
266 return false;
267 }
268
269 /**
270 * Get an associative array containing the item for each of the keys that have items.
271 * @param array $keys List of strings
272 * @param integer $flags Bitfield; supports READ_LATEST [optional]
273 * @return array
274 */
275 public function getMulti( array $keys, $flags = 0 ) {
276 $res = array();
277 foreach ( $keys as $key ) {
278 $val = $this->get( $key );
279 if ( $val !== false ) {
280 $res[$key] = $val;
281 }
282 }
283 return $res;
284 }
285
286 /**
287 * Batch insertion
288 * @param array $data $key => $value assoc array
289 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
290 * @return bool Success
291 * @since 1.24
292 */
293 public function setMulti( array $data, $exptime = 0 ) {
294 $res = true;
295 foreach ( $data as $key => $value ) {
296 if ( !$this->set( $key, $value, $exptime ) ) {
297 $res = false;
298 }
299 }
300 return $res;
301 }
302
303 /**
304 * @param string $key
305 * @param mixed $value
306 * @param int $exptime
307 * @return bool Success
308 */
309 public function add( $key, $value, $exptime = 0 ) {
310 if ( $this->get( $key ) === false ) {
311 return $this->set( $key, $value, $exptime );
312 }
313 return false; // key already set
314 }
315
316 /**
317 * Increase stored value of $key by $value while preserving its TTL
318 * @param string $key Key to increase
319 * @param int $value Value to add to $key (Default 1)
320 * @return int|bool New value or false on failure
321 */
322 public function incr( $key, $value = 1 ) {
323 if ( !$this->lock( $key ) ) {
324 return false;
325 }
326 $n = $this->get( $key );
327 if ( $this->isInteger( $n ) ) { // key exists?
328 $n += intval( $value );
329 $this->set( $key, max( 0, $n ) ); // exptime?
330 } else {
331 $n = false;
332 }
333 $this->unlock( $key );
334
335 return $n;
336 }
337
338 /**
339 * Decrease stored value of $key by $value while preserving its TTL
340 * @param string $key
341 * @param int $value
342 * @return int|bool New value or false on failure
343 */
344 public function decr( $key, $value = 1 ) {
345 return $this->incr( $key, - $value );
346 }
347
348 /**
349 * Increase stored value of $key by $value while preserving its TTL
350 *
351 * This will create the key with value $init and TTL $ttl if not present
352 *
353 * @param string $key
354 * @param int $ttl
355 * @param int $value
356 * @param int $init
357 * @return bool
358 * @since 1.24
359 */
360 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
361 return $this->incr( $key, $value ) ||
362 $this->add( $key, (int)$init, $ttl ) || $this->incr( $key, $value );
363 }
364
365 /**
366 * Get the "last error" registered; clearLastError() should be called manually
367 * @return int ERR_* constant for the "last error" registry
368 * @since 1.23
369 */
370 public function getLastError() {
371 return $this->lastError;
372 }
373
374 /**
375 * Clear the "last error" registry
376 * @since 1.23
377 */
378 public function clearLastError() {
379 $this->lastError = self::ERR_NONE;
380 }
381
382 /**
383 * Set the "last error" registry
384 * @param int $err ERR_* constant
385 * @since 1.23
386 */
387 protected function setLastError( $err ) {
388 $this->lastError = $err;
389 }
390
391 /**
392 * Modify a cache update operation array for EventRelayer::notify()
393 *
394 * This is used for relayed writes, e.g. for broadcasting a change
395 * to multiple data-centers. If the array contains a 'val' field
396 * then the command involves setting a key to that value. Note that
397 * for simplicity, 'val' is always a simple scalar value. This method
398 * is used to possibly serialize the value and add any cache-specific
399 * key/values needed for the relayer daemon (e.g. memcached flags).
400 *
401 * @param array $event
402 * @return array
403 * @since 1.26
404 */
405 public function modifySimpleRelayEvent( array $event ) {
406 return $event;
407 }
408
409 /**
410 * @param string $text
411 */
412 protected function debug( $text ) {
413 if ( $this->debugMode ) {
414 $this->logger->debug( "{class} debug: $text", array(
415 'class' => get_class( $this ),
416 ) );
417 }
418 }
419
420 /**
421 * Convert an optionally relative time to an absolute time
422 * @param int $exptime
423 * @return int
424 */
425 protected function convertExpiry( $exptime ) {
426 if ( ( $exptime != 0 ) && ( $exptime < 86400 * 3650 /* 10 years */ ) ) {
427 return time() + $exptime;
428 } else {
429 return $exptime;
430 }
431 }
432
433 /**
434 * Convert an optionally absolute expiry time to a relative time. If an
435 * absolute time is specified which is in the past, use a short expiry time.
436 *
437 * @param int $exptime
438 * @return int
439 */
440 protected function convertToRelative( $exptime ) {
441 if ( $exptime >= 86400 * 3650 /* 10 years */ ) {
442 $exptime -= time();
443 if ( $exptime <= 0 ) {
444 $exptime = 1;
445 }
446 return $exptime;
447 } else {
448 return $exptime;
449 }
450 }
451
452 /**
453 * Check if a value is an integer
454 *
455 * @param mixed $value
456 * @return bool
457 */
458 protected function isInteger( $value ) {
459 return ( is_int( $value ) || ctype_digit( $value ) );
460 }
461 }