objectcache: improve BagOStuff arithmetic method signatures
[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 /** @var int TTL when a key is copied to a higher cache tier */
44 private static $UPGRADE_TTL = 3600;
45
46 /**
47 * $params include:
48 * - caches: A numbered array of either ObjectFactory::getObjectFromSpec
49 * arrays yeilding BagOStuff objects or direct BagOStuff objects.
50 * If using the former, the 'args' field *must* be set.
51 * The first cache is the primary one, being the first to
52 * be read in the fallback chain. Writes happen to all stores
53 * in the order they are defined. However, lock()/unlock() calls
54 * only use the primary store.
55 * - replication: Either 'sync' or 'async'. This controls whether writes
56 * to secondary stores are deferred when possible. Async writes
57 * require setting 'asyncHandler'. HHVM register_postsend_function() function.
58 * Async writes can increase the chance of some race conditions
59 * or cause keys to expire seconds later than expected. It is
60 * safe to use for modules when cached values: are immutable,
61 * invalidation uses logical TTLs, invalidation uses etag/timestamp
62 * validation against the DB, or merge() is used to handle races.
63 * @param array $params
64 * @throws InvalidArgumentException
65 */
66 public function __construct( $params ) {
67 parent::__construct( $params );
68
69 if ( empty( $params['caches'] ) || !is_array( $params['caches'] ) ) {
70 throw new InvalidArgumentException(
71 __METHOD__ . ': "caches" parameter must be an array of caches'
72 );
73 }
74
75 $this->caches = [];
76 foreach ( $params['caches'] as $cacheInfo ) {
77 if ( $cacheInfo instanceof BagOStuff ) {
78 $this->caches[] = $cacheInfo;
79 } else {
80 if ( !isset( $cacheInfo['args'] ) ) {
81 // B/C for when $cacheInfo was for ObjectCache::newFromParams().
82 // Callers intenting this to be for ObjectFactory::getObjectFromSpec
83 // should have set "args" per the docs above. Doings so avoids extra
84 // (likely harmless) params (factory/class/calls) ending up in "args".
85 $cacheInfo['args'] = [ $cacheInfo ];
86 }
87 $this->caches[] = ObjectFactory::getObjectFromSpec( $cacheInfo );
88 }
89 }
90 $this->mergeFlagMaps( $this->caches );
91
92 $this->asyncWrites = (
93 isset( $params['replication'] ) &&
94 $params['replication'] === 'async' &&
95 is_callable( $this->asyncHandler )
96 );
97
98 $this->cacheIndexes = array_keys( $this->caches );
99 }
100
101 public function setDebug( $enabled ) {
102 parent::setDebug( $enabled );
103 foreach ( $this->caches as $cache ) {
104 $cache->setDebug( $enabled );
105 }
106 }
107
108 public function get( $key, $flags = 0 ) {
109 if ( $this->fieldHasFlags( $flags, self::READ_LATEST ) ) {
110 // If the latest write was a delete(), we do NOT want to fallback
111 // to the other tiers and possibly see the old value. Also, this
112 // is used by merge(), which only needs to hit the primary.
113 return $this->caches[0]->get( $key, $flags );
114 }
115
116 $value = false;
117 $missIndexes = []; // backends checked
118 foreach ( $this->caches as $i => $cache ) {
119 $value = $cache->get( $key, $flags );
120 if ( $value !== false ) {
121 break;
122 }
123 $missIndexes[] = $i;
124 }
125
126 if (
127 $value !== false &&
128 $this->fieldHasFlags( $flags, self::READ_VERIFIED ) &&
129 $missIndexes
130 ) {
131 // Backfill the value to the higher (and often faster/smaller) cache tiers
132 $this->doWrite(
133 $missIndexes,
134 $this->asyncWrites,
135 'set',
136 // @TODO: consider using self::WRITE_ALLOW_SEGMENTS here?
137 [ $key, $value, self::$UPGRADE_TTL ]
138 );
139 }
140
141 return $value;
142 }
143
144 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
145 return $this->doWrite(
146 $this->cacheIndexes,
147 $this->usesAsyncWritesGivenFlags( $flags ),
148 __FUNCTION__,
149 func_get_args()
150 );
151 }
152
153 public function delete( $key, $flags = 0 ) {
154 return $this->doWrite(
155 $this->cacheIndexes,
156 $this->usesAsyncWritesGivenFlags( $flags ),
157 __FUNCTION__,
158 func_get_args()
159 );
160 }
161
162 public function add( $key, $value, $exptime = 0, $flags = 0 ) {
163 // Try the write to the top-tier cache
164 $ok = $this->doWrite(
165 [ 0 ],
166 $this->usesAsyncWritesGivenFlags( $flags ),
167 __FUNCTION__,
168 func_get_args()
169 );
170
171 if ( $ok ) {
172 // Relay the add() using set() if it succeeded. This is meant to handle certain
173 // migration scenarios where the same store might get written to twice for certain
174 // keys. In that case, it does not make sense to return false due to "self-conflicts".
175 return $this->doWrite(
176 array_slice( $this->cacheIndexes, 1 ),
177 $this->usesAsyncWritesGivenFlags( $flags ),
178 'set',
179 [ $key, $value, $exptime, $flags ]
180 );
181 }
182
183 return false;
184 }
185
186 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
187 return $this->doWrite(
188 $this->cacheIndexes,
189 $this->usesAsyncWritesGivenFlags( $flags ),
190 __FUNCTION__,
191 func_get_args()
192 );
193 }
194
195 public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
196 return $this->doWrite(
197 $this->cacheIndexes,
198 $this->usesAsyncWritesGivenFlags( $flags ),
199 __FUNCTION__,
200 func_get_args()
201 );
202 }
203
204 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
205 // Only need to lock the first cache; also avoids deadlocks
206 return $this->caches[0]->lock( $key, $timeout, $expiry, $rclass );
207 }
208
209 public function unlock( $key ) {
210 // Only the first cache is locked
211 return $this->caches[0]->unlock( $key );
212 }
213
214 public function deleteObjectsExpiringBefore(
215 $timestamp,
216 callable $progress = null,
217 $limit = INF
218 ) {
219 $ret = false;
220 foreach ( $this->caches as $cache ) {
221 if ( $cache->deleteObjectsExpiringBefore( $timestamp, $progress, $limit ) ) {
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 changeTTLMulti( array $keys, $exptime, $flags = 0 ) {
261 return $this->doWrite(
262 $this->cacheIndexes,
263 $this->usesAsyncWritesGivenFlags( $flags ),
264 __FUNCTION__,
265 func_get_args()
266 );
267 }
268
269 public function incr( $key, $value = 1, $flags = 0 ) {
270 return $this->doWrite(
271 $this->cacheIndexes,
272 $this->asyncWrites,
273 __FUNCTION__,
274 func_get_args()
275 );
276 }
277
278 public function decr( $key, $value = 1, $flags = 0 ) {
279 return $this->doWrite(
280 $this->cacheIndexes,
281 $this->asyncWrites,
282 __FUNCTION__,
283 func_get_args()
284 );
285 }
286
287 public function incrWithInit( $key, $exptime, $value = 1, $init = null, $flags = 0 ) {
288 return $this->doWrite(
289 $this->cacheIndexes,
290 $this->asyncWrites,
291 __FUNCTION__,
292 func_get_args()
293 );
294 }
295
296 public function getLastError() {
297 return $this->caches[0]->getLastError();
298 }
299
300 public function clearLastError() {
301 $this->caches[0]->clearLastError();
302 }
303
304 /**
305 * Apply a write method to the backing caches specified by $indexes (in order)
306 *
307 * @param int[] $indexes List of backing cache indexes
308 * @param bool $asyncWrites
309 * @param string $method Method name of backing caches
310 * @param array $args Arguments to the method of backing caches
311 * @return bool
312 */
313 protected function doWrite( $indexes, $asyncWrites, $method, array $args ) {
314 $ret = true;
315
316 if ( array_diff( $indexes, [ 0 ] ) && $asyncWrites && $method !== 'merge' ) {
317 // Deep-clone $args to prevent misbehavior when something writes an
318 // object to the BagOStuff then modifies it afterwards, e.g. T168040.
319 $args = unserialize( serialize( $args ) );
320 }
321
322 foreach ( $indexes as $i ) {
323 $cache = $this->caches[$i];
324 if ( $i == 0 || !$asyncWrites ) {
325 // First store or in sync mode: write now and get result
326 if ( !$cache->$method( ...$args ) ) {
327 $ret = false;
328 }
329 } else {
330 // Secondary write in async mode: do not block this HTTP request
331 $logger = $this->logger;
332 ( $this->asyncHandler )(
333 function () use ( $cache, $method, $args, $logger ) {
334 if ( !$cache->$method( ...$args ) ) {
335 $logger->warning( "Async $method op failed" );
336 }
337 }
338 );
339 }
340 }
341
342 return $ret;
343 }
344
345 /**
346 * @param int $flags
347 * @return bool
348 */
349 protected function usesAsyncWritesGivenFlags( $flags ) {
350 return $this->fieldHasFlags( $flags, self::WRITE_SYNC ) ? false : $this->asyncWrites;
351 }
352
353 public function makeKeyInternal( $keyspace, $args ) {
354 return $this->caches[0]->makeKeyInternal( $keyspace, $args );
355 }
356
357 public function makeKey( $class, ...$components ) {
358 return $this->caches[0]->makeKey( ...func_get_args() );
359 }
360
361 public function makeGlobalKey( $class, ...$components ) {
362 return $this->caches[0]->makeGlobalKey( ...func_get_args() );
363 }
364
365 public function addBusyCallback( callable $workCallback ) {
366 $this->caches[0]->addBusyCallback( $workCallback );
367 }
368
369 public function setMockTime( &$time ) {
370 parent::setMockTime( $time );
371 foreach ( $this->caches as $cache ) {
372 $cache->setMockTime( $time );
373 $cache->setMockTime( $time );
374 }
375 }
376 }