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