Special case opus mime detction
[mediawiki.git] / includes / libs / objectcache / MultiWriteBagOStuff.php
blob9dcfa7c55eec5740f6c88388cf556a7b9ad1e885
1 <?php
2 /**
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
20 * @file
21 * @ingroup Cache
24 /**
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.
29 * @ingroup Cache
31 class MultiWriteBagOStuff extends BagOStuff {
32 /** @var BagOStuff[] */
33 protected $caches;
34 /** @var bool Use async secondary writes */
35 protected $asyncWrites = false;
37 /** Idiom for "write to all backends" */
38 const ALL = INF;
40 const UPGRADE_TTL = 3600; // TTL when a key is copied to a higher cache tier
42 /**
43 * $params include:
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
52 * to secondary stores are deferred when possible. Async writes
53 * require setting 'asyncHandler'. 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.
59 * @param array $params
60 * @throws InvalidArgumentException
62 public function __construct( $params ) {
63 parent::__construct( $params );
65 if ( empty( $params['caches'] ) || !is_array( $params['caches'] ) ) {
66 throw new InvalidArgumentException(
67 __METHOD__ . ': "caches" parameter must be an array of caches'
71 $this->caches = [];
72 foreach ( $params['caches'] as $cacheInfo ) {
73 if ( $cacheInfo instanceof BagOStuff ) {
74 $this->caches[] = $cacheInfo;
75 } else {
76 if ( !isset( $cacheInfo['args'] ) ) {
77 // B/C for when $cacheInfo was for ObjectCache::newFromParams().
78 // Callers intenting this to be for ObjectFactory::getObjectFromSpec
79 // should have set "args" per the docs above. Doings so avoids extra
80 // (likely harmless) params (factory/class/calls) ending up in "args".
81 $cacheInfo['args'] = [ $cacheInfo ];
83 $this->caches[] = ObjectFactory::getObjectFromSpec( $cacheInfo );
86 $this->mergeFlagMaps( $this->caches );
88 $this->asyncWrites = (
89 isset( $params['replication'] ) &&
90 $params['replication'] === 'async' &&
91 is_callable( $this->asyncHandler )
95 public function setDebug( $debug ) {
96 foreach ( $this->caches as $cache ) {
97 $cache->setDebug( $debug );
101 protected function doGet( $key, $flags = 0 ) {
102 if ( ( $flags & self::READ_LATEST ) == self::READ_LATEST ) {
103 // If the latest write was a delete(), we do NOT want to fallback
104 // to the other tiers and possibly see the old value. Also, this
105 // is used by mergeViaLock(), which only needs to hit the primary.
106 return $this->caches[0]->get( $key, $flags );
109 $misses = 0; // number backends checked
110 $value = false;
111 foreach ( $this->caches as $cache ) {
112 $value = $cache->get( $key, $flags );
113 if ( $value !== false ) {
114 break;
116 ++$misses;
119 if ( $value !== false
120 && $misses > 0
121 && ( $flags & self::READ_VERIFIED ) == self::READ_VERIFIED
123 $this->doWrite( $misses, $this->asyncWrites, 'set', $key, $value, self::UPGRADE_TTL );
126 return $value;
129 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
130 $asyncWrites = ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC )
131 ? false
132 : $this->asyncWrites;
134 return $this->doWrite( self::ALL, $asyncWrites, 'set', $key, $value, $exptime );
137 public function delete( $key ) {
138 return $this->doWrite( self::ALL, $this->asyncWrites, 'delete', $key );
141 public function add( $key, $value, $exptime = 0 ) {
142 return $this->doWrite( self::ALL, $this->asyncWrites, 'add', $key, $value, $exptime );
145 public function incr( $key, $value = 1 ) {
146 return $this->doWrite( self::ALL, $this->asyncWrites, 'incr', $key, $value );
149 public function decr( $key, $value = 1 ) {
150 return $this->doWrite( self::ALL, $this->asyncWrites, 'decr', $key, $value );
153 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
154 // Only need to lock the first cache; also avoids deadlocks
155 return $this->caches[0]->lock( $key, $timeout, $expiry, $rclass );
158 public function unlock( $key ) {
159 // Only the first cache is locked
160 return $this->caches[0]->unlock( $key );
163 public function getLastError() {
164 return $this->caches[0]->getLastError();
167 public function clearLastError() {
168 $this->caches[0]->clearLastError();
172 * Apply a write method to the first $count backing caches
174 * @param integer $count
175 * @param bool $asyncWrites
176 * @param string $method
177 * @param mixed ...
178 * @return bool
180 protected function doWrite( $count, $asyncWrites, $method /*, ... */ ) {
181 $ret = true;
182 $args = array_slice( func_get_args(), 3 );
184 foreach ( $this->caches as $i => $cache ) {
185 if ( $i >= $count ) {
186 break; // ignore the lower tiers
189 if ( $i == 0 || !$asyncWrites ) {
190 // First store or in sync mode: write now and get result
191 if ( !call_user_func_array( [ $cache, $method ], $args ) ) {
192 $ret = false;
194 } else {
195 // Secondary write in async mode: do not block this HTTP request
196 $logger = $this->logger;
197 call_user_func(
198 $this->asyncHandler,
199 function () use ( $cache, $method, $args, $logger ) {
200 if ( !call_user_func_array( [ $cache, $method ], $args ) ) {
201 $logger->warning( "Async $method op failed" );
208 return $ret;
212 * Delete objects expiring before a certain date.
214 * Succeed if any of the child caches succeed.
215 * @param string $date
216 * @param bool|callable $progressCallback
217 * @return bool
219 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
220 $ret = false;
221 foreach ( $this->caches as $cache ) {
222 if ( $cache->deleteObjectsExpiringBefore( $date, $progressCallback ) ) {
223 $ret = true;
227 return $ret;