Merge "Update ResourceLoader for Ib7fc2f939b"
[lhc/web/wiklou.git] / includes / objectcache / MultiWriteBagOStuff.php
1 <?php
2 /**
3 * Wrapper for object caching in different caches.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Cache
22 */
23
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.
28 *
29 * @ingroup Cache
30 */
31 class MultiWriteBagOStuff extends BagOStuff {
32 /** @var BagOStuff[] */
33 protected $caches;
34 /** @var bool Use async secondary writes */
35 protected $asyncWrites = false;
36
37 /** Idiom for "write to all backends" */
38 const ALL = INF;
39
40 const UPGRADE_TTL = 3600; // TTL when a key is copied to a higher cache tier
41
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 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.
59 *
60 * @param array $params
61 * @throws InvalidArgumentException
62 */
63 public function __construct( $params ) {
64 parent::__construct( $params );
65
66 if ( empty( $params['caches'] ) || !is_array( $params['caches'] ) ) {
67 throw new InvalidArgumentException(
68 __METHOD__ . ': "caches" parameter must be an array of caches'
69 );
70 }
71
72 $this->caches = array();
73 foreach ( $params['caches'] as $cacheInfo ) {
74 if ( $cacheInfo instanceof BagOStuff ) {
75 $this->caches[] = $cacheInfo;
76 } else {
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 );
83 }
84 $this->caches[] = ObjectFactory::getObjectFromSpec( $cacheInfo );
85 }
86 }
87
88 $this->asyncWrites = isset( $params['replication'] ) && $params['replication'] === 'async';
89 }
90
91 /**
92 * @param bool $debug
93 */
94 public function setDebug( $debug ) {
95 $this->doWrite( self::ALL, 'setDebug', $debug );
96 }
97
98 protected function doGet( $key, $flags = 0 ) {
99 $misses = 0; // number backends checked
100 $value = false;
101 foreach ( $this->caches as $cache ) {
102 $value = $cache->get( $key, $flags );
103 if ( $value !== false ) {
104 break;
105 }
106 ++$misses;
107 }
108
109 if ( $value !== false
110 && $misses > 0
111 && ( $flags & self::READ_VERIFIED ) == self::READ_VERIFIED
112 ) {
113 $this->doWrite( $misses, 'set', $key, $value, self::UPGRADE_TTL );
114 }
115
116 return $value;
117 }
118
119 /**
120 * @param string $key
121 * @param mixed $value
122 * @param int $exptime
123 * @return bool
124 */
125 public function set( $key, $value, $exptime = 0 ) {
126 return $this->doWrite( self::ALL, 'set', $key, $value, $exptime );
127 }
128
129 /**
130 * @param string $key
131 * @return bool
132 */
133 public function delete( $key ) {
134 return $this->doWrite( self::ALL, 'delete', $key );
135 }
136
137 /**
138 * @param string $key
139 * @param mixed $value
140 * @param int $exptime
141 * @return bool
142 */
143 public function add( $key, $value, $exptime = 0 ) {
144 return $this->doWrite( self::ALL, 'add', $key, $value, $exptime );
145 }
146
147 /**
148 * @param string $key
149 * @param int $value
150 * @return bool|null
151 */
152 public function incr( $key, $value = 1 ) {
153 return $this->doWrite( self::ALL, 'incr', $key, $value );
154 }
155
156 /**
157 * @param string $key
158 * @param int $value
159 * @return bool
160 */
161 public function decr( $key, $value = 1 ) {
162 return $this->doWrite( self::ALL, 'decr', $key, $value );
163 }
164
165 /**
166 * @param string $key
167 * @param int $timeout
168 * @param int $expiry
169 * @param string $rclass
170 * @return bool
171 */
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 );
175 }
176
177 /**
178 * @param string $key
179 * @return bool
180 */
181 public function unlock( $key ) {
182 return $this->caches[0]->unlock( $key );
183 }
184
185 /**
186 * @param string $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
191 */
192 public function merge( $key, $callback, $exptime = 0, $attempts = 10 ) {
193 return $this->doWrite( self::ALL, 'merge', $key, $callback, $exptime );
194 }
195
196 public function getLastError() {
197 return $this->caches[0]->getLastError();
198 }
199
200 public function clearLastError() {
201 $this->caches[0]->clearLastError();
202 }
203
204 /**
205 * Apply a write method to the first $count backing caches
206 *
207 * @param integer $count
208 * @param string $method
209 * @param mixed ...
210 * @return bool
211 */
212 protected function doWrite( $count, $method /*, ... */ ) {
213 $ret = true;
214 $args = array_slice( func_get_args(), 2 );
215
216 foreach ( $this->caches as $i => $cache ) {
217 if ( $i >= $count ) {
218 break; // ignore the lower tiers
219 }
220
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 ) ) {
224 $ret = false;
225 }
226 } else {
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" );
233 }
234 }
235 );
236 }
237 }
238
239 return $ret;
240 }
241
242 /**
243 * Delete objects expiring before a certain date.
244 *
245 * Succeed if any of the child caches succeed.
246 * @param string $date
247 * @param bool|callable $progressCallback
248 * @return bool
249 */
250 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
251 $ret = false;
252 foreach ( $this->caches as $cache ) {
253 if ( $cache->deleteObjectsExpiringBefore( $date, $progressCallback ) ) {
254 $ret = true;
255 }
256 }
257
258 return $ret;
259 }
260 }