Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
16.28% covered (danger)
16.28%
14 / 86
19.05% covered (danger)
19.05%
4 / 21
CRAP
0.00% covered (danger)
0.00%
0 / 1
BagOStuff
16.47% covered (danger)
16.47%
14 / 85
19.05% covered (danger)
19.05%
4 / 21
1448.30
0.00% covered (danger)
0.00%
0 / 1
 __construct
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
2.02
 setLogger
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getLogger
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getWithSetCallback
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
20
 get
n/a
0 / 0
n/a
0 / 0
0
 set
n/a
0 / 0
n/a
0 / 0
0
 delete
n/a
0 / 0
n/a
0 / 0
0
 add
n/a
0 / 0
n/a
0 / 0
0
 merge
n/a
0 / 0
n/a
0 / 0
0
 changeTTL
n/a
0 / 0
n/a
0 / 0
0
 lock
n/a
0 / 0
n/a
0 / 0
0
 unlock
n/a
0 / 0
n/a
0 / 0
0
 getScopedLock
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 deleteObjectsExpiringBefore
n/a
0 / 0
n/a
0 / 0
0
 getMulti
n/a
0 / 0
n/a
0 / 0
0
 setMulti
n/a
0 / 0
n/a
0 / 0
0
 deleteMulti
n/a
0 / 0
n/a
0 / 0
0
 changeTTLMulti
n/a
0 / 0
n/a
0 / 0
0
 incrWithInit
n/a
0 / 0
n/a
0 / 0
0
 watchErrors
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getLastError
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 setLastError
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 makeGlobalKey
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 makeKey
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isKeyGlobal
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getQoS
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getSegmentationSize
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 getSegmentedValueMaxSize
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 fieldHasFlags
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 mergeFlagMaps
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
 makeKeyInternal
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
3.04
 makeFallbackKey
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 requireConvertGenericKey
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 convertGenericKey
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 proxyCall
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
90
 getCurrentTime
n/a
0 / 0
n/a
0 / 0
2
 setMockTime
