0758aef14d2d67c0dd1ed03a2d9fbcb4dd6def07
[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 /**
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
91 */
92 abstract public function get( $key, &$casToken = null );
93
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
100 */
101 abstract public function set( $key, $value, $exptime = 0 );
102
103 /**
104 * Delete an item.
105 * @param string $key
106 * @return bool True if the item was deleted or not found, false on failure
107 */
108 abstract public function delete( $key );
109
110 /**
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).
114 *
115 * @param string $key
116 * @param Closure $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
120 */
121 public function merge( $key, Closure $callback, $exptime = 0, $attempts = 10 ) {
122 return $this->mergeViaCas( $key, $callback, $exptime, $attempts );
123 }
124
125 /**
126 * @see BagOStuff::merge()
127 *
128 * @param string $key
129 * @param Closure $callback Callback method to be executed
130 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
131 * @param int $attempts The amount of times to attempt a merge in case of failure
132 * @return bool Success
133 */
134 protected function mergeViaCas( $key, Closure $callback, $exptime = 0, $attempts = 10 ) {
135 do {
136 $casToken = null; // passed by reference
137 $currentValue = $this->get( $key, $casToken ); // get the old value
138 $value = $callback( $this, $key, $currentValue ); // derive the new value
139
140 if ( $value === false ) {
141 $success = true; // do nothing
142 } elseif ( $currentValue === false ) {
143 // Try to create the key, failing if it gets created in the meantime
144 $success = $this->add( $key, $value, $exptime );
145 } else {
146 // Try to update the key, failing if it gets changed in the meantime
147 $success = $this->cas( $casToken, $key, $value, $exptime );
148 }
149 } while ( !$success && --$attempts );
150
151 return $success;
152 }
153
154 /**
155 * Check and set an item.
156 * @param mixed $casToken
157 * @param string $key
158 * @param mixed $value
159 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
160 * @return bool Success
161 */
162 abstract protected function cas( $casToken, $key, $value, $exptime = 0 );
163
164 /**
165 * @see BagOStuff::merge()
166 *
167 * @param string $key
168 * @param Closure $callback Callback method to be executed
169 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
170 * @param int $attempts The amount of times to attempt a merge in case of failure
171 * @return bool Success
172 */
173 protected function mergeViaLock( $key, Closure $callback, $exptime = 0, $attempts = 10 ) {
174 if ( !$this->lock( $key, 6 ) ) {
175 return false;
176 }
177
178 $currentValue = $this->get( $key ); // get the old value
179 $value = $callback( $this, $key, $currentValue ); // derive the new value
180
181 if ( $value === false ) {
182 $success = true; // do nothing
183 } else {
184 $success = $this->set( $key, $value, $exptime ); // set the new value
185 }
186
187 if ( !$this->unlock( $key ) ) {
188 // this should never happen
189 trigger_error( "Could not release lock for key '$key'." );
190 }
191
192 return $success;
193 }
194
195 /**
196 * @param string $key
197 * @param int $timeout Lock wait timeout [optional]
198 * @param int $expiry Lock expiry [optional]
199 * @return bool Success
200 */
201 public function lock( $key, $timeout = 6, $expiry = 6 ) {
202 $this->clearLastError();
203 $timestamp = microtime( true ); // starting UNIX timestamp
204 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
205 return true;
206 } elseif ( $this->getLastError() ) {
207 return false;
208 }
209
210 $uRTT = ceil( 1e6 * ( microtime( true ) - $timestamp ) ); // estimate RTT (us)
211 $sleep = 2 * $uRTT; // rough time to do get()+set()
212
213 $locked = false; // lock acquired
214 $attempts = 0; // failed attempts
215 do {
216 if ( ++$attempts >= 3 && $sleep <= 5e5 ) {
217 // Exponentially back off after failed attempts to avoid network spam.
218 // About 2*$uRTT*(2^n-1) us of "sleep" happen for the next n attempts.
219 $sleep *= 2;
220 }
221 usleep( $sleep ); // back off
222 $this->clearLastError();
223 $locked = $this->add( "{$key}:lock", 1, $expiry );
224 if ( $this->getLastError() ) {
225 return false;
226 }
227 } while ( !$locked && ( microtime( true ) - $timestamp ) < $timeout );
228
229 return $locked;
230 }
231
232 /**
233 * @param string $key
234 * @return bool Success
235 */
236 public function unlock( $key ) {
237 return $this->delete( "{$key}:lock" );
238 }
239
240 /**
241 * Delete all objects expiring before a certain date.
242 * @param string $date The reference date in MW format
243 * @param callable|bool $progressCallback Optional, a function which will be called
244 * regularly during long-running operations with the percentage progress
245 * as the first parameter.
246 *
247 * @return bool Success, false if unimplemented
248 */
249 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
250 // stub
251 return false;
252 }
253
254 /* *** Emulated functions *** */
255
256 /**
257 * Get an associative array containing the item for each of the keys that have items.
258 * @param array $keys List of strings
259 * @return array
260 */
261 public function getMulti( array $keys ) {
262 $res = array();
263 foreach ( $keys as $key ) {
264 $val = $this->get( $key );
265 if ( $val !== false ) {
266 $res[$key] = $val;
267 }
268 }
269 return $res;
270 }
271
272 /**
273 * Batch insertion
274 * @param array $data $key => $value assoc array
275 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
276 * @return bool Success
277 * @since 1.24
278 */
279 public function setMulti( array $data, $exptime = 0 ) {
280 $res = true;
281 foreach ( $data as $key => $value ) {
282 if ( !$this->set( $key, $value, $exptime ) ) {
283 $res = false;
284 }
285 }
286 return $res;
287 }
288
289 /**
290 * @param string $key
291 * @param mixed $value
292 * @param int $exptime
293 * @return bool Success
294 */
295 public function add( $key, $value, $exptime = 0 ) {
296 if ( $this->get( $key ) === false ) {
297 return $this->set( $key, $value, $exptime );
298 }
299 return false; // key already set
300 }
301
302 /**
303 * Increase stored value of $key by $value while preserving its TTL
304 * @param string $key Key to increase
305 * @param int $value Value to add to $key (Default 1)
306 * @return int|bool New value or false on failure
307 */
308 public function incr( $key, $value = 1 ) {
309 if ( !$this->lock( $key ) ) {
310 return false;
311 }
312 $n = $this->get( $key );
313 if ( $this->isInteger( $n ) ) { // key exists?
314 $n += intval( $value );
315 $this->set( $key, max( 0, $n ) ); // exptime?
316 } else {
317 $n = false;
318 }
319 $this->unlock( $key );
320
321 return $n;
322 }
323
324 /**
325 * Decrease stored value of $key by $value while preserving its TTL
326 * @param string $key
327 * @param int $value
328 * @return int
329 */
330 public function decr( $key, $value = 1 ) {
331 return $this->incr( $key, - $value );
332 }
333
334 /**
335 * Increase stored value of $key by $value while preserving its TTL
336 *
337 * This will create the key with value $init and TTL $ttl if not present
338 *
339 * @param string $key
340 * @param int $ttl
341 * @param int $value
342 * @param int $init
343 * @return bool
344 * @since 1.24
345 */
346 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
347 return $this->incr( $key, $value ) ||
348 $this->add( $key, (int)$init, $ttl ) || $this->incr( $key, $value );
349 }
350
351 /**
352 * Get the "last error" registered; clearLastError() should be called manually
353 * @return int ERR_* constant for the "last error" registry
354 * @since 1.23
355 */
356 public function getLastError() {
357 return $this->lastError;
358 }
359
360 /**
361 * Clear the "last error" registry
362 * @since 1.23
363 */
364 public function clearLastError() {
365 $this->lastError = self::ERR_NONE;
366 }
367
368 /**
369 * Set the "last error" registry
370 * @param int $err ERR_* constant
371 * @since 1.23
372 */
373 protected function setLastError( $err ) {
374 $this->lastError = $err;
375 }
376
377 /**
378 * @param string $text
379 */
380 public function debug( $text ) {
381 if ( $this->debugMode ) {
382 $this->logger->debug( "{class} debug: $text", array(
383 'class' => get_class( $this ),
384 ) );
385 }
386 }
387
388 /**
389 * Convert an optionally relative time to an absolute time
390 * @param int $exptime
391 * @return int
392 */
393 protected function convertExpiry( $exptime ) {
394 if ( ( $exptime != 0 ) && ( $exptime < 86400 * 3650 /* 10 years */ ) ) {
395 return time() + $exptime;
396 } else {
397 return $exptime;
398 }
399 }
400
401 /**
402 * Convert an optionally absolute expiry time to a relative time. If an
403 * absolute time is specified which is in the past, use a short expiry time.
404 *
405 * @param int $exptime
406 * @return int
407 */
408 protected function convertToRelative( $exptime ) {
409 if ( $exptime >= 86400 * 3650 /* 10 years */ ) {
410 $exptime -= time();
411 if ( $exptime <= 0 ) {
412 $exptime = 1;
413 }
414 return $exptime;
415 } else {
416 return $exptime;
417 }
418 }
419
420 /**
421 * Check if a value is an integer
422 *
423 * @param mixed $value
424 * @return bool
425 */
426 protected function isInteger( $value ) {
427 return ( is_int( $value ) || ctype_digit( $value ) );
428 }
429 }