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
23 use Wikimedia\ObjectFactory
;
26 * A cache class that replicates all writes to multiple child caches. Reads
27 * are implemented by reading from the caches in the order they are given in
28 * the configuration until a cache gives a positive result.
32 class MultiWriteBagOStuff
extends BagOStuff
{
33 /** @var BagOStuff[] */
35 /** @var bool Use async secondary writes */
36 protected $asyncWrites = false;
38 /** Idiom for "write to all backends" */
41 const UPGRADE_TTL
= 3600; // TTL when a key is copied to a higher cache tier
45 * - caches: A numbered array of either ObjectFactory::getObjectFromSpec
46 * arrays yeilding BagOStuff objects or direct BagOStuff objects.
47 * If using the former, the 'args' field *must* be set.
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
53 * to secondary stores are deferred when possible. Async writes
54 * require setting 'asyncHandler'. 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.
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'
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'] = [ $cacheInfo ];
84 $this->caches
[] = ObjectFactory
::getObjectFromSpec( $cacheInfo );
87 $this->mergeFlagMaps( $this->caches
);
89 $this->asyncWrites
= (
90 isset( $params['replication'] ) &&
91 $params['replication'] === 'async' &&
92 is_callable( $this->asyncHandler
)
96 public function setDebug( $debug ) {
97 foreach ( $this->caches
as $cache ) {
98 $cache->setDebug( $debug );
102 protected function doGet( $key, $flags = 0 ) {
103 if ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
) {
104 // If the latest write was a delete(), we do NOT want to fallback
105 // to the other tiers and possibly see the old value. Also, this
106 // is used by mergeViaLock(), which only needs to hit the primary.
107 return $this->caches
[0]->get( $key, $flags );
110 $misses = 0; // number backends checked
112 foreach ( $this->caches
as $cache ) {
113 $value = $cache->get( $key, $flags );
114 if ( $value !== false ) {
120 if ( $value !== false
122 && ( $flags & self
::READ_VERIFIED
) == self
::READ_VERIFIED
124 $this->doWrite( $misses, $this->asyncWrites
, 'set', $key, $value, self
::UPGRADE_TTL
);
130 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
131 $asyncWrites = ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
)
133 : $this->asyncWrites
;
135 return $this->doWrite( self
::ALL
, $asyncWrites, 'set', $key, $value, $exptime );
138 public function delete( $key ) {
139 return $this->doWrite( self
::ALL
, $this->asyncWrites
, 'delete', $key );
142 public function add( $key, $value, $exptime = 0 ) {
143 return $this->doWrite( self
::ALL
, $this->asyncWrites
, 'add', $key, $value, $exptime );
146 public function incr( $key, $value = 1 ) {
147 return $this->doWrite( self
::ALL
, $this->asyncWrites
, 'incr', $key, $value );
150 public function decr( $key, $value = 1 ) {
151 return $this->doWrite( self
::ALL
, $this->asyncWrites
, 'decr', $key, $value );
154 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
155 // Only need to lock the first cache; also avoids deadlocks
156 return $this->caches
[0]->lock( $key, $timeout, $expiry, $rclass );
159 public function unlock( $key ) {
160 // Only the first cache is locked
161 return $this->caches
[0]->unlock( $key );
164 public function getLastError() {
165 return $this->caches
[0]->getLastError();
168 public function clearLastError() {
169 $this->caches
[0]->clearLastError();
173 * Apply a write method to the first $count backing caches
176 * @param bool $asyncWrites
177 * @param string $method
178 * @param mixed $args,...
181 protected function doWrite( $count, $asyncWrites, $method /*, ... */ ) {
183 $args = array_slice( func_get_args(), 3 );
185 if ( $count > 1 && $asyncWrites ) {
186 // Deep-clone $args to prevent misbehavior when something writes an
187 // object to the BagOStuff then modifies it afterwards, e.g. T168040.
188 $args = unserialize( serialize( $args ) );
191 foreach ( $this->caches
as $i => $cache ) {
192 if ( $i >= $count ) {
193 break; // ignore the lower tiers
196 if ( $i == 0 ||
!$asyncWrites ) {
197 // First store or in sync mode: write now and get result
198 if ( !call_user_func_array( [ $cache, $method ], $args ) ) {
202 // Secondary write in async mode: do not block this HTTP request
203 $logger = $this->logger
;
206 function () use ( $cache, $method, $args, $logger ) {
207 if ( !call_user_func_array( [ $cache, $method ], $args ) ) {
208 $logger->warning( "Async $method op failed" );
219 * Delete objects expiring before a certain date.
221 * Succeed if any of the child caches succeed.
222 * @param string $date
223 * @param bool|callable $progressCallback
226 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
228 foreach ( $this->caches
as $cache ) {
229 if ( $cache->deleteObjectsExpiringBefore( $date, $progressCallback ) ) {
237 public function makeKey( $class, $component = null ) {
238 return call_user_func_array( [ $this->caches
[0], __FUNCTION__
], func_get_args() );
241 public function makeGlobalKey( $class, $component = null ) {
242 return call_user_func_array( [ $this->caches
[0], __FUNCTION__
], func_get_args() );