n/a
0 / 0
n/a
0 / 0
1
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 */
6
7/**
8 * @defgroup Cache BagOStuff
9 *
10 * Most important classes are:
11 *
12 * @see ObjectCacheFactory
13 * @see WANObjectCache
14 * @see BagOStuff
15 */
16
17namespace Wikimedia\ObjectCache;
18
19use InvalidArgumentException;
20use Psr\Log\LoggerAwareInterface;
21use Psr\Log\LoggerInterface;
22use Psr\Log\NullLogger;
23use Wikimedia\LightweightObjectStore\ExpirationAwareness;
24use Wikimedia\ScopedCallback;
25use Wikimedia\Stats\StatsFactory;
26
27/**
28 * Abstract class for any ephemeral data store
29 *
30 * Class instances should be created with an intended access scope for the dataset, such as:
31 *   - a) A single PHP thread on a server (e.g. stored in a PHP variable)
32 *   - b) A single application server (e.g. stored in php-apcu or sqlite)
33 *   - c) All application servers in datacenter (e.g. stored in memcached or mysql)
34 *   - d) All application servers in all datacenters (e.g. stored via mcrouter or dynomite)
35 *
36 * Callers should use the proper factory methods that yield BagOStuff instances. Site admins
37 * should make sure that the configuration for those factory methods match their access scope.
38 * BagOStuff subclasses have widely varying levels of support replication features within and
39 * among datacenters.
40 *
41 * Subclasses should override the default "segmentationSize" field with an appropriate value.
42 * The value should not be larger than what the backing store (by default) supports. It also
43 * should be roughly informed by common performance bottlenecks (e.g. values over a certain size
44 * having poor scalability). The same goes for the "segmentedValueMaxSize" member, which limits
45 * the maximum size and chunk count (indirectly) of values.
46 *
47 * A few notes about data consistency for BagOStuff instances:
48 *  - Read operation methods, e.g. get(), should be synchronous in the local datacenter.
49 *    When used with READ_LATEST, such operations should reflect any prior writes originating
50 *    from the local datacenter (e.g. by avoiding replica DBs or invoking quorom reads).
51 *  - Write operation methods, e.g. set(), should be synchronous in the local datacenter, with
52 *    asynchronous cross-datacenter replication. This replication can be either "best effort"
53 *    or eventually consistent. If the write succeeded, then any subsequent `get()` operations with
54 *    READ_LATEST, regardless of datacenter, should reflect the changes.
55 *  - Locking operation methods, e.g. lock(), unlock(), and getScopedLock(), should only apply
56 *    to the local datacenter.
57 *  - Any set of single-key write operation method calls originating from a single datacenter
58 *    should observe "best effort" linearizability.
59 *    In this context, "best effort" means that consistency holds as long as connectivity is
60 *    strong, network latency is low, and there are no relevant storage server failures.
61 *    Per https://en.wikipedia.org/wiki/PACELC_theorem, the store should act as a PA/EL
62 *    distributed system for these operations.
63 *
64 * @stable to extend
65 * @newable
66 * @ingroup Cache
67 * @copyright 2003-2004 Brooke Vibber <bvibber@wikimedia.org>
68 */
69abstract class BagOStuff implements
70    ExpirationAwareness,
71    IStoreKeyEncoder,
72    LoggerAwareInterface
73{
74    /** @var StatsFactory */
75    protected $stats;
76    /** @var LoggerInterface */
77    protected $logger;
78    /** @var callable|null */
79    protected $asyncHandler;
80    /** @var int[] Map of (BagOStuff:ATTR_* constant => BagOStuff:QOS_* constant) */
81    protected $attrMap = [];
82
83    /** @var string Default keyspace; used by makeKey() */
84    protected $keyspace;
85
86    /** @var int BagOStuff:ERR_* constant of the last error that occurred */
87    protected $lastError = self::ERR_NONE;
88    /** @var int Error event sequence number of the last error that occurred */
89    protected $lastErrorId = 0;
90
91    /** @var int Next sequence number to use for watch/error events */
92    protected static $nextErrorMonitorId = 1;
93
94    /** @var float|null */
95    private $wallClockOverride;
96
97    /** Storage operation succeeded, or no operation was performed. Exposed via getLastError(). */
98    public const ERR_NONE = 0;
99    /** Storage operation failed to yield a complete response. */
100    public const ERR_NO_RESPONSE = 1;
101    /** Storage operation could not establish a connection. */
102    public const ERR_UNREACHABLE = 2;
103    /** Storage operation failed due to usage limitations or an I/O error. */
104    public const ERR_UNEXPECTED = 3;
105
106    /**
107     * Key in getQoS() for durability of storage writes.
108     *
109     * This helps middleware distinguish between different kinds of BagOStuff
110     * implementations, without hardcoding class names, and in a way that works
111     * even through a wrapper like CachedBagOStuff, MultiWriteBagOStuff, or
112     * WANObjectCache.
113     *
114     * Value must be a QOS_DURABILITY_ constant, where higher means stronger.
115     *
116     * Example use cases:
117     *
118     * - SqlBlobStore::getCacheTTL, skip main cache if the cache is also sql-based.
119     * - MediumSpecificBagOStuff::unlock, use stricter logic if the lock is known
120     *   to be stored in the current process.
121     *
122     * @see BagOStuff::getQoS
123     */
124    public const ATTR_DURABILITY = 2;
125    /** Storage is disabled or never saves data, not even temporarily (EmptyBagOStuff). */
126    public const QOS_DURABILITY_NONE = 1;
127    /** Storage survives in memory until the end of the current request or CLI process (HashBagOStuff). */
128    public const QOS_DURABILITY_SCRIPT = 2;
129    /** Storage survives in memory until a shared service is restarted (e.g. MemcachedBagOStuff). */
130    public const QOS_DURABILITY_SERVICE = 3;
131    /**
132     * Storage survives on disk on a best-effort basis (e.g. RedisBagOStuff).
133     *
134     * Very recent writes may be lost when the service is restarted, because the storage
135     * service is not expected to synchronously flush to disk (fsync), and writes are not
136     * expected to be replicated in case of server maintenance or replacement.
137     */
138    public const QOS_DURABILITY_DISK = 4;
139    /**
140     * Storage survives on disk with high availability (SqlBagOStuff).
141     *
142     * Writes typically wait for flush to disk and/or have replication.
143     */
144    public const QOS_DURABILITY_RDBMS = 5;
145    /** Generic "unknown" value; useful for comparisons (always "good enough") */
146    public const QOS_UNKNOWN = INF;
147
148    /** Bitfield constants for get()/getMulti(); these are only advisory */
149    /** If supported, avoid reading stale data due to replication */
150    public const READ_LATEST = 1;
151    /** Promise that the caller handles detection of staleness */
152    public const READ_VERIFIED = 2;
153
154    /** Bitfield constants for set()/merge(); these are only advisory */
155    /** Only change state of the in-memory cache */
156    public const WRITE_CACHE_ONLY = 8;
157    /** Allow partitioning of the value if it is a large string */
158    public const WRITE_ALLOW_SEGMENTS = 16;
159
160    /**
161     * If supported, do not block on write operation completion; instead, treat writes as
162     * successful based on whether they could be buffered. When using this flag with methods
163     * that yield item values, the boolean "true" will be used as a placeholder. The next
164     * blocking operation (e.g. typical read) will trigger a flush of the operation buffer.
165     */
166    public const WRITE_BACKGROUND = 64;
167
168    /** Abort after the first merge conflict */
169    public const MAX_CONFLICTS_ONE = 1;
170
171    /** @var string Global keyspace; used by makeGlobalKey() */
172    protected const GLOBAL_KEYSPACE = 'global';
173    /** @var string Precomputed global cache key prefix (needs no encoding) */
174    protected const GLOBAL_PREFIX = 'global:';
175
176    /** @var int Item is a single cache key */
177    protected const ARG0_KEY = 0;
178    /** @var int Item is an array of cache keys */
179    protected const ARG0_KEYARR = 1;
180    /** @var int Item is an array indexed by cache keys */
181    protected const ARG0_KEYMAP = 2;
182    /** @var int Item does not involve any keys */
183    protected const ARG0_NONKEY = 3;
184
185    /** @var int Item is an array indexed by cache keys */
186    protected const RES_KEYMAP = 0;
187    /** @var int Item does not involve any keys */
188    protected const RES_NONKEY = 1;
189
190    /**
191     * @stable to call
192     *
193     * @param array $params Parameters include:
194     *   - keyspace: Keyspace to use for keys in makeKey(). [Default: "local"]
195     *   - stats: StatsFactory instance. [optional]
196     *   - logger: \Psr\Log\LoggerInterface instance. [optional]
197     *   - asyncHandler: Callable to use for scheduling tasks after the web request ends.
198     *       In CLI mode, it should run the task immediately. [Default: null]
199     *
200     * @phpcs:ignore Generic.Files.LineLength
201     * @phan-param array{keyspace?:string,stats?:\Wikimedia\Stats\StatsFactory,logger?:\Psr\Log\LoggerInterface,asyncHandler?:callable} $params
202     */
203    public function __construct( array $params = [] ) {
204        $this->keyspace = $params['keyspace'] ?? 'local';
205        $this->stats = $params['stats'] ?? StatsFactory::newNull();
206        $this->setLogger( $params['logger'] ?? new NullLogger() );
207
208        $asyncHandler = $params['asyncHandler'] ?? null;
209        if ( is_callable( $asyncHandler ) ) {
210            $this->asyncHandler = $asyncHandler;
211        }
212    }
213
214    /**
215     * @param LoggerInterface $logger
216     *
217     * @return void
218     */
219    public function setLogger( LoggerInterface $logger ): void {
220        $this->logger = $logger;
221    }
222
223    /**
224     * @since 1.35
225     * @return LoggerInterface
226     */
227    public function getLogger(): LoggerInterface {
228        return $this->logger;
229    }
230
231    /**
232     * Get an item, regenerating and setting it if not found
233     *
234     * The callback can take $exptime as argument by reference and modify it.
235     * Nothing is stored nor deleted if the callback returns false.
236     *
237     * @param string $key
238     * @param int $exptime Time-to-live (seconds)
239     * @param callable $callback Callback that derives the new value
240     * @param int $flags Bitfield of BagOStuff::READ_* or BagOStuff::WRITE_* constants [optional]
241     *
242     * @return mixed The cached value if found or the result of $callback otherwise
243     * @since 1.27
244     */
245    final public function getWithSetCallback( $key, $exptime, $callback, $flags = 0 ) {
246        $value = $this->get( $key, $flags );
247
248        if ( $value === false ) {
249            $value = $callback( $exptime );
250            if ( $value !== false && $exptime >= 0 ) {
251                $this->set( $key, $value, $exptime, $flags );
252            }
253        }
254
255        return $value;
256    }
257
258    /**
259     * Get an item
260     *
261     * If the key includes a deterministic input hash (e.g. the key can only have
262     * the correct value) or complete staleness checks are handled by the caller
263     * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
264     * This lets tiered backends know they can safely upgrade a cached value to
265     * higher tiers using standard TTLs.
266     *
267     * @param string $key
268     * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
269     *
270     * @return mixed Returns false on failure or if the item does not exist
271     */
272    abstract public function get( $key, $flags = 0 );
273
274    /**
275     * Set an item
276     *
277     * @param string $key
278     * @param mixed $value
279     * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
280     * @param int $flags Bitfield of BagOStuff::WRITE_* constants
281     *  If setting WRITE_ALLOW_SEGMENTS, remember to also set it in any delete() calls.
282     * @return bool Success
283     */
284    abstract public function set( $key, $value, $exptime = 0, $flags = 0 );
285
286    /**
287     * Delete an item if it exists
288     *
289     * For large values set with WRITE_ALLOW_SEGMENTS, this only deletes the placeholder
290     * key with the segment list. To delete the underlying blobs, include WRITE_ALLOW_SEGMENTS
291     * in the flags for delete() as well. While deleting the segment list key has the effect of
292     * functionally deleting the key, it leaves unused blobs in storage.
293     *
294     * The reason that this is not done automatically, is that to delete underlying blobs,
295     * requires first fetching the current segment list. Given that 99% of keys don't use
296     * WRITE_ALLOW_SEGMENTS, this would be wasteful.
297     *
298     * @param string $key
299     * @param int $flags Bitfield of BagOStuff::WRITE_* constants
300     * @return bool Success (item deleted or not found)
301     */
302    abstract public function delete( $key, $flags = 0 );
303
304    /**
305     * Insert an item if it does not already exist
306     *
307     * @param string $key
308     * @param mixed $value
309     * @param int $exptime
310     * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
311     *
312     * @return bool Success (item created)
313     */
314    abstract public function add( $key, $value, $exptime = 0, $flags = 0 );
315
316    /**
317     * Merge changes into the existing cache value (possibly creating a new one)
318     *
319     * The callback function returns the new value given the current value
320     * (which will be false if not present), and takes the arguments:
321     * (this BagOStuff, cache key, current value, TTL).
322     * The TTL parameter is reference set to $exptime. It can be overridden in the callback.
323     * Nothing is stored nor deleted if the callback returns false.
324     *
325     * @param string $key
326     * @param callable $callback Callback method to be executed
327     * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
328     * @param int $attempts The amount of times to attempt a merge in case of failure
329     * @param int $flags Bitfield of BagOStuff::WRITE_* constants
330     *
331     * @return bool Success
332     */
333    abstract public function merge(
334        $key,
335        callable $callback,
336        $exptime = 0,
337        $attempts = 10,
338        $flags = 0
339    );
340
341    /**
342     * Change the expiration on an item
343     *
344     * If an expiry in the past is given then the key will immediately be expired
345     *
346     * For large values written using WRITE_ALLOW_SEGMENTS, this only changes the TTL of the
347     * main segment list key. While lowering the TTL of the segment list key has the effect of
348     * functionally lowering the TTL of the key, it might leave unused blobs in cache for longer.
349     * Raising the TTL of such keys is not effective, since the expiration of a single segment
350     * key effectively expires the entire value.
351     *
352     * @param string $key
353     * @param int $exptime TTL or UNIX timestamp
354     * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
355     *
356     * @return bool Success (item found and updated)
357     * @since 1.28
358     */
359    abstract public function changeTTL( $key, $exptime = 0, $flags = 0 );
360
361    /**
362     * Acquire an advisory lock on a key string, exclusive to the caller
363     *
364     * @param string $key
365     * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
366     * @param int $exptime Lock time-to-live in seconds; 1 day maximum [optional]
367     * @param string $rclass If this thread already holds the lock, and the lock was acquired
368     *  using the same value for this parameter, then return true and use reference counting so
369     *  that only the unlock() call from the outermost lock() caller actually releases the lock
370     *  (note that only the outermost time-to-live is used) [optional]
371     *
372     * @return bool Success
373     */
374    abstract public function lock( $key, $timeout = 6, $exptime = 6, $rclass = '' );
375
376    /**
377     * Release an advisory lock on a key string
378     *
379     * @param string $key
380     *
381     * @return bool Success
382     */
383    abstract public function unlock( $key );
384
385    /**
386     * Get a lightweight exclusive self-unlocking lock
387     *
388     * Note that the same lock cannot be acquired twice.
389     *
390     * This is useful for task de-duplication or to avoid obtrusive
391     * (though non-corrupting) DB errors like INSERT key conflicts
392     * or deadlocks when using LOCK IN SHARE MODE.
393     *
394     * @param string $key
395     * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
396     * @param int $exptime Lock time-to-live [optional]; 1 day maximum
397     * @param string $rclass Allow reentry if set and the current lock used this value
398     *
399     * @since 1.26
400     */
401    #[\NoDiscard]
402    final public function getScopedLock( $key, $timeout = 6, $exptime = 30, $rclass = '' ): ?ScopedCallback {
403        $exptime = min( $exptime ?: INF, self::TTL_DAY );
404
405        if ( !$this->lock( $key, $timeout, $exptime, $rclass ) ) {
406            return null;
407        }
408
409        return new ScopedCallback( function () use ( $key ) {
410            $this->unlock( $key );
411        } );
412    }
413
414    /**
415     * Delete all objects expiring before a certain date
416     *
417     * @param string|int $timestamp The reference date in MW or TS::UNIX format
418     * @param callable|null $progress Optional, a function which will be called
419     *     regularly during long-running operations with the percentage progress
420     *     as the first parameter. [optional]
421     * @param int|float $limit Maximum number of keys to delete [default: INF]
422     * @param string|null $tag Tag to purge a single shard only.
423     *  This is only supported when server tags are used in configuration.
424     *
425     * @return bool Success; false if unimplemented
426     */
427    abstract public function deleteObjectsExpiringBefore(
428        $timestamp,
429        ?callable $progress = null,
430        $limit = INF,
431        ?string $tag = null
432    );
433
434    /**
435     * Get a batch of items
436     *
437     * @param string[] $keys List of keys
438     * @param int $flags Bitfield; supports READ_LATEST [optional]
439     *
440     * @return mixed[] Map of (key => value) for existing keys
441     */
442    abstract public function getMulti( array $keys, $flags = 0 );
443
444    /**
445     * Set a batch of items
446     *
447     * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O
448     *
449     * WRITE_BACKGROUND can be used for bulk insertion where the response is not vital
450     *
451     * @param mixed[] $valueByKey Map of (key => value)
452     * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
453     * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
454     *
455     * @return bool Success
456     * @since 1.24
457     */
458    abstract public function setMulti( array $valueByKey, $exptime = 0, $flags = 0 );
459
460    /**
461     * Delete a batch of items
462     *
463     * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O
464     *
465     * WRITE_BACKGROUND can be used for bulk deletion where the response is not vital
466     *
467     * @param string[] $keys List of keys
468     * @param int $flags Bitfield of BagOStuff::WRITE_* constants
469     * @return bool Success (items deleted and/or not found)
470     * @since 1.33
471     */
472    abstract public function deleteMulti( array $keys, $flags = 0 );
473
474    /**
475     * Change the expiration of multiple items
476     *
477     * @see BagOStuff::changeTTL()
478     *
479     * @param string[] $keys List of keys
480     * @param int $exptime TTL or UNIX timestamp
481     * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
482     *
483     * @return bool Success (all items found and updated)
484     * @since 1.34
485     */
486    abstract public function changeTTLMulti( array $keys, $exptime, $flags = 0 );
487
488    /**
489     * Increase the value of the given key (no TTL change) if it exists or create it otherwise
490     *
491     * This will create the key with the value $init and TTL $exptime instead if not present.
492     * Callers should make sure that both ($init - $step) and $exptime are invariants for all
493     * operations to any given key. The value of $init should be at least that of $step.
494     *
495     * The new value is returned, except if the WRITE_BACKGROUND flag is given, in which case
496     * the handler may choose to return true to indicate that the operation has been dispatched.
497     *
498     * @param string $key Key built via makeKey() or makeGlobalKey()
499     * @param int $exptime Time-to-live (in seconds) or a UNIX timestamp expiration
500     * @param int $step Amount to increase the key value by [default: 1]
501     * @param int|null $init Value to initialize the key to if it does not exist [default: $step]
502     * @param int $flags Bit field of class WRITE_* constants [optional]
503     *
504     * @return int|bool New value (or true if asynchronous) on success; false on failure
505     * @since 1.24
506     */
507    abstract public function incrWithInit( $key, $exptime, $step = 1, $init = null, $flags = 0 );
508
509    /**
510     * Get a "watch point" token that can be used to get the "last error" to occur after now
511     *
512     * @return int A token to that can be used with getLastError()
513     * @since 1.38
514     */
515    public function watchErrors() {
516        return self::$nextErrorMonitorId++;
517    }
518
519    /**
520     * Get the "last error" registry
521     *
522     * The method should be invoked by a caller as part of the following pattern:
523     *   - The caller invokes watchErrors() to get a "since token"
524     *   - The caller invokes a sequence of cache operation methods
525     *   - The caller invokes getLastError() with the "since token"
526     *
527     * External callers can also invoke this method as part of the following pattern:
528     *   - The caller invokes clearLastError()
529     *   - The caller invokes a sequence of cache operation methods
530     *   - The caller invokes getLastError()
531     *
532     * @param int $watchPoint Only consider errors from after this "watch point" [optional]
533     *
534     * @return int BagOStuff:ERR_* constant for the "last error" registry
535     * @note Parameters added in 1.38: $watchPoint
536     * @since 1.23
537     */
538    public function getLastError( $watchPoint = 0 ) {
539        return ( $this->lastErrorId > $watchPoint ) ? $this->lastError : self::ERR_NONE;
540    }
541
542    /**
543     * Set the "last error" registry due to a problem encountered during an attempted operation
544     *
545     * @param int $error BagOStuff:ERR_* constant
546     *
547     * @since 1.23
548     */
549    protected function setLastError( $error ) {
550        $this->lastError = $error;
551        $this->lastErrorId = self::$nextErrorMonitorId++;
552    }
553
554    /**
555     * Make a cache key from the given components, in the "global" keyspace
556     *
557     * Global keys are shared with and visible to all sites hosted in the same
558     * infrastructure (e.g. cross-wiki within the same wiki farm). Others sites
559     * may read the stored value from their requests, and they must be able to
560     * correctly compute new values from their own request context.
561     *
562     * @see BagOStuff::makeKeyInternal
563     * @since 1.27
564     * @param string $keygroup Key group component, should be under 48 characters.
565     * @param string|int ...$components Additional, ordered, key components for entity IDs
566     * @return string Colon-separated, keyspace-prepended, ordered list of encoded components
567     */
568    public function makeGlobalKey( $keygroup, ...$components ) {
569        return $this->makeKeyInternal( self::GLOBAL_KEYSPACE, func_get_args() );
570    }
571
572    /**
573     * Make a cache key from the given components, in the default keyspace
574     *
575     * The default keyspace is unique to a given site. Subsequent web requests
576     * to the same site (e.g. local wiki, or same domain name) will interact
577     * with the same keyspace.
578     *
579     * Requests to other sites hosted on the same infrastructure (e.g. cross-wiki
580     * or cross-domain), have their own keyspace that naturally avoids conflicts.
581     *
582     * As caller you are responsible for:
583     * - Limit the key group (first component) to 48 characters
584     *
585     * Internally, the colon is used as delimiter (":"), and this is
586     * automatically escaped in supplied components to avoid ambiguity or
587     * key conflicts. BagOStuff subclasses are responsible for applying any
588     * additional escaping or limits as-needed before sending commands over
589     * the network.
590     *
591     * @see BagOStuff::makeKeyInternal
592     * @since 1.27
593     * @param string $keygroup Key group component, should be under 48 characters.
594     * @param string|int ...$components Additional, ordered, key components for entity IDs
595     * @return string Colon-separated, keyspace-prepended, ordered list of encoded components
596     */
597    public function makeKey( $keygroup, ...$components ) {
598        return $this->makeKeyInternal( $this->keyspace, func_get_args() );
599    }
600
601    /**
602     * Check whether a cache key is in the global keyspace
603     *
604     * @param string $key
605     * @return bool
606     * @since 1.35
607     */
608    public function isKeyGlobal( $key ) {
609        return str_starts_with( $key, self::GLOBAL_PREFIX );
610    }
611
612    /**
613     * @param int $flag BagOStuff::ATTR_* constant
614     *
615     * @return int BagOStuff:QOS_* constant
616     * @since 1.28
617     */
618    public function getQoS( $flag ) {
619        return $this->attrMap[$flag] ?? self::QOS_UNKNOWN;
620    }
621
622    /**
623     * @deprecated since 1.43, not used anywhere.
624     * @return int|float The chunk size, in bytes, of segmented objects (INF for no limit)
625     * @since 1.34
626     */
627    public function getSegmentationSize() {
628        wfDeprecated( __METHOD__, '1.43' );
629
630        return INF;
631    }
632
633    /**
634     * @deprecated since 1.43, not used anywhere.
635     * @return int|float Maximum total segmented object size in bytes (INF for no limit)
636     * @since 1.34
637     */
638    public function getSegmentedValueMaxSize() {
639        wfDeprecated( __METHOD__, '1.43' );
640
641        return INF;
642    }
643
644    /**
645     * @param int $field
646     * @param int $flags
647     *
648     * @return bool
649     * @since 1.34
650     */
651    final protected function fieldHasFlags( $field, $flags ) {
652        return ( ( $field & $flags ) === $flags );
653    }
654
655    /**
656     * Merge the flag maps of one or more BagOStuff objects into a "lowest common denominator" map
657     *
658     * @param BagOStuff[] $bags
659     *
660     * @return int[] Resulting flag map (class ATTR_* constant => class QOS_* constant)
661     */
662    final protected function mergeFlagMaps( array $bags ) {
663        $map = [];
664        foreach ( $bags as $bag ) {
665            foreach ( $bag->attrMap as $attr => $rank ) {
666                if ( isset( $map[$attr] ) ) {
667                    $map[$attr] = min( $map[$attr], $rank );
668                } else {
669                    $map[$attr] = $rank;
670                }
671            }
672        }
673
674        return $map;
675    }
676
677    /**
678     * Make a cache key for the given keyspace and components
679     *
680     * Subclasses may override this method to apply different escaping,
681     * or to deal with size constraints (such as MemcachedBagOStuff).
682     * For example, by converting long components into hashes.
683     *
684     * If you override this method, you MUST override ::requireConvertGenericKey()
685     * to return true. This ensures that wrapping classes (e.g. MultiWriteBagOStuff)
686     * know to re-encode keys before calling read/write methods. See also ::proxyCall().
687     *
688     * @see BagOStuff::proxyCall
689     * @since 1.27
690     *
691     * @param string $keyspace
692     * @param string[]|int[]|null[] $components Key group and other components
693     *
694     * @return string
695     */
696    protected function makeKeyInternal( $keyspace, $components ) {
697        if ( count( $components ) < 1 ) {
698            throw new InvalidArgumentException( "Missing key group" );
699        }
700
701        $key = $keyspace;
702        foreach ( $components as $component ) {
703            // Escape delimiter (":") and escape ("%") characters
704            $key .= ':' . strtr( $component ?? '', [ '%' => '%25', ':' => '%3A' ] );
705        }
706
707        return $key;
708    }
709
710    /**
711     * Re-format a cache key that is too long.
712     *
713     * @since 1.45
714     * @see BagOStuff::makeKeyInternal
715     * @param string $key
716     * @param int $maxLength
717     * @return string
718     */
719    protected function makeFallbackKey( string $key, int $maxLength ) {
720        if ( strlen( $key ) > $maxLength ) {
721            // Components are "<0=keyspace>:<1=keygroup>:<others...>"
722            $components = str_replace( [ '%3A', '%25' ], [ ':', '%' ], explode( ':', $key ) );
723            if ( count( $components ) < 2 ) {
724                throw new InvalidArgumentException( 'Key lacks keyspace' );
725            }
726
727            // Prefer to preserve the keygroup for statistics.
728            // Try "mywiki:mykeygroup:#<64-char hash>"
729            // This gives 138 chars (205-64-3) for the keyspace and keygroup.
730            $hash = hash( 'sha256', $key );
731            $key = $components[0] . ':' . $components[1] . ':#' . $hash;
732            if ( strlen( $key ) > $maxLength ) {
733                // Try "mywiki:BagOStuff-long-key:##<64-char hash>"
734                // Might be legacy code that passes a long string as the key without a keygroup.
735                $key = $components[0] . ':BagOStuff-long-key:##' . $hash;
736            }
737        }
738
739        return $key;
740    }
741
742    /**
743     * Whether ::proxyCall() must re-encode cache keys before calling read/write methods.
744     *
745     * @stable to override
746     * @see BagOStuff::makeKeyInternal
747     * @see BagOStuff::proxyCall
748     * @since 1.41
749     * @return bool
750     */
751    protected function requireConvertGenericKey(): bool {
752        return false;
753    }
754
755    /**
756     * Convert a key from BagOStuff::makeKeyInternal into one for the current subclass
757     *
758     * @see BagOStuff::proxyCall
759     *
760     * @param string $key Result from BagOStuff::makeKeyInternal
761     *
762     * @return string Result from current subclass override of BagOStuff::makeKeyInternal
763     */
764    private function convertGenericKey( $key ) {
765        if ( !$this->requireConvertGenericKey() ) {
766            // If subclass doesn't overwrite makeKeyInternal, no re-encoding is needed.
767            return $key;
768        }
769
770        // Extract the components from a "generic" key formatted by BagOStuff::makeKeyInternal()
771        // Note that the order of each corresponding search/replace pair matters!
772        $components = str_replace( [ '%3A', '%25' ], [ ':', '%' ], explode( ':', $key ) );
773        if ( count( $components ) < 2 ) {
774            // Legacy key, not even formatted by makeKey()/makeGlobalKey(). Keep as-is.
775            return $key;
776        }
777
778        $keyspace = array_shift( $components );
779
780        return $this->makeKeyInternal( $keyspace, $components );
781    }
782
783    /**
784     * Call a method on behalf of wrapper BagOStuff instance
785     *
786     * The "wrapper" BagOStuff subclass that calls proxyCall() MUST NOT override
787     * the default makeKeyInternal() implementation, because proxyCall() needs
788     * to turn the "generic" key back into an array, and re-format it according
789     * to the backend-specific BagOStuff::makeKey implementation.
790     *
791     * For example, when using MultiWriteBagOStuff with Memcached as a backend,
792     * writes will go via MemcachedBagOStuff::proxyCall(), which then reformats
793     * the "generic" result of BagOStuff::makeKey (called as MultiWriteBagOStuff::makeKey)
794     * using MemcachedBagOStuff::makeKeyInternal.
795     *
796     * @param string $method Name of a non-final public method that reads/changes keys
797     * @param int $arg0Sig BagOStuff::ARG0_* constant describing argument 0
798     * @param int $resSig BagOStuff::RES_* constant describing the return value
799     * @param array $genericArgs Method arguments passed to the wrapper instance
800     * @param BagOStuff $wrapper The wrapper BagOStuff instance using this result
801     *
802     * @return mixed Method result with any keys remapped to "generic" keys
803     */
804    protected function proxyCall(
805        string $method,
806        int $arg0Sig,
807        int $resSig,
808        array $genericArgs,
809        BagOStuff $wrapper
810    ) {
811        // Get the corresponding store-specific cache keys...
812        $storeArgs = $genericArgs;
813        switch ( $arg0Sig ) {
814            case self::ARG0_KEY:
815                $storeArgs[0] = $this->convertGenericKey( $genericArgs[0] );
816                break;
817            case self::ARG0_KEYARR:
818                foreach ( $genericArgs[0] as $i => $genericKey ) {
819                    $storeArgs[0][$i] = $this->convertGenericKey( $genericKey );
820                }
821                break;
822            case self::ARG0_KEYMAP:
823                $storeArgs[0] = [];
824                foreach ( $genericArgs[0] as $genericKey => $v ) {
825                    $storeArgs[0][$this->convertGenericKey( $genericKey )] = $v;
826                }
827                break;
828        }
829
830        // Result of invoking the method with the corresponding store-specific cache keys
831        $watchPoint = $this->watchErrors();
832        $storeRes = $this->$method( ...$storeArgs );
833        $lastError = $this->getLastError( $watchPoint );
834        if ( $lastError !== self::ERR_NONE ) {
835            $wrapper->setLastError( $lastError );
836        }
837
838        // Convert any store-specific cache keys in the result back to generic cache keys
839        if ( $resSig === self::RES_KEYMAP ) {
840            // Map of (store-specific cache key => generic cache key)
841            $genericKeyByStoreKey = array_combine( $storeArgs[0], $genericArgs[0] );
842
843            $genericRes = [];
844            foreach ( $storeRes as $storeKey => $value ) {
845                $genericRes[$genericKeyByStoreKey[$storeKey]] = $value;
846            }
847        } else {
848            $genericRes = $storeRes;
849        }
850
851        return $genericRes;
852    }
853
854    /**
855     * @internal For testing only
856     * @return float UNIX timestamp
857     * @codeCoverageIgnore
858     */
859    public function getCurrentTime() {
860        return $this->wallClockOverride ?: microtime( true );
861    }
862
863    /**
864     * @internal For testing only
865     *
866     * @param float|null &$time Mock UNIX timestamp
867     *
868     * @codeCoverageIgnore
869     */
870    public function setMockTime( &$time ) {
871        $this->wallClockOverride =& $time;
872    }
873}
874
875/** @deprecated class alias since 1.43 */
876class_alias( BagOStuff::class, 'BagOStuff' );