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.
30 * Note that cache key construction will use the first cache backend in the list,
31 * so make sure that the other backends can handle such keys (e.g. via encoding).
35 class MultiWriteBagOStuff
extends BagOStuff
{
36 /** @var BagOStuff[] */
38 /** @var bool Use async secondary writes */
39 protected $asyncWrites = false;
40 /** @var int[] List of all backing cache indexes */
41 protected $cacheIndexes = [];
43 const UPGRADE_TTL
= 3600; // TTL when a key is copied to a higher cache tier
47 * - caches: A numbered array of either ObjectFactory::getObjectFromSpec
48 * arrays yeilding BagOStuff objects or direct BagOStuff objects.
49 * If using the former, the 'args' field *must* be set.
50 * The first cache is the primary one, being the first to
51 * be read in the fallback chain. Writes happen to all stores
52 * in the order they are defined. However, lock()/unlock() calls
53 * only use the primary store.
54 * - replication: Either 'sync' or 'async'. This controls whether writes
55 * to secondary stores are deferred when possible. Async writes
56 * require setting 'asyncHandler'. HHVM register_postsend_function() function.
57 * Async writes can increase the chance of some race conditions
58 * or cause keys to expire seconds later than expected. It is
59 * safe to use for modules when cached values: are immutable,
60 * invalidation uses logical TTLs, invalidation uses etag/timestamp
61 * validation against the DB, or merge() is used to handle races.
62 * @param array $params
63 * @throws InvalidArgumentException
65 public function __construct( $params ) {
66 parent
::__construct( $params );
68 if ( empty( $params['caches'] ) ||
!is_array( $params['caches'] ) ) {
69 throw new InvalidArgumentException(
70 __METHOD__
. ': "caches" parameter must be an array of caches'
75 foreach ( $params['caches'] as $cacheInfo ) {
76 if ( $cacheInfo instanceof BagOStuff
) {
77 $this->caches
[] = $cacheInfo;
79 if ( !isset( $cacheInfo['args'] ) ) {
80 // B/C for when $cacheInfo was for ObjectCache::newFromParams().
81 // Callers intenting this to be for ObjectFactory::getObjectFromSpec
82 // should have set "args" per the docs above. Doings so avoids extra
83 // (likely harmless) params (factory/class/calls) ending up in "args".
84 $cacheInfo['args'] = [ $cacheInfo ];
86 $this->caches
[] = ObjectFactory
::getObjectFromSpec( $cacheInfo );
89 $this->mergeFlagMaps( $this->caches
);
91 $this->asyncWrites
= (
92 isset( $params['replication'] ) &&
93 $params['replication'] === 'async' &&
94 is_callable( $this->asyncHandler
)
97 $this->cacheIndexes
= array_keys( $this->caches
);
100 public function setDebug( $debug ) {
101 foreach ( $this->caches
as $cache ) {
102 $cache->setDebug( $debug );
106 public function get( $key, $flags = 0 ) {
107 if ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
) {
108 // If the latest write was a delete(), we do NOT want to fallback
109 // to the other tiers and possibly see the old value. Also, this
110 // is used by merge(), which only needs to hit the primary.
111 return $this->caches
[0]->get( $key, $flags );
115 $missIndexes = []; // backends checked
116 foreach ( $this->caches
as $i => $cache ) {
117 $value = $cache->get( $key, $flags );
118 if ( $value !== false ) {
124 if ( $value !== false
126 && ( $flags & self
::READ_VERIFIED
) == self
::READ_VERIFIED
128 // Backfill the value to the higher (and often faster/smaller) cache tiers
133 // @TODO: consider using self::WRITE_ALLOW_SEGMENTS here?
134 [ $key, $value, self
::UPGRADE_TTL
]
141 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
142 return $this->doWrite(
144 $this->usesAsyncWritesGivenFlags( $flags ),
150 public function delete( $key, $flags = 0 ) {
151 return $this->doWrite(
153 $this->usesAsyncWritesGivenFlags( $flags ),
159 public function add( $key, $value, $exptime = 0, $flags = 0 ) {
160 // Try the write to the top-tier cache
161 $ok = $this->doWrite(
163 $this->usesAsyncWritesGivenFlags( $flags ),
169 // Relay the add() using set() if it succeeded. This is meant to handle certain
170 // migration scenarios where the same store might get written to twice for certain
171 // keys. In that case, it does not make sense to return false due to "self-conflicts".
172 return $this->doWrite(
173 array_slice( $this->cacheIndexes
, 1 ),
174 $this->usesAsyncWritesGivenFlags( $flags ),
176 [ $key, $value, $exptime, $flags ]
183 public function merge( $key, callable
$callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
184 return $this->doWrite(
186 $this->usesAsyncWritesGivenFlags( $flags ),
192 public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
193 return $this->doWrite(
195 $this->usesAsyncWritesGivenFlags( $flags ),
201 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
202 // Only need to lock the first cache; also avoids deadlocks
203 return $this->caches
[0]->lock( $key, $timeout, $expiry, $rclass );
206 public function unlock( $key ) {
207 // Only the first cache is locked
208 return $this->caches
[0]->unlock( $key );
211 public function deleteObjectsExpiringBefore(
213 callable
$progress = null,
217 foreach ( $this->caches
as $cache ) {
218 if ( $cache->deleteObjectsExpiringBefore( $timestamp, $progress, $limit ) ) {
226 public function getMulti( array $keys, $flags = 0 ) {
227 // Just iterate over each key in order to handle all the backfill logic
229 foreach ( $keys as $key ) {
230 $val = $this->get( $key, $flags );
231 if ( $val !== false ) {
239 public function setMulti( array $data, $exptime = 0, $flags = 0 ) {
240 return $this->doWrite(
242 $this->usesAsyncWritesGivenFlags( $flags ),
248 public function deleteMulti( array $data, $flags = 0 ) {
249 return $this->doWrite(
251 $this->usesAsyncWritesGivenFlags( $flags ),
257 public function changeTTLMulti( array $keys, $exptime, $flags = 0 ) {
258 return $this->doWrite(
260 $this->usesAsyncWritesGivenFlags( $flags ),
266 public function incr( $key, $value = 1 ) {
267 return $this->doWrite(
275 public function decr( $key, $value = 1 ) {
276 return $this->doWrite(
284 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
285 return $this->doWrite(
293 public function getLastError() {
294 return $this->caches
[0]->getLastError();
297 public function clearLastError() {
298 $this->caches
[0]->clearLastError();
302 * Apply a write method to the backing caches specified by $indexes (in order)
304 * @param int[] $indexes List of backing cache indexes
305 * @param bool $asyncWrites
306 * @param string $method Method name of backing caches
307 * @param array $args Arguments to the method of backing caches
310 protected function doWrite( $indexes, $asyncWrites, $method, array $args ) {
313 if ( array_diff( $indexes, [ 0 ] ) && $asyncWrites && $method !== 'merge' ) {
314 // Deep-clone $args to prevent misbehavior when something writes an
315 // object to the BagOStuff then modifies it afterwards, e.g. T168040.
316 $args = unserialize( serialize( $args ) );
319 foreach ( $indexes as $i ) {
320 $cache = $this->caches
[$i];
321 if ( $i == 0 ||
!$asyncWrites ) {
322 // First store or in sync mode: write now and get result
323 if ( !$cache->$method( ...$args ) ) {
327 // Secondary write in async mode: do not block this HTTP request
328 $logger = $this->logger
;
329 ( $this->asyncHandler
)(
330 function () use ( $cache, $method, $args, $logger ) {
331 if ( !$cache->$method( ...$args ) ) {
332 $logger->warning( "Async $method op failed" );
346 protected function usesAsyncWritesGivenFlags( $flags ) {
347 return ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) ?
false : $this->asyncWrites
;
350 public function makeKeyInternal( $keyspace, $args ) {
351 return $this->caches
[0]->makeKeyInternal( ...func_get_args() );
354 public function makeKey( $class, $component = null ) {
355 return $this->caches
[0]->makeKey( ...func_get_args() );
358 public function makeGlobalKey( $class, $component = null ) {
359 return $this->caches
[0]->makeGlobalKey( ...func_get_args() );
362 protected function doGet( $key, $flags = 0, &$casToken = null ) {
363 throw new LogicException( __METHOD__
. ': proxy class does not need this method.' );
366 protected function doSet( $key, $value, $exptime = 0, $flags = 0 ) {
367 throw new LogicException( __METHOD__
. ': proxy class does not need this method.' );
370 protected function doDelete( $key, $flags = 0 ) {
371 throw new LogicException( __METHOD__
. ': proxy class does not need this method.' );
374 protected function doChangeTTL( $key, $exptime, $flags ) {
375 throw new LogicException( __METHOD__
. ': proxy class does not need this method.' );
378 protected function doGetMulti( array $keys, $flags = 0 ) {
379 throw new LogicException( __METHOD__
. ': proxy class does not need this method.' );
382 protected function doSetMulti( array $keys, $exptime = 0, $flags = 0 ) {
383 throw new LogicException( __METHOD__
. ': proxy class does not need this method.' );
386 protected function doDeleteMulti( array $keys, $flags = 0 ) {
387 throw new LogicException( __METHOD__
. ': proxy class does not need this method.' );
390 protected function serialize( $value ) {
391 throw new LogicException( __METHOD__
. ': proxy class does not need this method.' );
394 protected function unserialize( $blob ) {
395 throw new LogicException( __METHOD__
. ': proxy class does not need this method.' );