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