3 * Wrapper for object caching in different caches.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * A cache class that replicates all writes to multiple child caches. Reads
26 * are implemented by reading from the caches in the order they are given in
27 * the configuration until a cache gives a positive result.
31 class MultiWriteBagOStuff
extends BagOStuff
{
32 /** @var BagOStuff[] */
34 /** @var bool Use async secondary writes */
35 protected $asyncWrites = false;
37 /** Idiom for "write to all backends" */
40 const UPGRADE_TTL
= 3600; // TTL when a key is copied to a higher cache tier
44 * - caches: This should have a numbered array of cache parameter
45 * structures, in the style required by $wgObjectCaches. See
46 * the documentation of $wgObjectCaches for more detail.
47 * BagOStuff objects can also be used as values.
48 * The first cache is the primary one, being the first to
49 * be read in the fallback chain. Writes happen to all stores
50 * in the order they are defined. However, lock()/unlock() calls
51 * only use the primary store.
52 * - replication: Either 'sync' or 'async'. This controls whether writes to
53 * secondary stores are deferred when possible. Async writes
54 * require the HHVM register_postsend_function() function.
55 * Async writes can increase the chance of some race conditions
56 * or cause keys to expire seconds later than expected. It is
57 * safe to use for modules when cached values: are immutable,
58 * invalidation uses logical TTLs, invalidation uses etag/timestamp
59 * validation against the DB, or merge() is used to handle races.
61 * @param array $params
62 * @throws InvalidArgumentException
64 public function __construct( $params ) {
65 parent
::__construct( $params );
67 if ( empty( $params['caches'] ) ||
!is_array( $params['caches'] ) ) {
68 throw new InvalidArgumentException(
69 __METHOD__
. ': "caches" parameter must be an array of caches'
73 $this->caches
= array();
74 foreach ( $params['caches'] as $cacheInfo ) {
75 $this->caches
[] = ( $cacheInfo instanceof BagOStuff
)
77 : ObjectCache
::newFromParams( $cacheInfo );
80 $this->asyncWrites
= isset( $params['replication'] ) && $params['replication'] === 'async';
86 public function setDebug( $debug ) {
87 $this->doWrite( self
::ALL
, 'setDebug', $debug );
90 protected function doGet( $key, $flags = 0 ) {
91 $misses = 0; // number backends checked
93 foreach ( $this->caches
as $cache ) {
94 $value = $cache->get( $key, $flags );
95 if ( $value !== false ) {
101 if ( $value !== false
103 && ( $flags & self
::READ_VERIFIED
) == self
::READ_VERIFIED
105 $this->doWrite( $misses, 'set', $key, $value, self
::UPGRADE_TTL
);
113 * @param mixed $value
114 * @param int $exptime
117 public function set( $key, $value, $exptime = 0 ) {
118 return $this->doWrite( self
::ALL
, 'set', $key, $value, $exptime );
125 public function delete( $key ) {
126 return $this->doWrite( self
::ALL
, 'delete', $key );
131 * @param mixed $value
132 * @param int $exptime
135 public function add( $key, $value, $exptime = 0 ) {
136 return $this->doWrite( self
::ALL
, 'add', $key, $value, $exptime );
144 public function incr( $key, $value = 1 ) {
145 return $this->doWrite( self
::ALL
, 'incr', $key, $value );
153 public function decr( $key, $value = 1 ) {
154 return $this->doWrite( self
::ALL
, 'decr', $key, $value );
159 * @param int $timeout
161 * @param string $rclass
164 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
165 // Lock only the first cache, to avoid deadlocks
166 return $this->caches
[0]->lock( $key, $timeout, $expiry, $rclass );
173 public function unlock( $key ) {
174 return $this->caches
[0]->unlock( $key );
179 * @param callable $callback Callback method to be executed
180 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
181 * @param int $attempts The amount of times to attempt a merge in case of failure
182 * @return bool Success
184 public function merge( $key, $callback, $exptime = 0, $attempts = 10 ) {
185 return $this->doWrite( self
::ALL
, 'merge', $key, $callback, $exptime );
188 public function getLastError() {
189 return $this->caches
[0]->getLastError();
192 public function clearLastError() {
193 $this->caches
[0]->clearLastError();
197 * Apply a write method to the first $count backing caches
199 * @param integer $count
200 * @param string $method
204 protected function doWrite( $count, $method /*, ... */ ) {
206 $args = array_slice( func_get_args(), 2 );
208 foreach ( $this->caches
as $i => $cache ) {
209 if ( $i >= $count ) {
210 break; // ignore the lower tiers
213 if ( $i == 0 ||
!$this->asyncWrites
) {
214 // First store or in sync mode: write now and get result
215 if ( !call_user_func_array( array( $cache, $method ), $args ) ) {
219 // Secondary write in async mode: do not block this HTTP request
220 $logger = $this->logger
;
221 DeferredUpdates
::addCallableUpdate(
222 function () use ( $cache, $method, $args, $logger ) {
223 if ( !call_user_func_array( array( $cache, $method ), $args ) ) {
224 $logger->warning( "Async $method op failed" );
235 * Delete objects expiring before a certain date.
237 * Succeed if any of the child caches succeed.
238 * @param string $date
239 * @param bool|callable $progressCallback
242 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
244 foreach ( $this->caches
as $cache ) {
245 if ( $cache->deleteObjectsExpiringBefore( $date, $progressCallback ) ) {