Merge "feedback: Fix misplaced mw.Title.getNameText() call"
[lhc/web/wiklou.git] / includes / libs / 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 use Wikimedia\ObjectFactory;
24
25 /**
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.
29 *
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).
32 *
33 * @ingroup Cache
34 */
35 class MultiWriteBagOStuff extends BagOStuff {
36 /** @var BagOStuff[] */
37 protected $caches;
38 /** @var bool Use async secondary writes */
39 protected $asyncWrites = false;
40 /** @var int[] List of all backing cache indexes */
41 protected $cacheIndexes = [];
42
43 const UPGRADE_TTL = 3600; // TTL when a key is copied to a higher cache tier
44
45 /**
46 * $params include:
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
64 */
65 public function __construct( $params ) {
66 parent::__construct( $params );
67
68 if ( empty( $params['caches'] ) || !is_array( $params['caches'] ) ) {
69 throw new InvalidArgumentException(
70 __METHOD__ . ': "caches" parameter must be an array of caches'
71 );
72 }
73
74 $this->caches = [];
75 foreach ( $params['caches'] as $cacheInfo ) {
76 if ( $cacheInfo instanceof BagOStuff ) {
77 $this->caches[] = $cacheInfo;
78 } else {
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 ];
85 }
86 $this->caches[] = ObjectFactory::getObjectFromSpec( $cacheInfo );
87 }
88 }
89 $this->mergeFlagMaps( $this->caches );
90
91 $this->asyncWrites = (
92 isset( $params['replication'] ) &&
93 $params['replication'] === 'async' &&
94 is_callable( $this->asyncHandler )
95 );
96
97 $this->cacheIndexes = array_keys( $this->caches );
98 }
99
100 public function setDebug( $debug ) {
101 foreach ( $this->caches as $cache ) {
102 $cache->setDebug( $debug );
103 }
104 }
105
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 );
112 }
113
114 $value = false;
115 $missIndexes = []; // backends checked
116 foreach ( $this->caches as $i => $cache ) {
117 $value = $cache->get( $key, $flags );
118 if ( $value !== false ) {
119 break;
120 }
121 $missIndexes[] = $i;
122 }
123
124 if ( $value !== false
125 && $missIndexes
126 && ( $flags & self::READ_VERIFIED ) == self::READ_VERIFIED
127 ) {
128 // Backfill the value to the higher (and often faster/smaller) cache tiers
129 $this->doWrite(
130 $missIndexes,
131 $this->asyncWrites,
132 'set',
133 [ $key, $value, self::UPGRADE_TTL ]
134 );
135 }
136
137 return $value;
138 }
139
140 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
141 return $this->doWrite(
142 $this->cacheIndexes,
143 $this->usesAsyncWritesGivenFlags( $flags ),
144 __FUNCTION__,
145 func_get_args()
146 );
147 }
148
149 public function delete( $key, $flags = 0 ) {
150 return $this->doWrite(
151 $this->cacheIndexes,
152 $this->usesAsyncWritesGivenFlags( $flags ),
153 __FUNCTION__,
154 func_get_args()
155 );
156 }
157
158 public function add( $key, $value, $exptime = 0, $flags = 0 ) {
159 // Try the write to the top-tier cache
160 $ok = $this->doWrite(
161 [ 0 ],
162 $this->usesAsyncWritesGivenFlags( $flags ),
163 __FUNCTION__,
164 func_get_args()
165 );
166
167 if ( $ok ) {
168 // Relay the add() using set() if it succeeded. This is meant to handle certain
169 // migration scenarios where the same store might get written to twice for certain
170 // keys. In that case, it does not make sense to return false due to "self-conflicts".
171 return $this->doWrite(
172 array_slice( $this->cacheIndexes, 1 ),
173 $this->usesAsyncWritesGivenFlags( $flags ),
174 'set',
175 [ $key, $value, $exptime, $flags ]
176 );
177 }
178
179 return false;
180 }
181
182 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
183 return $this->doWrite(
184 $this->cacheIndexes,
185 $this->usesAsyncWritesGivenFlags( $flags ),
186 __FUNCTION__,
187 func_get_args()
188 );
189 }
190
191 public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
192 return $this->doWrite(
193 $this->cacheIndexes,
194 $this->usesAsyncWritesGivenFlags( $flags ),
195 __FUNCTION__,
196 func_get_args()
197 );
198 }
199
200 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
201 // Only need to lock the first cache; also avoids deadlocks
202 return $this->caches[0]->lock( $key, $timeout, $expiry, $rclass );
203 }
204
205 public function unlock( $key ) {
206 // Only the first cache is locked
207 return $this->caches[0]->unlock( $key );
208 }
209
210 /**
211 * Delete objects expiring before a certain date.
212 *
213 * Succeed if any of the child caches succeed.
214 * @param string $date
215 * @param bool|callable $progressCallback
216 * @return bool
217 */
218 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
219 $ret = false;
220 foreach ( $this->caches as $cache ) {
221 if ( $cache->deleteObjectsExpiringBefore( $date, $progressCallback ) ) {
222 $ret = true;
223 }
224 }
225
226 return $ret;
227 }
228
229 public function getMulti( array $keys, $flags = 0 ) {
230 // Just iterate over each key in order to handle all the backfill logic
231 $res = [];
232 foreach ( $keys as $key ) {
233 $val = $this->get( $key, $flags );
234 if ( $val !== false ) {
235 $res[$key] = $val;
236 }
237 }
238
239 return $res;
240 }
241
242 public function setMulti( array $data, $exptime = 0, $flags = 0 ) {
243 return $this->doWrite(
244 $this->cacheIndexes,
245 $this->usesAsyncWritesGivenFlags( $flags ),
246 __FUNCTION__,
247 func_get_args()
248 );
249 }
250
251 public function deleteMulti( array $data, $flags = 0 ) {
252 return $this->doWrite(
253 $this->cacheIndexes,
254 $this->usesAsyncWritesGivenFlags( $flags ),
255 __FUNCTION__,
256 func_get_args()
257 );
258 }
259
260 public function incr( $key, $value = 1 ) {
261 return $this->doWrite(
262 $this->cacheIndexes,
263 $this->asyncWrites,
264 __FUNCTION__,
265 func_get_args()
266 );
267 }
268
269 public function decr( $key, $value = 1 ) {
270 return $this->doWrite(
271 $this->cacheIndexes,
272 $this->asyncWrites,
273 __FUNCTION__,
274 func_get_args()
275 );
276 }
277
278 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
279 return $this->doWrite(
280 $this->cacheIndexes,
281 $this->asyncWrites,
282 __FUNCTION__,
283 func_get_args()
284 );
285 }
286
287 public function getLastError() {
288 return $this->caches[0]->getLastError();
289 }
290
291 public function clearLastError() {
292 $this->caches[0]->clearLastError();
293 }
294
295 /**
296 * Apply a write method to the backing caches specified by $indexes (in order)
297 *
298 * @param int[] $indexes List of backing cache indexes
299 * @param bool $asyncWrites
300 * @param string $method Method name of backing caches
301 * @param array[] $args Arguments to the method of backing caches
302 * @return bool
303 */
304 protected function doWrite( $indexes, $asyncWrites, $method, array $args ) {
305 $ret = true;
306
307 if ( array_diff( $indexes, [ 0 ] ) && $asyncWrites && $method !== 'merge' ) {
308 // Deep-clone $args to prevent misbehavior when something writes an
309 // object to the BagOStuff then modifies it afterwards, e.g. T168040.
310 $args = unserialize( serialize( $args ) );
311 }
312
313 foreach ( $indexes as $i ) {
314 $cache = $this->caches[$i];
315 if ( $i == 0 || !$asyncWrites ) {
316 // First store or in sync mode: write now and get result
317 if ( !$cache->$method( ...$args ) ) {
318 $ret = false;
319 }
320 } else {
321 // Secondary write in async mode: do not block this HTTP request
322 $logger = $this->logger;
323 ( $this->asyncHandler )(
324 function () use ( $cache, $method, $args, $logger ) {
325 if ( !$cache->$method( ...$args ) ) {
326 $logger->warning( "Async $method op failed" );
327 }
328 }
329 );
330 }
331 }
332
333 return $ret;
334 }
335
336 /**
337 * @param int $flags
338 * @return bool
339 */
340 protected function usesAsyncWritesGivenFlags( $flags ) {
341 return ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) ? false : $this->asyncWrites;
342 }
343
344 public function makeKeyInternal( $keyspace, $args ) {
345 return $this->caches[0]->makeKeyInternal( ...func_get_args() );
346 }
347
348 public function makeKey( $class, $component = null ) {
349 return $this->caches[0]->makeKey( ...func_get_args() );
350 }
351
352 public function makeGlobalKey( $class, $component = null ) {
353 return $this->caches[0]->makeGlobalKey( ...func_get_args() );
354 }
355
356 protected function doGet( $key, $flags = 0, &$casToken = null ) {
357 throw new LogicException( __METHOD__ . ': proxy class does not need this method.' );
358 }
359 }