Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
44.71% covered (danger)
44.71%
76 / 170
33.33% covered (danger)
33.33%
6 / 18
CRAP
0.00% covered (danger)
0.00%
0 / 1
MultiWriteBagOStuff
44.97% covered (danger)
44.97%
76 / 169
33.33% covered (danger)
33.33%
6 / 18
382.45
0.00% covered (danger)
0.00%
0 / 1
 __construct
76.47% covered (warning)
76.47%
13 / 17
0.00% covered (danger)
0.00%
0 / 1
7.64
 get
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
56
 set
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 delete
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 add
94.44% covered (success)
94.44%
17 / 18
0.00% covered (danger)
0.00%
0 / 1
3.00
 merge
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 changeTTL
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 lock
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 unlock
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 deleteObjectsExpiringBefore
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 getMulti
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 setMulti
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 deleteMulti
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 changeTTLMulti
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 incrWithInit
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 setMockTime
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 callKeyMethodOnTierCache
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 callKeyWriteMethodOnTierCaches
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
9
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 */
6namespace Wikimedia\ObjectCache;
7
8use InvalidArgumentException;
9use Wikimedia\ObjectFactory\ObjectFactory;
10
11/**
12 * Wrap multiple BagOStuff objects, to implement different caching tiers.
13 *
14 * The order of the caches is important. The first tier is considered the primary
15 * and highest tier which must handle the majority of the load for reads,
16 * and is generally less persistent, smaller, and faster (e.g. evicts data
17 * regularly based on demand, keeping fewer keys at a given time).
18 * The other caches are consider secondary and lower tiers, which should
19 * hold more data and retain it for longer than the primary tier.
20 *
21 * Data writes ("set") go to all given BagOStuff caches.
22 * If the `replication => async` option is set, then only the primary write
23 * is blocking during the web request, with other writes deferred until
24 * after the web response is sent.
25 *
26 * Data reads try each cache in the order they are given, until a value is found.
27 * When a value is found at a secondary tier, it is automatically copied (back)
28 * to the primary tier.
29 *
30 * **Example**: Keep popular data in memcached, with a fallback to a MySQL database.
31 * This is how ParserCache is used at Wikimedia Foundation (as of 2024).
32 *
33 * ```
34 * $wgObjectCaches['parsercache-multiwrite'] = [
35 *    'class' => 'MultiWriteBagOStuff',
36 *    'caches' => [
37 *      0 => [
38 *        'class' => 'MemcachedPeclBagOStuff',
39 *        'servers' => [ '127.0.0.1:11212' ],
40 *      ],
41 *      1 => [
42 *        'class' => 'SqlBagOStuff',
43 *        'servers' => $parserCacheDbServers,
44 *        'purgePeriod' => 0,
45 *        'tableName' => 'pc',
46 *        'shards' => 256,
47 *        'reportDupes' => false
48 *      ],
49 *    ]
50 * ];
51 * ```
52 *
53 * If you configure a memcached server for MultiWriteBagOStuff that is the same
54 * as the one used for MediaWiki more generally, it is recommended to specify
55 * the tier via ObjectCache::getInstance() so that the same object and Memcached
56 * connection can be re-used.
57 *
58 * ```
59 * $wgObjectCaches['my-memcached'] = [ .. ];
60 * $wgMainCacheType = 'my-memcached';
61 *
62 * $wgObjectCaches['parsercache-multiwrite'] = [
63 *    'class' => 'MultiWriteBagOStuff',
64 *    'caches' => [
65 *      0 => [
66 *        'factory' => [ 'ObjectCache', 'getInstance' ],
67 *        'args' => [ 'my-memcached' ],
68 *      ],
69 *      1 => [
70 *        'class' => 'SqlBagOStuff',
71 *        'servers' => $parserCacheDbServers,
72 *        'purgePeriod' => 0,
73 *        'tableName' => 'pc',
74 *        'shards' => 256,
75 *        'reportDupes' => false
76 *      ],
77 *    ]
78 * ];
79 * ```
80 *
81 * The makeKey() method of this class uses an implementation-agnostic encoding.
82 * When it forward gets and sets to the other BagOStuff objects, keys are
83 * automatically re-encoded. For example, to satisfy the character and length
84 * constraints of MemcachedBagOStuff.
85 *
86 * @newable
87 * @ingroup Cache
88 */
89class MultiWriteBagOStuff extends BagOStuff {
90    /** @var BagOStuff[] Backing cache stores in order of highest to lowest tier */
91    protected $caches;
92
93    /** @var bool Use async secondary writes */
94    protected $asyncWrites = false;
95    /** @var int[] List of all backing cache indexes */
96    protected $cacheIndexes = [];
97
98    /** @var int TTL when a key is copied to a higher cache tier */
99    private static $UPGRADE_TTL = 3600;
100
101    /**
102     * @stable to call
103     *
104     * @param array $params
105     *   - caches: A numbered array of either ObjectFactory::getObjectFromSpec
106     *      arrays yielding BagOStuff objects or direct BagOStuff objects.
107     *      If using the former, the 'args' field *must* be set.
108     *      The first cache is the primary one, being the first to
109     *      be read in the fallback chain. Writes happen to all stores
110     *      in the order they are defined. However, lock()/unlock() calls
111     *      only use the primary store.
112     *   - replication: Either 'sync' or 'async'. This controls whether writes
113     *      to secondary stores are deferred when possible. To use 'async' writes
114     *      requires the 'asyncHandler' option to be set as well.
115     *      Async writes can increase the chance of some race conditions
116     *      or cause keys to expire seconds later than expected. It is
117     *      safe to use for modules when cached values: are immutable,
118     *      invalidation uses logical TTLs, invalidation uses etag/timestamp
119     *      validation against the DB, or merge() is used to handle races.
120     *
121     * @phan-param array{caches:array<int,array|BagOStuff>,replication:string} $params
122     */
123    public function __construct( $params ) {
124        parent::__construct( $params );
125
126        if ( empty( $params['caches'] ) || !is_array( $params['caches'] ) ) {
127            throw new InvalidArgumentException(
128                __METHOD__ . ': "caches" parameter must be an array of caches'
129            );
130        }
131
132        $this->caches = [];
133        foreach ( $params['caches'] as $cacheInfo ) {
134            if ( $cacheInfo instanceof BagOStuff ) {
135                $this->caches[] = $cacheInfo;
136            } else {
137                $this->caches[] = ObjectFactory::getObjectFromSpec( $cacheInfo );
138            }
139        }
140
141        $this->attrMap = $this->mergeFlagMaps( $this->caches );
142
143        $this->asyncWrites = (
144            isset( $params['replication'] ) &&
145            $params['replication'] === 'async' &&
146            is_callable( $this->asyncHandler )
147        );
148
149        $this->cacheIndexes = array_keys( $this->caches );
150    }
151
152    /** @inheritDoc */
153    public function get( $key, $flags = 0 ) {
154        $args = func_get_args();
155
156        if ( $this->fieldHasFlags( $flags, self::READ_LATEST ) ) {
157            // If the latest write was a delete(), we do NOT want to fallback
158            // to the other tiers and possibly see the old value. Also, this
159            // is used by merge(), which only needs to hit the primary.
160            return $this->callKeyMethodOnTierCache(
161                0,
162                __FUNCTION__,
163                self::ARG0_KEY,
164                self::RES_NONKEY,
165                $args
166            );
167        }
168
169        $value = false;
170        // backends checked
171        $missIndexes = [];
172        foreach ( $this->cacheIndexes as $i ) {
173            $value = $this->callKeyMethodOnTierCache(
174                $i,
175                __FUNCTION__,
176                self::ARG0_KEY,
177                self::RES_NONKEY,
178                $args
179            );
180            if ( $value !== false ) {
181                break;
182            }
183            $missIndexes[] = $i;
184        }
185
186        if (
187            $value !== false &&
188            $this->fieldHasFlags( $flags, self::READ_VERIFIED ) &&
189            $missIndexes
190        ) {
191            // Backfill the value to the higher (and often faster/smaller) cache tiers
192            $this->callKeyWriteMethodOnTierCaches(
193                $missIndexes,
194                'set',
195                self::ARG0_KEY,
196                self::RES_NONKEY,
197                [ $key, $value, self::$UPGRADE_TTL ]
198            );
199        }
200
201        return $value;
202    }
203
204    /** @inheritDoc */
205    public function set( $key, $value, $exptime = 0, $flags = 0 ) {
206        return $this->callKeyWriteMethodOnTierCaches(
207            $this->cacheIndexes,
208            __FUNCTION__,
209            self::ARG0_KEY,
210            self::RES_NONKEY,
211            func_get_args()
212        );
213    }
214
215    /** @inheritDoc */
216    public function delete( $key, $flags = 0 ) {
217        return $this->callKeyWriteMethodOnTierCaches(
218            $this->cacheIndexes,
219            __FUNCTION__,
220            self::ARG0_KEY,
221            self::RES_NONKEY,
222            func_get_args()
223        );
224    }
225
226    /** @inheritDoc */
227    public function add( $key, $value, $exptime = 0, $flags = 0 ) {
228        // Try the write to the top-tier cache
229        $ok = $this->callKeyMethodOnTierCache(
230            0,
231            __FUNCTION__,
232            self::ARG0_KEY,
233            self::RES_NONKEY,
234            func_get_args()
235        );
236
237        if ( $ok ) {
238            // Relay the add() using set() if it succeeded. This is meant to handle certain
239            // migration scenarios where the same store might get written to twice for certain
240            // keys. In that case, it makes no sense to return false due to "self-conflicts".
241            $okSecondaries = $this->callKeyWriteMethodOnTierCaches(
242                array_slice( $this->cacheIndexes, 1 ),
243                'set',
244                self::ARG0_KEY,
245                self::RES_NONKEY,
246                [ $key, $value, $exptime, $flags ]
247            );
248            if ( $okSecondaries === false ) {
249                $ok = false;
250            }
251        }
252
253        return $ok;
254    }
255
256    /** @inheritDoc */
257    public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
258        return $this->callKeyWriteMethodOnTierCaches(
259            $this->cacheIndexes,
260            __FUNCTION__,
261            self::ARG0_KEY,
262            self::RES_NONKEY,
263            func_get_args()
264        );
265    }
266
267    /** @inheritDoc */
268    public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
269        return $this->callKeyWriteMethodOnTierCaches(
270            $this->cacheIndexes,
271            __FUNCTION__,
272            self::ARG0_KEY,
273            self::RES_NONKEY,
274            func_get_args()
275        );
276    }
277
278    /** @inheritDoc */
279    public function lock( $key, $timeout = 6, $exptime = 6, $rclass = '' ) {
280        // Only need to lock the first cache; also avoids deadlocks
281        return $this->callKeyMethodOnTierCache(
282            0,
283            __FUNCTION__,
284            self::ARG0_KEY,
285            self::RES_NONKEY,
286            func_get_args()
287        );
288    }
289
290    /** @inheritDoc */
291    public function unlock( $key ) {
292        // Only the first cache is locked
293        return $this->callKeyMethodOnTierCache(
294            0,
295            __FUNCTION__,
296            self::ARG0_KEY,
297            self::RES_NONKEY,
298            func_get_args()
299        );
300    }
301
302    /** @inheritDoc */
303    public function deleteObjectsExpiringBefore(
304        $timestamp,
305        ?callable $progress = null,
306        $limit = INF,
307        ?string $tag = null
308    ) {
309        $ret = false;
310        foreach ( $this->caches as $cache ) {
311            if ( $cache->deleteObjectsExpiringBefore( $timestamp, $progress, $limit, $tag ) ) {
312                $ret = true;
313            }
314        }
315
316        return $ret;
317    }
318
319    /** @inheritDoc */
320    public function getMulti( array $keys, $flags = 0 ) {
321        // Just iterate over each key in order to handle all the backfill logic
322        $res = [];
323        foreach ( $keys as $key ) {
324            $val = $this->get( $key, $flags );
325            if ( $val !== false ) {
326                $res[$key] = $val;
327            }
328        }
329
330        return $res;
331    }
332
333    /** @inheritDoc */
334    public function setMulti( array $valueByKey, $exptime = 0, $flags = 0 ) {
335        return $this->callKeyWriteMethodOnTierCaches(
336            $this->cacheIndexes,
337            __FUNCTION__,
338            self::ARG0_KEYMAP,
339            self::RES_NONKEY,
340            func_get_args()
341        );
342    }
343
344    /** @inheritDoc */
345    public function deleteMulti( array $keys, $flags = 0 ) {
346        return $this->callKeyWriteMethodOnTierCaches(
347            $this->cacheIndexes,
348            __FUNCTION__,
349            self::ARG0_KEYARR,
350            self::RES_NONKEY,
351            func_get_args()
352        );
353    }
354
355    /** @inheritDoc */
356    public function changeTTLMulti( array $keys, $exptime, $flags = 0 ) {
357        return $this->callKeyWriteMethodOnTierCaches(
358            $this->cacheIndexes,
359            __FUNCTION__,
360            self::ARG0_KEYARR,
361            self::RES_NONKEY,
362            func_get_args()
363        );
364    }
365
366    /** @inheritDoc */
367    public function incrWithInit( $key, $exptime, $step = 1, $init = null, $flags = 0 ) {
368        return $this->callKeyWriteMethodOnTierCaches(
369            $this->cacheIndexes,
370            __FUNCTION__,
371            self::ARG0_KEY,
372            self::RES_NONKEY,
373            func_get_args()
374        );
375    }
376
377    /** @inheritDoc */
378    public function setMockTime( &$time ) {
379        parent::setMockTime( $time );
380        foreach ( $this->caches as $cache ) {
381            $cache->setMockTime( $time );
382        }
383    }
384
385    /**
386     * Call a method on the cache instance for the given cache tier (index)
387     *
388     * @param int $index Cache tier
389     * @param string $method Method name
390     * @param int $arg0Sig BagOStuff::A0_* constant describing argument 0
391     * @param int $rvSig BagOStuff::RV_* constant describing the return value
392     * @param array $args Method arguments
393     *
394     * @return mixed The result of calling the given method
395     */
396    private function callKeyMethodOnTierCache( $index, $method, $arg0Sig, $rvSig, array $args ) {
397        return $this->caches[$index]->proxyCall( $method, $arg0Sig, $rvSig, $args, $this );
398    }
399
400    /**
401     * Call a write method on the cache instances, in order, for the given tiers (indexes)
402     *
403     * @param int[] $indexes List of cache tiers
404     * @param string $method Method name
405     * @param int $arg0Sig BagOStuff::ARG0_* constant describing argument 0
406     * @param int $resSig BagOStuff::RES_* constant describing the return value
407     * @param array $args Method arguments
408     *
409     * @return mixed First synchronous result or false if any failed; null if all asynchronous
410     */
411    private function callKeyWriteMethodOnTierCaches(
412        array $indexes,
413        $method,
414        $arg0Sig,
415        $resSig,
416        array $args
417    ) {
418        $res = null;
419
420        if ( $this->asyncWrites && array_diff( $indexes, [ 0 ] ) && $method !== 'merge' ) {
421            // Deep-clone $args to prevent misbehavior when something writes an
422            // object to the BagOStuff then modifies it afterwards, e.g. T168040.
423            $args = unserialize( serialize( $args ) );
424        }
425
426        foreach ( $indexes as $i ) {
427            $cache = $this->caches[$i];
428
429            if ( $i == 0 || !$this->asyncWrites ) {
430                // Tier 0 store or in sync mode: write synchronously and get result
431                $storeRes = $cache->proxyCall( $method, $arg0Sig, $resSig, $args, $this );
432                if ( $storeRes === false ) {
433                    $res = false;
434                } elseif ( $res === null ) {
435                    // first synchronous result
436                    $res = $storeRes;
437                }
438            } else {
439                // Secondary write in async mode: do not block this HTTP request
440                ( $this->asyncHandler )(
441                    function () use ( $cache, $method, $arg0Sig, $resSig, $args ) {
442                        $cache->proxyCall( $method, $arg0Sig, $resSig, $args, $this );
443                    }
444                );
445            }
446        }
447
448        return $res;
449    }
450}
451
452/** @deprecated class alias since 1.43 */
453class_alias( MultiWriteBagOStuff::class, 'MultiWriteBagOStuff' );