Removed unused and poorly supported time argument to BagOStuff::delete
[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 /**
32 * interface is intended to be more or less compatible with
33 * the PHP memcached client.
34 *
35 * backends for local hash array and SQL table included:
36 * <code>
37 * $bag = new HashBagOStuff();
38 * $bag = new SqlBagOStuff(); # connect to db first
39 * </code>
40 *
41 * @ingroup Cache
42 */
43 abstract class BagOStuff {
44 private $debugMode = false;
45
46 protected $lastError = self::ERR_NONE;
47
48 /** Possible values for getLastError() */
49 const ERR_NONE = 0; // no error
50 const ERR_NO_RESPONSE = 1; // no response
51 const ERR_UNREACHABLE = 2; // can't connect
52 const ERR_UNEXPECTED = 3; // response gave some error
53
54 /**
55 * @param bool $bool
56 */
57 public function setDebug( $bool ) {
58 $this->debugMode = $bool;
59 }
60
61 /**
62 * Get an item with the given key. Returns false if it does not exist.
63 * @param string $key
64 * @param mixed $casToken [optional]
65 * @return mixed Returns false on failure
66 */
67 abstract public function get( $key, &$casToken = null );
68
69 /**
70 * Set an item.
71 * @param string $key
72 * @param mixed $value
73 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
74 * @return bool Success
75 */
76 abstract public function set( $key, $value, $exptime = 0 );
77
78 /**
79 * Check and set an item.
80 * @param mixed $casToken
81 * @param string $key
82 * @param mixed $value
83 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
84 * @return bool Success
85 */
86 abstract public function cas( $casToken, $key, $value, $exptime = 0 );
87
88 /**
89 * Delete an item.
90 * @param string $key
91 * @return bool True if the item was deleted or not found, false on failure
92 */
93 abstract public function delete( $key );
94
95 /**
96 * Merge changes into the existing cache value (possibly creating a new one).
97 * The callback function returns the new value given the current value (possibly false),
98 * and takes the arguments: (this BagOStuff object, cache key, current value).
99 *
100 * @param string $key
101 * @param Closure $callback Callback method to be executed
102 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
103 * @param int $attempts The amount of times to attempt a merge in case of failure
104 * @return bool Success
105 */
106 public function merge( $key, Closure $callback, $exptime = 0, $attempts = 10 ) {
107 return $this->mergeViaCas( $key, $callback, $exptime, $attempts );
108 }
109
110 /**
111 * @see BagOStuff::merge()
112 *
113 * @param string $key
114 * @param Closure $callback Callback method to be executed
115 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
116 * @param int $attempts The amount of times to attempt a merge in case of failure
117 * @return bool Success
118 */
119 protected function mergeViaCas( $key, Closure $callback, $exptime = 0, $attempts = 10 ) {
120 do {
121 $casToken = null; // passed by reference
122 $currentValue = $this->get( $key, $casToken ); // get the old value
123 $value = $callback( $this, $key, $currentValue ); // derive the new value
124
125 if ( $value === false ) {
126 $success = true; // do nothing
127 } elseif ( $currentValue === false ) {
128 // Try to create the key, failing if it gets created in the meantime
129 $success = $this->add( $key, $value, $exptime );
130 } else {
131 // Try to update the key, failing if it gets changed in the meantime
132 $success = $this->cas( $casToken, $key, $value, $exptime );
133 }
134 } while ( !$success && --$attempts );
135
136 return $success;
137 }
138
139 /**
140 * @see BagOStuff::merge()
141 *
142 * @param string $key
143 * @param Closure $callback Callback method to be executed
144 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
145 * @param int $attempts The amount of times to attempt a merge in case of failure
146 * @return bool Success
147 */
148 protected function mergeViaLock( $key, Closure $callback, $exptime = 0, $attempts = 10 ) {
149 if ( !$this->lock( $key, 6 ) ) {
150 return false;
151 }
152
153 $currentValue = $this->get( $key ); // get the old value
154 $value = $callback( $this, $key, $currentValue ); // derive the new value
155
156 if ( $value === false ) {
157 $success = true; // do nothing
158 } else {
159 $success = $this->set( $key, $value, $exptime ); // set the new value
160 }
161
162 if ( !$this->unlock( $key ) ) {
163 // this should never happen
164 trigger_error( "Could not release lock for key '$key'." );
165 }
166
167 return $success;
168 }
169
170 /**
171 * @param string $key
172 * @param int $timeout Lock wait timeout [optional]
173 * @param int $expiry Lock expiry [optional]
174 * @return bool Success
175 */
176 public function lock( $key, $timeout = 6, $expiry = 6 ) {
177 $this->clearLastError();
178 $timestamp = microtime( true ); // starting UNIX timestamp
179 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
180 return true;
181 } elseif ( $this->getLastError() ) {
182 return false;
183 }
184
185 $uRTT = ceil( 1e6 * ( microtime( true ) - $timestamp ) ); // estimate RTT (us)
186 $sleep = 2 * $uRTT; // rough time to do get()+set()
187
188 $locked = false; // lock acquired
189 $attempts = 0; // failed attempts
190 do {
191 if ( ++$attempts >= 3 && $sleep <= 1e6 ) {
192 // Exponentially back off after failed attempts to avoid network spam.
193 // About 2*$uRTT*(2^n-1) us of "sleep" happen for the next n attempts.
194 $sleep *= 2;
195 }
196 usleep( $sleep ); // back off
197 $this->clearLastError();
198 $locked = $this->add( "{$key}:lock", 1, $expiry );
199 if ( $this->getLastError() ) {
200 return false;
201 }
202 } while ( !$locked && ( microtime( true ) - $timestamp ) < $timeout );
203
204 return $locked;
205 }
206
207 /**
208 * @param string $key
209 * @return bool Success
210 */
211 public function unlock( $key ) {
212 return $this->delete( "{$key}:lock" );
213 }
214
215 /**
216 * Delete all objects expiring before a certain date.
217 * @param string $date The reference date in MW format
218 * @param callable|bool $progressCallback Optional, a function which will be called
219 * regularly during long-running operations with the percentage progress
220 * as the first parameter.
221 *
222 * @return bool Success, false if unimplemented
223 */
224 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
225 // stub
226 return false;
227 }
228
229 /* *** Emulated functions *** */
230
231 /**
232 * Get an associative array containing the item for each of the keys that have items.
233 * @param array $keys List of strings
234 * @return array
235 */
236 public function getMulti( array $keys ) {
237 $res = array();
238 foreach ( $keys as $key ) {
239 $val = $this->get( $key );
240 if ( $val !== false ) {
241 $res[$key] = $val;
242 }
243 }
244 return $res;
245 }
246
247 /**
248 * Batch insertion
249 * @param array $data $key => $value assoc array
250 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
251 * @return bool Success
252 * @since 1.24
253 */
254 public function setMulti( array $data, $exptime = 0 ) {
255 $res = true;
256 foreach ( $data as $key => $value ) {
257 if ( !$this->set( $key, $value, $exptime ) ) {
258 $res = false;
259 }
260 }
261 return $res;
262 }
263
264 /**
265 * @param string $key
266 * @param mixed $value
267 * @param int $exptime
268 * @return bool Success
269 */
270 public function add( $key, $value, $exptime = 0 ) {
271 if ( $this->get( $key ) === false ) {
272 return $this->set( $key, $value, $exptime );
273 }
274 return false; // key already set
275 }
276
277 /**
278 * Increase stored value of $key by $value while preserving its TTL
279 * @param string $key Key to increase
280 * @param int $value Value to add to $key (Default 1)
281 * @return int|bool New value or false on failure
282 */
283 public function incr( $key, $value = 1 ) {
284 if ( !$this->lock( $key ) ) {
285 return false;
286 }
287 $n = $this->get( $key );
288 if ( $this->isInteger( $n ) ) { // key exists?
289 $n += intval( $value );
290 $this->set( $key, max( 0, $n ) ); // exptime?
291 } else {
292 $n = false;
293 }
294 $this->unlock( $key );
295
296 return $n;
297 }
298
299 /**
300 * Decrease stored value of $key by $value while preserving its TTL
301 * @param string $key
302 * @param int $value
303 * @return int
304 */
305 public function decr( $key, $value = 1 ) {
306 return $this->incr( $key, - $value );
307 }
308
309 /**
310 * Increase stored value of $key by $value while preserving its TTL
311 *
312 * This will create the key with value $init and TTL $ttl if not present
313 *
314 * @param string $key
315 * @param int $ttl
316 * @param int $value
317 * @param int $init
318 * @return bool
319 * @since 1.24
320 */
321 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
322 return $this->incr( $key, $value ) ||
323 $this->add( $key, (int)$init, $ttl ) || $this->incr( $key, $value );
324 }
325
326 /**
327 * Get the "last error" registered; clearLastError() should be called manually
328 * @return int ERR_* constant for the "last error" registry
329 * @since 1.23
330 */
331 public function getLastError() {
332 return $this->lastError;
333 }
334
335 /**
336 * Clear the "last error" registry
337 * @since 1.23
338 */
339 public function clearLastError() {
340 $this->lastError = self::ERR_NONE;
341 }
342
343 /**
344 * Set the "last error" registry
345 * @param int $err ERR_* constant
346 * @since 1.23
347 */
348 protected function setLastError( $err ) {
349 $this->lastError = $err;
350 }
351
352 /**
353 * @param string $text
354 */
355 public function debug( $text ) {
356 if ( $this->debugMode ) {
357 $class = get_class( $this );
358 wfDebug( "$class debug: $text\n" );
359 }
360 }
361
362 /**
363 * Convert an optionally relative time to an absolute time
364 * @param int $exptime
365 * @return int
366 */
367 protected function convertExpiry( $exptime ) {
368 if ( ( $exptime != 0 ) && ( $exptime < 86400 * 3650 /* 10 years */ ) ) {
369 return time() + $exptime;
370 } else {
371 return $exptime;
372 }
373 }
374
375 /**
376 * Convert an optionally absolute expiry time to a relative time. If an
377 * absolute time is specified which is in the past, use a short expiry time.
378 *
379 * @param int $exptime
380 * @return int
381 */
382 protected function convertToRelative( $exptime ) {
383 if ( $exptime >= 86400 * 3650 /* 10 years */ ) {
384 $exptime -= time();
385 if ( $exptime <= 0 ) {
386 $exptime = 1;
387 }
388 return $exptime;
389 } else {
390 return $exptime;
391 }
392 }
393
394 /**
395 * Check if a value is an integer
396 *
397 * @param mixed $value
398 * @return bool
399 */
400 protected function isInteger( $value ) {
401 return ( is_int( $value ) || ctype_digit( $value ) );
402 }
403 }