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: A numbered array of either ObjectFactory::getObjectFromSpec
45 * arrays yeilding BagOStuff objects or direct BagOStuff objects.
46 * If using the former, the 'args' field *must* be set.
47 * The first cache is the primary one, being the first to
48 * be read in the fallback chain. Writes happen to all stores
49 * in the order they are defined. However, lock()/unlock() calls
50 * only use the primary store.
51 * - replication: Either 'sync' or 'async'. This controls whether writes to
52 * secondary stores are deferred when possible. Async writes
53 * require the HHVM register_postsend_function() function.
54 * Async writes can increase the chance of some race conditions
55 * or cause keys to expire seconds later than expected. It is
56 * safe to use for modules when cached values: are immutable,
57 * invalidation uses logical TTLs, invalidation uses etag/timestamp
58 * validation against the DB, or merge() is used to handle races.
60 * @param array $params
61 * @throws InvalidArgumentException
63 public function __construct( $params ) {
64 parent
::__construct( $params );
66 if ( empty( $params['caches'] ) ||
!is_array( $params['caches'] ) ) {
67 throw new InvalidArgumentException(
68 __METHOD__
. ': "caches" parameter must be an array of caches'
72 $this->caches
= array();
73 foreach ( $params['caches'] as $cacheInfo ) {
74 if ( $cacheInfo instanceof BagOStuff
) {
75 $this->caches
[] = $cacheInfo;
77 if ( !isset( $cacheInfo['args'] ) ) {
78 // B/C for when $cacheInfo was for ObjectCache::newFromParams().
79 // Callers intenting this to be for ObjectFactory::getObjectFromSpec
80 // should have set "args" per the docs above. Doings so avoids extra
81 // (likely harmless) params (factory/class/calls) ending up in "args".
82 $cacheInfo['args'] = array( $cacheInfo );
84 $this->caches
[] = ObjectFactory
::getObjectFromSpec( $cacheInfo );
88 $this->asyncWrites
= isset( $params['replication'] ) && $params['replication'] === 'async';
94 public function setDebug( $debug ) {
95 $this->doWrite( self
::ALL
, 'setDebug', $debug );
98 protected function doGet( $key, $flags = 0 ) {
99 $misses = 0; // number backends checked
101 foreach ( $this->caches
as $cache ) {
102 $value = $cache->get( $key, $flags );
103 if ( $value !== false ) {
109 if ( $value !== false
111 && ( $flags & self
::READ_VERIFIED
) == self
::READ_VERIFIED
113 $this->doWrite( $misses, 'set', $key, $value, self
::UPGRADE_TTL
);
121 * @param mixed $value
122 * @param int $exptime
125 public function set( $key, $value, $exptime = 0 ) {
126 return $this->doWrite( self
::ALL
, 'set', $key, $value, $exptime );
133 public function delete( $key ) {
134 return $this->doWrite( self
::ALL
, 'delete', $key );
139 * @param mixed $value
140 * @param int $exptime
143 public function add( $key, $value, $exptime = 0 ) {
144 return $this->doWrite( self
::ALL
, 'add', $key, $value, $exptime );
152 public function incr( $key, $value = 1 ) {
153 return $this->doWrite( self
::ALL
, 'incr', $key, $value );
161 public function decr( $key, $value = 1 ) {
162 return $this->doWrite( self
::ALL
, 'decr', $key, $value );
167 * @param int $timeout
169 * @param string $rclass
172 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
173 // Lock only the first cache, to avoid deadlocks
174 return $this->caches
[0]->lock( $key, $timeout, $expiry, $rclass );
181 public function unlock( $key ) {
182 return $this->caches
[0]->unlock( $key );
187 * @param callable $callback Callback method to be executed
188 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
189 * @param int $attempts The amount of times to attempt a merge in case of failure
190 * @return bool Success
192 public function merge( $key, $callback, $exptime = 0, $attempts = 10 ) {
193 return $this->doWrite( self
::ALL
, 'merge', $key, $callback, $exptime );
196 public function getLastError() {
197 return $this->caches
[0]->getLastError();
200 public function clearLastError() {
201 $this->caches
[0]->clearLastError();
205 * Apply a write method to the first $count backing caches
207 * @param integer $count
208 * @param string $method
212 protected function doWrite( $count, $method /*, ... */ ) {
214 $args = array_slice( func_get_args(), 2 );
216 foreach ( $this->caches
as $i => $cache ) {
217 if ( $i >= $count ) {
218 break; // ignore the lower tiers
221 if ( $i == 0 ||
!$this->asyncWrites
) {
222 // First store or in sync mode: write now and get result
223 if ( !call_user_func_array( array( $cache, $method ), $args ) ) {
227 // Secondary write in async mode: do not block this HTTP request
228 $logger = $this->logger
;
229 DeferredUpdates
::addCallableUpdate(
230 function () use ( $cache, $method, $args, $logger ) {
231 if ( !call_user_func_array( array( $cache, $method ), $args ) ) {
232 $logger->warning( "Async $method op failed" );
243 * Delete objects expiring before a certain date.
245 * Succeed if any of the child caches succeed.
246 * @param string $date
247 * @param bool|callable $progressCallback
250 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
252 foreach ( $this->caches
as $cache ) {
253 if ( $cache->deleteObjectsExpiringBefore( $date, $progressCallback ) ) {