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