Tidy up the class
[mediawiki.git] / includes / BagOStuff.php
blobac0263d8340604c4989273960bf9f3e5c873c141
1 <?php
3 # Copyright (C) 2003-2004 Brion Vibber <brion@pobox.com>
4 # http://www.mediawiki.org/
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along
17 # with this program; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 # http://www.gnu.org/copyleft/gpl.html
21 /**
22 * @defgroup Cache Cache
24 * @file
25 * @ingroup Cache
28 /**
29 * interface is intended to be more or less compatible with
30 * the PHP memcached client.
32 * backends for local hash array and SQL table included:
33 * <code>
34 * $bag = new HashBagOStuff();
35 * $bag = new SqlBagOStuff(); # connect to db first
36 * </code>
38 * @ingroup Cache
40 abstract class BagOStuff {
41 var $debugMode = false;
43 public function set_debug( $bool ) {
44 $this->debugMode = $bool;
47 /* *** THE GUTS OF THE OPERATION *** */
48 /* Override these with functional things in subclasses */
50 /**
51 * Get an item with the given key. Returns false if it does not exist.
52 * @param $key string
54 abstract public function get( $key );
56 /**
57 * Set an item.
58 * @param $key string
59 * @param $value mixed
60 * @param $exptime int Either an interval in seconds or a unix timestamp for expiry
62 abstract public function set( $key, $value, $exptime = 0 );
65 * Delete an item.
66 * @param $key string
67 * @param $time int Amount of time to delay the operation (mostly memcached-specific)
69 abstract public function delete( $key, $time = 0 );
71 public function lock( $key, $timeout = 0 ) {
72 /* stub */
73 return true;
76 public function unlock( $key ) {
77 /* stub */
78 return true;
81 public function keys() {
82 /* stub */
83 return array();
86 /* *** Emulated functions *** */
87 /* Better performance can likely be got with custom written versions */
88 public function get_multi( $keys ) {
89 $out = array();
91 foreach ( $keys as $key ) {
92 $out[$key] = $this->get( $key );
95 return $out;
98 public function set_multi( $hash, $exptime = 0 ) {
99 foreach ( $hash as $key => $value ) {
100 $this->set( $key, $value, $exptime );
104 public function add( $key, $value, $exptime = 0 ) {
105 if ( $this->get( $key ) == false ) {
106 $this->set( $key, $value, $exptime );
107 return true;
111 public function add_multi( $hash, $exptime = 0 ) {
112 foreach ( $hash as $key => $value ) {
113 $this->add( $key, $value, $exptime );
117 public function delete_multi( $keys, $time = 0 ) {
118 foreach ( $keys as $key ) {
119 $this->delete( $key, $time );
123 public function replace( $key, $value, $exptime = 0 ) {
124 if ( $this->get( $key ) !== false ) {
125 $this->set( $key, $value, $exptime );
129 public function incr( $key, $value = 1 ) {
130 if ( !$this->lock( $key ) ) {
131 return false;
133 $value = intval( $value );
135 $n = false;
136 if ( ( $n = $this->get( $key ) ) !== false ) {
137 $n += $value;
138 $this->set( $key, $n ); // exptime?
140 $this->unlock( $key );
141 return $n;
144 public function decr( $key, $value = 1 ) {
145 return $this->incr( $key, - $value );
148 public function debug( $text ) {
149 if ( $this->debugMode )
150 wfDebug( "BagOStuff debug: $text\n" );
154 * Convert an optionally relative time to an absolute time
156 protected function convertExpiry( $exptime ) {
157 if ( ( $exptime != 0 ) && ( $exptime < 3600 * 24 * 30 ) ) {
158 return time() + $exptime;
159 } else {
160 return $exptime;
166 * Functional versions!
167 * This is a test of the interface, mainly. It stores things in an associative
168 * array, which is not going to persist between program runs.
170 * @ingroup Cache
172 class HashBagOStuff extends BagOStuff {
173 var $bag;
175 function __construct() {
176 $this->bag = array();
179 protected function expire( $key ) {
180 $et = $this->bag[$key][1];
181 if ( ( $et == 0 ) || ( $et > time() ) ) {
182 return false;
184 $this->delete( $key );
185 return true;
188 function get( $key ) {
189 if ( !isset( $this->bag[$key] ) ) {
190 return false;
192 if ( $this->expire( $key ) ) {
193 return false;
195 return $this->bag[$key][0];
198 function set( $key, $value, $exptime = 0 ) {
199 $this->bag[$key] = array( $value, $this->convertExpiry( $exptime ) );
202 function delete( $key, $time = 0 ) {
203 if ( !isset( $this->bag[$key] ) ) {
204 return false;
206 unset( $this->bag[$key] );
207 return true;
210 function keys() {
211 return array_keys( $this->bag );
216 * Class to store objects in the database
218 * @ingroup Cache
220 class SqlBagOStuff extends BagOStuff {
221 var $lb, $db;
222 var $lastExpireAll = 0;
224 protected function getDB() {
225 global $wgDBtype;
226 if ( !isset( $this->db ) ) {
227 /* We must keep a separate connection to MySQL in order to avoid deadlocks
228 * However, SQLite has an opposite behaviour.
229 * @todo Investigate behaviour for other databases
231 if ( $wgDBtype == 'sqlite' ) {
232 $this->db = wfGetDB( DB_MASTER );
233 } else {
234 $this->lb = wfGetLBFactory()->newMainLB();
235 $this->db = $this->lb->getConnection( DB_MASTER );
236 $this->db->clearFlag( DBO_TRX );
239 return $this->db;
242 public function get( $key ) {
243 # expire old entries if any
244 $this->garbageCollect();
245 $db = $this->getDB();
246 $row = $db->selectRow( 'objectcache', array( 'value', 'exptime' ),
247 array( 'keyname' => $key ), __METHOD__ );
248 if ( !$row ) {
249 $this->debug( 'get: no matching rows' );
250 return false;
253 $this->debug( "get: retrieved data; expiry time is " . $row->exptime );
254 if ( $this->isExpired( $row->exptime ) ) {
255 $this->debug( "get: key has expired, deleting" );
256 try {
257 $db->begin();
258 # Put the expiry time in the WHERE condition to avoid deleting a
259 # newly-inserted value
260 $db->delete( 'objectcache',
261 array(
262 'keyname' => $key,
263 'exptime' => $row->exptime
264 ), __METHOD__ );
265 $db->commit();
266 } catch ( DBQueryError $e ) {
267 $this->handleWriteError( $e );
269 return false;
271 return $this->unserialize( $db->decodeBlob( $row->value ) );
274 public function set( $key, $value, $exptime = 0 ) {
275 $db = $this->getDB();
276 $exptime = intval( $exptime );
277 if ( $exptime < 0 ) $exptime = 0;
278 if ( $exptime == 0 ) {
279 $encExpiry = $this->getMaxDateTime();
280 } else {
281 if ( $exptime < 3.16e8 ) # ~10 years
282 $exptime += time();
283 $encExpiry = $db->timestamp( $exptime );
285 try {
286 $db->begin();
287 $db->delete( 'objectcache', array( 'keyname' => $key ), __METHOD__ );
288 $db->insert( 'objectcache',
289 array(
290 'keyname' => $key,
291 'value' => $db->encodeBlob( $this->serialize( $value ) ),
292 'exptime' => $encExpiry
293 ), __METHOD__ );
294 $db->commit();
295 } catch ( DBQueryError $e ) {
296 $this->handleWriteError( $e );
297 return false;
299 return true;
302 public function delete( $key, $time = 0 ) {
303 $db = $this->getDB();
304 try {
305 $db->begin();
306 $db->delete( 'objectcache', array( 'keyname' => $key ), __METHOD__ );
307 $db->commit();
308 } catch ( DBQueryError $e ) {
309 $this->handleWriteError( $e );
310 return false;
312 return true;
315 public function incr( $key, $step = 1 ) {
316 $db = $this->getDB();
317 $step = intval( $step );
319 try {
320 $db->begin();
321 $row = $db->selectRow( 'objectcache', array( 'value', 'exptime' ),
322 array( 'keyname' => $key ), __METHOD__, array( 'FOR UPDATE' ) );
323 if ( $row === false ) {
324 // Missing
325 $db->commit();
326 return false;
328 $db->delete( 'objectcache', array( 'keyname' => $key ), __METHOD__ );
329 if ( $this->isExpired( $row->exptime ) ) {
330 // Expired, do not reinsert
331 $db->commit();
332 return false;
335 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value ) ) );
336 $newValue = $oldValue + $step;
337 $db->insert( 'objectcache',
338 array(
339 'keyname' => $key,
340 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
341 'exptime' => $row->exptime
342 ), __METHOD__ );
343 $db->commit();
344 } catch ( DBQueryError $e ) {
345 $this->handleWriteError( $e );
346 return false;
348 return $newValue;
351 public function keys() {
352 $db = $this->getDB();
353 $res = $db->select( 'objectcache', array( 'keyname' ), false, __METHOD__ );
354 $result = array();
355 foreach ( $res as $row ) {
356 $result[] = $row->keyname;
358 return $result;
361 protected function isExpired( $exptime ) {
362 return $exptime != $this->getMaxDateTime() && wfTimestamp( TS_UNIX, $exptime ) < time();
365 protected function getMaxDateTime() {
366 if ( time() > 0x7fffffff ) {
367 return $this->getDB()->timestamp( 1 << 62 );
368 } else {
369 return $this->getDB()->timestamp( 0x7fffffff );
373 protected function garbageCollect() {
374 /* Ignore 99% of requests */
375 if ( !mt_rand( 0, 100 ) ) {
376 $now = time();
377 /* Avoid repeating the delete within a few seconds */
378 if ( $now > ( $this->lastExpireAll + 1 ) ) {
379 $this->lastExpireAll = $now;
380 $this->expireAll();
385 public function expireAll() {
386 $db = $this->getDB();
387 $now = $db->timestamp();
388 try {
389 $db->begin();
390 $db->delete( 'objectcache', array( 'exptime < ' . $db->addQuotes( $now ) ), __METHOD__ );
391 $db->commit();
392 } catch ( DBQueryError $e ) {
393 $this->handleWriteError( $e );
397 public function deleteAll() {
398 $db = $this->getDB();
399 try {
400 $db->begin();
401 $db->delete( 'objectcache', '*', __METHOD__ );
402 $db->commit();
403 } catch ( DBQueryError $e ) {
404 $this->handleWriteError( $e );
409 * Serialize an object and, if possible, compress the representation.
410 * On typical message and page data, this can provide a 3X decrease
411 * in storage requirements.
413 * @param $data mixed
414 * @return string
416 protected function serialize( &$data ) {
417 $serial = serialize( $data );
418 if ( function_exists( 'gzdeflate' ) ) {
419 return gzdeflate( $serial );
420 } else {
421 return $serial;
426 * Unserialize and, if necessary, decompress an object.
427 * @param $serial string
428 * @return mixed
430 protected function unserialize( $serial ) {
431 if ( function_exists( 'gzinflate' ) ) {
432 $decomp = @gzinflate( $serial );
433 if ( false !== $decomp ) {
434 $serial = $decomp;
437 $ret = unserialize( $serial );
438 return $ret;
442 * Handle a DBQueryError which occurred during a write operation.
443 * Ignore errors which are due to a read-only database, rethrow others.
445 protected function handleWriteError( $exception ) {
446 $db = $this->getDB();
447 if ( !$db->wasReadOnlyError() ) {
448 throw $exception;
450 try {
451 $db->rollback();
452 } catch ( DBQueryError $e ) {
454 wfDebug( __METHOD__ . ": ignoring query error\n" );
455 $db->ignoreErrors( false );
460 * Backwards compatibility alias
462 class MediaWikiBagOStuff extends SqlBagOStuff { }
465 * This is a wrapper for APC's shared memory functions
467 * @ingroup Cache
469 class APCBagOStuff extends BagOStuff {
470 public function get( $key ) {
471 $val = apc_fetch( $key );
472 if ( is_string( $val ) ) {
473 $val = unserialize( $val );
475 return $val;
478 public function set( $key, $value, $exptime = 0 ) {
479 apc_store( $key, serialize( $value ), $exptime );
480 return true;
483 public function delete( $key, $time = 0 ) {
484 apc_delete( $key );
485 return true;
488 public function keys() {
489 $info = apc_cache_info( 'user' );
490 $list = $info['cache_list'];
491 $keys = array();
492 foreach ( $list as $entry ) {
493 $keys[] = $entry['info'];
495 return $keys;
500 * This is a wrapper for eAccelerator's shared memory functions.
502 * This is basically identical to the deceased Turck MMCache version,
503 * mostly because eAccelerator is based on Turck MMCache.
505 * @ingroup Cache
507 class eAccelBagOStuff extends BagOStuff {
508 public function get( $key ) {
509 $val = eaccelerator_get( $key );
510 if ( is_string( $val ) ) {
511 $val = unserialize( $val );
513 return $val;
516 public function set( $key, $value, $exptime = 0 ) {
517 eaccelerator_put( $key, serialize( $value ), $exptime );
518 return true;
521 public function delete( $key, $time = 0 ) {
522 eaccelerator_rm( $key );
523 return true;
526 public function lock( $key, $waitTimeout = 0 ) {
527 eaccelerator_lock( $key );
528 return true;
531 public function unlock( $key ) {
532 eaccelerator_unlock( $key );
533 return true;
538 * Wrapper for XCache object caching functions; identical interface
539 * to the APC wrapper
541 * @ingroup Cache
543 class XCacheBagOStuff extends BagOStuff {
546 * Get a value from the XCache object cache
548 * @param $key String: cache key
549 * @return mixed
551 public function get( $key ) {
552 $val = xcache_get( $key );
553 if ( is_string( $val ) )
554 $val = unserialize( $val );
555 return $val;
559 * Store a value in the XCache object cache
561 * @param $key String: cache key
562 * @param $value Mixed: object to store
563 * @param $expire Int: expiration time
564 * @return bool
566 public function set( $key, $value, $expire = 0 ) {
567 xcache_set( $key, serialize( $value ), $expire );
568 return true;
572 * Remove a value from the XCache object cache
574 * @param $key String: cache key
575 * @param $time Int: not used in this implementation
576 * @return bool
578 public function delete( $key, $time = 0 ) {
579 xcache_unset( $key );
580 return true;
585 * Cache that uses DBA as a backend.
586 * Slow due to the need to constantly open and close the file to avoid holding
587 * writer locks. Intended for development use only, as a memcached workalike
588 * for systems that don't have it.
590 * @ingroup Cache
592 class DBABagOStuff extends BagOStuff {
593 var $mHandler, $mFile, $mReader, $mWriter, $mDisabled;
595 public function __construct( $dir = false ) {
596 global $wgDBAhandler;
597 if ( $dir === false ) {
598 global $wgTmpDirectory;
599 $dir = $wgTmpDirectory;
601 $this->mFile = "$dir/mw-cache-" . wfWikiID();
602 $this->mFile .= '.db';
603 wfDebug( __CLASS__ . ": using cache file {$this->mFile}\n" );
604 $this->mHandler = $wgDBAhandler;
608 * Encode value and expiry for storage
610 function encode( $value, $expiry ) {
611 # Convert to absolute time
612 $expiry = $this->convertExpiry( $expiry );
613 return sprintf( '%010u', intval( $expiry ) ) . ' ' . serialize( $value );
617 * @return list containing value first and expiry second
619 function decode( $blob ) {
620 if ( !is_string( $blob ) ) {
621 return array( null, 0 );
622 } else {
623 return array(
624 unserialize( substr( $blob, 11 ) ),
625 intval( substr( $blob, 0, 10 ) )
630 function getReader() {
631 if ( file_exists( $this->mFile ) ) {
632 $handle = dba_open( $this->mFile, 'rl', $this->mHandler );
633 } else {
634 $handle = $this->getWriter();
636 if ( !$handle ) {
637 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
639 return $handle;
642 function getWriter() {
643 $handle = dba_open( $this->mFile, 'cl', $this->mHandler );
644 if ( !$handle ) {
645 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
647 return $handle;
650 function get( $key ) {
651 wfProfileIn( __METHOD__ );
652 wfDebug( __METHOD__ . "($key)\n" );
653 $handle = $this->getReader();
654 if ( !$handle ) {
655 return null;
657 $val = dba_fetch( $key, $handle );
658 list( $val, $expiry ) = $this->decode( $val );
659 # Must close ASAP because locks are held
660 dba_close( $handle );
662 if ( !is_null( $val ) && $expiry && $expiry < time() ) {
663 # Key is expired, delete it
664 $handle = $this->getWriter();
665 dba_delete( $key, $handle );
666 dba_close( $handle );
667 wfDebug( __METHOD__ . ": $key expired\n" );
668 $val = null;
670 wfProfileOut( __METHOD__ );
671 return $val;
674 function set( $key, $value, $exptime = 0 ) {
675 wfProfileIn( __METHOD__ );
676 wfDebug( __METHOD__ . "($key)\n" );
677 $blob = $this->encode( $value, $exptime );
678 $handle = $this->getWriter();
679 if ( !$handle ) {
680 return false;
682 $ret = dba_replace( $key, $blob, $handle );
683 dba_close( $handle );
684 wfProfileOut( __METHOD__ );
685 return $ret;
688 function delete( $key, $time = 0 ) {
689 wfProfileIn( __METHOD__ );
690 wfDebug( __METHOD__ . "($key)\n" );
691 $handle = $this->getWriter();
692 if ( !$handle ) {
693 return false;
695 $ret = dba_delete( $key, $handle );
696 dba_close( $handle );
697 wfProfileOut( __METHOD__ );
698 return $ret;
701 function add( $key, $value, $exptime = 0 ) {
702 wfProfileIn( __METHOD__ );
703 $blob = $this->encode( $value, $exptime );
704 $handle = $this->getWriter();
705 if ( !$handle ) {
706 return false;
708 $ret = dba_insert( $key, $blob, $handle );
709 # Insert failed, check to see if it failed due to an expired key
710 if ( !$ret ) {
711 list( $value, $expiry ) = $this->decode( dba_fetch( $key, $handle ) );
712 if ( $expiry < time() ) {
713 # Yes expired, delete and try again
714 dba_delete( $key, $handle );
715 $ret = dba_insert( $key, $blob, $handle );
716 # This time if it failed then it will be handled by the caller like any other race
720 dba_close( $handle );
721 wfProfileOut( __METHOD__ );
722 return $ret;
725 function keys() {
726 $reader = $this->getReader();
727 $k1 = dba_firstkey( $reader );
728 if ( !$k1 ) {
729 return array();
731 $result[] = $k1;
732 while ( $key = dba_nextkey( $reader ) ) {
733 $result[] = $key;
735 return $result;