SpecialBlock [Vue]: load extension-provided messages
[mediawiki.git] / includes / libs / objectcache / BagOStuff.php
bloba2337caa8e82b3c2ab71197cbc375be0ba75acb3
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
18 * @file
21 /**
22 * @defgroup Cache BagOStuff
24 * Most important classes are:
26 * @see ObjectCacheFactory
27 * @see WANObjectCache
28 * @see BagOStuff
31 namespace Wikimedia\ObjectCache;
33 use InvalidArgumentException;
34 use Psr\Log\LoggerAwareInterface;
35 use Psr\Log\LoggerInterface;
36 use Psr\Log\NullLogger;
37 use Wikimedia\LightweightObjectStore\ExpirationAwareness;
38 use Wikimedia\LightweightObjectStore\StorageAwareness;
39 use Wikimedia\ScopedCallback;
40 use Wikimedia\Stats\StatsFactory;
42 /**
43 * Abstract class for any ephemeral data store
45 * Class instances should be created with an intended access scope for the dataset, such as:
46 * - a) A single PHP thread on a server (e.g. stored in a PHP variable)
47 * - b) A single application server (e.g. stored in php-apcu or sqlite)
48 * - c) All application servers in datacenter (e.g. stored in memcached or mysql)
49 * - d) All application servers in all datacenters (e.g. stored via mcrouter or dynomite)
51 * Callers should use the proper factory methods that yield BagOStuff instances. Site admins
52 * should make sure that the configuration for those factory methods match their access scope.
53 * BagOStuff subclasses have widely varying levels of support replication features within and
54 * among datacenters.
56 * Subclasses should override the default "segmentationSize" field with an appropriate value.
57 * The value should not be larger than what the backing store (by default) supports. It also
58 * should be roughly informed by common performance bottlenecks (e.g. values over a certain size
59 * having poor scalability). The same goes for the "segmentedValueMaxSize" member, which limits
60 * the maximum size and chunk count (indirectly) of values.
62 * A few notes about data consistency for BagOStuff instances:
63 * - Read operation methods, e.g. get(), should be synchronous in the local datacenter.
64 * When used with READ_LATEST, such operations should reflect any prior writes originating
65 * from the local datacenter (e.g. by avoiding replica DBs or invoking quorom reads).
66 * - Write operation methods, e.g. set(), should be synchronous in the local datacenter, with
67 * asynchronous cross-datacenter replication. This replication can be either "best effort"
68 * or eventually consistent. If the write succeeded, then any subsequent `get()` operations with
69 * READ_LATEST, regardless of datacenter, should reflect the changes.
70 * - Locking operation methods, e.g. lock(), unlock(), and getScopedLock(), should only apply
71 * to the local datacenter.
72 * - Any set of single-key write operation method calls originating from a single datacenter
73 * should observe "best effort" linearizability.
74 * In this context, "best effort" means that consistency holds as long as connectivity is
75 * strong, network latency is low, and there are no relevant storage server failures.
76 * Per https://en.wikipedia.org/wiki/PACELC_theorem, the store should act as a PA/EL
77 * distributed system for these operations.
79 * @stable to extend
80 * @newable
81 * @ingroup Cache
82 * @copyright 2003-2004 Brooke Vibber <bvibber@wikimedia.org>
84 abstract class BagOStuff implements
85 ExpirationAwareness,
86 StorageAwareness,
87 IStoreKeyEncoder,
88 LoggerAwareInterface
90 /** @var StatsFactory */
91 protected $stats;
92 /** @var LoggerInterface */
93 protected $logger;
94 /** @var callable|null */
95 protected $asyncHandler;
96 /** @var int[] Map of (BagOStuff:ATTR_* constant => BagOStuff:QOS_* constant) */
97 protected $attrMap = [];
99 /** @var string Default keyspace; used by makeKey() */
100 protected $keyspace;
102 /** @var int BagOStuff:ERR_* constant of the last error that occurred */
103 protected $lastError = self::ERR_NONE;
104 /** @var int Error event sequence number of the last error that occurred */
105 protected $lastErrorId = 0;
107 /** @var int Next sequence number to use for watch/error events */
108 protected static $nextErrorMonitorId = 1;
110 /** @var float|null */
111 private $wallClockOverride;
113 /** Bitfield constants for get()/getMulti(); these are only advisory */
114 /** If supported, avoid reading stale data due to replication */
115 public const READ_LATEST = 1;
116 /** Promise that the caller handles detection of staleness */
117 public const READ_VERIFIED = 2;
119 /** Bitfield constants for set()/merge(); these are only advisory */
120 /** Only change state of the in-memory cache */
121 public const WRITE_CACHE_ONLY = 8;
122 /** Allow partitioning of the value if it is a large string */
123 public const WRITE_ALLOW_SEGMENTS = 16;
125 * Delete all the segments if the value is partitioned
126 * @deprecated since 1.43 Use WRITE_ALLOW_SEGMENTS instead.
128 public const WRITE_PRUNE_SEGMENTS = self::WRITE_ALLOW_SEGMENTS;
130 * If supported, do not block on write operation completion; instead, treat writes as
131 * succesful based on whether they could be buffered. When using this flag with methods
132 * that yield item values, the boolean "true" will be used as a placeholder. The next
133 * blocking operation (e.g. typical read) will trigger a flush of the operation buffer.
135 public const WRITE_BACKGROUND = 64;
137 /** Abort after the first merge conflict */
138 public const MAX_CONFLICTS_ONE = 1;
140 /** @var string Global keyspace; used by makeGlobalKey() */
141 protected const GLOBAL_KEYSPACE = 'global';
142 /** @var string Precomputed global cache key prefix (needs no encoding) */
143 protected const GLOBAL_PREFIX = 'global:';
145 /** @var int Item is a single cache key */
146 protected const ARG0_KEY = 0;
147 /** @var int Item is an array of cache keys */
148 protected const ARG0_KEYARR = 1;
149 /** @var int Item is an array indexed by cache keys */
150 protected const ARG0_KEYMAP = 2;
151 /** @var int Item does not involve any keys */
152 protected const ARG0_NONKEY = 3;
154 /** @var int Item is an array indexed by cache keys */
155 protected const RES_KEYMAP = 0;
156 /** @var int Item does not involve any keys */
157 protected const RES_NONKEY = 1;
160 * @stable to call
162 * @param array $params Parameters include:
163 * - keyspace: Keyspace to use for keys in makeKey(). [Default: "local"]
164 * - asyncHandler: Callable to use for scheduling tasks after the web request ends.
165 * In CLI mode, it should run the task immediately. [Default: null]
166 * - stats: IStatsdDataFactory instance. [optional]
167 * - logger: \Psr\Log\LoggerInterface instance. [optional]
169 * @phan-param array{keyspace?:string,logger?:\Psr\Log\LoggerInterface,asyncHandler?:callable} $params
171 public function __construct( array $params = [] ) {
172 $this->keyspace = $params['keyspace'] ?? 'local';
173 $this->stats = $params['stats'] ?? StatsFactory::newNull();
174 $this->setLogger( $params['logger'] ?? new NullLogger() );
176 $asyncHandler = $params['asyncHandler'] ?? null;
177 if ( is_callable( $asyncHandler ) ) {
178 $this->asyncHandler = $asyncHandler;
183 * @param LoggerInterface $logger
185 * @return void
187 public function setLogger( LoggerInterface $logger ) {
188 $this->logger = $logger;
192 * @since 1.35
193 * @return LoggerInterface
195 public function getLogger(): LoggerInterface {
196 return $this->logger;
200 * Get an item, regenerating and setting it if not found
202 * The callback can take $exptime as argument by reference and modify it.
203 * Nothing is stored nor deleted if the callback returns false.
205 * @param string $key
206 * @param int $exptime Time-to-live (seconds)
207 * @param callable $callback Callback that derives the new value
208 * @param int $flags Bitfield of BagOStuff::READ_* or BagOStuff::WRITE_* constants [optional]
210 * @return mixed The cached value if found or the result of $callback otherwise
211 * @since 1.27
213 final public function getWithSetCallback( $key, $exptime, $callback, $flags = 0 ) {
214 $value = $this->get( $key, $flags );
216 if ( $value === false ) {
217 $value = $callback( $exptime );
218 if ( $value !== false && $exptime >= 0 ) {
219 $this->set( $key, $value, $exptime, $flags );
223 return $value;
227 * Get an item
229 * If the key includes a deterministic input hash (e.g. the key can only have
230 * the correct value) or complete staleness checks are handled by the caller
231 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
232 * This lets tiered backends know they can safely upgrade a cached value to
233 * higher tiers using standard TTLs.
235 * @param string $key
236 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
238 * @return mixed Returns false on failure or if the item does not exist
240 abstract public function get( $key, $flags = 0 );
243 * Set an item
245 * @param string $key
246 * @param mixed $value
247 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
248 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
249 * If setting WRITE_ALLOW_SEGMENTS, remember to also set it in any delete() calls.
250 * @return bool Success
252 abstract public function set( $key, $value, $exptime = 0, $flags = 0 );
255 * Delete an item if it exists
257 * For large values set with WRITE_ALLOW_SEGMENTS, this only deletes the placeholder
258 * key with the segment list. To delete the underlying blobs, include WRITE_ALLOW_SEGMENTS
259 * in the flags for delete() as well. While deleting the segment list key has the effect of
260 * functionally deleting the key, it leaves unused blobs in storage.
262 * The reason that this is not done automatically, is that to delete underlying blobs,
263 * requires first fetching the current segment list. Given that 99% of keys don't use
264 * WRITE_ALLOW_SEGMENTS, this would be wasteful.
266 * @param string $key
267 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
268 * @return bool Success (item deleted or not found)
270 abstract public function delete( $key, $flags = 0 );
273 * Insert an item if it does not already exist
275 * @param string $key
276 * @param mixed $value
277 * @param int $exptime
278 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
280 * @return bool Success (item created)
282 abstract public function add( $key, $value, $exptime = 0, $flags = 0 );
285 * Merge changes into the existing cache value (possibly creating a new one)
287 * The callback function returns the new value given the current value
288 * (which will be false if not present), and takes the arguments:
289 * (this BagOStuff, cache key, current value, TTL).
290 * The TTL parameter is reference set to $exptime. It can be overridden in the callback.
291 * Nothing is stored nor deleted if the callback returns false.
293 * @param string $key
294 * @param callable $callback Callback method to be executed
295 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
296 * @param int $attempts The amount of times to attempt a merge in case of failure
297 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
299 * @return bool Success
301 abstract public function merge(
302 $key,
303 callable $callback,
304 $exptime = 0,
305 $attempts = 10,
306 $flags = 0
310 * Change the expiration on an item
312 * If an expiry in the past is given then the key will immediately be expired
314 * For large values written using WRITE_ALLOW_SEGMENTS, this only changes the TTL of the
315 * main segment list key. While lowering the TTL of the segment list key has the effect of
316 * functionally lowering the TTL of the key, it might leave unused blobs in cache for longer.
317 * Raising the TTL of such keys is not effective, since the expiration of a single segment
318 * key effectively expires the entire value.
320 * @param string $key
321 * @param int $exptime TTL or UNIX timestamp
322 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
324 * @return bool Success (item found and updated)
325 * @since 1.28
327 abstract public function changeTTL( $key, $exptime = 0, $flags = 0 );
330 * Acquire an advisory lock on a key string, exclusive to the caller
332 * @param string $key
333 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
334 * @param int $exptime Lock time-to-live in seconds; 1 day maximum [optional]
335 * @param string $rclass If this thread already holds the lock, and the lock was acquired
336 * using the same value for this parameter, then return true and use reference counting so
337 * that only the unlock() call from the outermost lock() caller actually releases the lock
338 * (note that only the outermost time-to-live is used) [optional]
340 * @return bool Success
342 abstract public function lock( $key, $timeout = 6, $exptime = 6, $rclass = '' );
345 * Release an advisory lock on a key string
347 * @param string $key
349 * @return bool Success
351 abstract public function unlock( $key );
354 * Get a lightweight exclusive self-unlocking lock
356 * Note that the same lock cannot be acquired twice.
358 * This is useful for task de-duplication or to avoid obtrusive
359 * (though non-corrupting) DB errors like INSERT key conflicts
360 * or deadlocks when using LOCK IN SHARE MODE.
362 * @param string $key
363 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
364 * @param int $exptime Lock time-to-live [optional]; 1 day maximum
365 * @param string $rclass Allow reentry if set and the current lock used this value
367 * @return ScopedCallback|null Returns null on failure
368 * @since 1.26
370 final public function getScopedLock( $key, $timeout = 6, $exptime = 30, $rclass = '' ) {
371 $exptime = min( $exptime ?: INF, self::TTL_DAY );
373 if ( !$this->lock( $key, $timeout, $exptime, $rclass ) ) {
374 return null;
377 return new ScopedCallback( function () use ( $key ) {
378 $this->unlock( $key );
379 } );
383 * Delete all objects expiring before a certain date
385 * @param string|int $timestamp The reference date in MW or TS_UNIX format
386 * @param callable|null $progress Optional, a function which will be called
387 * regularly during long-running operations with the percentage progress
388 * as the first parameter. [optional]
389 * @param int|float $limit Maximum number of keys to delete [default: INF]
390 * @param string|null $tag Tag to purge a single shard only.
391 * This is only supported when server tags are used in configuration.
393 * @return bool Success; false if unimplemented
395 abstract public function deleteObjectsExpiringBefore(
396 $timestamp,
397 ?callable $progress = null,
398 $limit = INF,
399 ?string $tag = null
403 * Get a batch of items
405 * @param string[] $keys List of keys
406 * @param int $flags Bitfield; supports READ_LATEST [optional]
408 * @return mixed[] Map of (key => value) for existing keys
410 abstract public function getMulti( array $keys, $flags = 0 );
413 * Set a batch of items
415 * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O
417 * WRITE_BACKGROUND can be used for bulk insertion where the response is not vital
419 * @param mixed[] $valueByKey Map of (key => value)
420 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
421 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
423 * @return bool Success
424 * @since 1.24
426 abstract public function setMulti( array $valueByKey, $exptime = 0, $flags = 0 );
429 * Delete a batch of items
431 * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O
433 * WRITE_BACKGROUND can be used for bulk deletion where the response is not vital
435 * @param string[] $keys List of keys
436 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
437 * @return bool Success (items deleted and/or not found)
438 * @since 1.33
440 abstract public function deleteMulti( array $keys, $flags = 0 );
443 * Change the expiration of multiple items
445 * @see BagOStuff::changeTTL()
447 * @param string[] $keys List of keys
448 * @param int $exptime TTL or UNIX timestamp
449 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
451 * @return bool Success (all items found and updated)
452 * @since 1.34
454 abstract public function changeTTLMulti( array $keys, $exptime, $flags = 0 );
457 * Increase the value of the given key (no TTL change) if it exists or create it otherwise
459 * This will create the key with the value $init and TTL $exptime instead if not present.
460 * Callers should make sure that both ($init - $step) and $exptime are invariants for all
461 * operations to any given key. The value of $init should be at least that of $step.
463 * The new value is returned, except if the WRITE_BACKGROUND flag is given, in which case
464 * the handler may choose to return true to indicate that the operation has been dispatched.
466 * @param string $key Key built via makeKey() or makeGlobalKey()
467 * @param int $exptime Time-to-live (in seconds) or a UNIX timestamp expiration
468 * @param int $step Amount to increase the key value by [default: 1]
469 * @param int|null $init Value to initialize the key to if it does not exist [default: $step]
470 * @param int $flags Bit field of class WRITE_* constants [optional]
472 * @return int|bool New value (or true if asynchronous) on success; false on failure
473 * @since 1.24
475 abstract public function incrWithInit( $key, $exptime, $step = 1, $init = null, $flags = 0 );
478 * Get a "watch point" token that can be used to get the "last error" to occur after now
480 * @return int A token to that can be used with getLastError()
481 * @since 1.38
483 public function watchErrors() {
484 return self::$nextErrorMonitorId++;
488 * Get the "last error" registry
490 * The method should be invoked by a caller as part of the following pattern:
491 * - The caller invokes watchErrors() to get a "since token"
492 * - The caller invokes a sequence of cache operation methods
493 * - The caller invokes getLastError() with the "since token"
495 * External callers can also invoke this method as part of the following pattern:
496 * - The caller invokes clearLastError()
497 * - The caller invokes a sequence of cache operation methods
498 * - The caller invokes getLastError()
500 * @param int $watchPoint Only consider errors from after this "watch point" [optional]
502 * @return int BagOStuff:ERR_* constant for the "last error" registry
503 * @note Parameters added in 1.38: $watchPoint
504 * @since 1.23
506 public function getLastError( $watchPoint = 0 ) {
507 return ( $this->lastErrorId > $watchPoint ) ? $this->lastError : self::ERR_NONE;
511 * Clear the "last error" registry
513 * @since 1.23
514 * @deprecated Since 1.38, hard deprecated in 1.43
516 public function clearLastError() {
517 wfDeprecated( __METHOD__, '1.38' );
518 $this->lastError = self::ERR_NONE;
522 * Set the "last error" registry due to a problem encountered during an attempted operation
524 * @param int $error BagOStuff:ERR_* constant
526 * @since 1.23
528 protected function setLastError( $error ) {
529 $this->lastError = $error;
530 $this->lastErrorId = self::$nextErrorMonitorId++;
534 * Make a cache key from the given components, in the "global" keyspace
536 * Global keys are shared with and visible to all sites hosted in the same
537 * infrastructure (e.g. cross-wiki within the same wiki farm). Others sites
538 * may read the stored value from their requests, and they must be able to
539 * correctly compute new values from their own request context.
541 * @see BagOStuff::makeKeyInternal
542 * @since 1.27
544 * @param string $keygroup Key group component, should be under 48 characters.
545 * @param string|int ...$components Additional, ordered, key components for entity IDs
547 * @return string Colon-separated, keyspace-prepended, ordered list of encoded components
549 public function makeGlobalKey( $keygroup, ...$components ) {
550 return $this->makeKeyInternal( self::GLOBAL_KEYSPACE, func_get_args() );
554 * Make a cache key from the given components, in the default keyspace
556 * The default keyspace is unique to a given site. Subsequent web requests
557 * to the same site (e.g. local wiki, or same domain name) will interact
558 * with the same keyspace.
560 * Requests to other sites hosted on the same infrastructure (e.g. cross-wiki
561 * or cross-domain), have their own keyspace that naturally avoids conflicts.
563 * As caller you are responsible for:
564 * - Limit the key group (first component) to 48 characters
566 * Internally, the colon is used as delimiter (":"), and this is
567 * automatically escaped in supplied components to avoid ambiguity or
568 * key conflicts. BagOStuff subclasses are responsible for applying any
569 * additional escaping or limits as-needed before sending commands over
570 * the network.
572 * @see BagOStuff::makeKeyInternal
573 * @since 1.27
575 * @param string $keygroup Key group component, should be under 48 characters.
576 * @param string|int ...$components Additional, ordered, key components for entity IDs
578 * @return string Colon-separated, keyspace-prepended, ordered list of encoded components
580 public function makeKey( $keygroup, ...$components ) {
581 return $this->makeKeyInternal( $this->keyspace, func_get_args() );
585 * Check whether a cache key is in the global keyspace
587 * @param string $key
589 * @return bool
590 * @since 1.35
592 public function isKeyGlobal( $key ) {
593 return str_starts_with( $key, self::GLOBAL_PREFIX );
597 * @param int $flag BagOStuff::ATTR_* constant
599 * @return int BagOStuff:QOS_* constant
600 * @since 1.28
602 public function getQoS( $flag ) {
603 return $this->attrMap[$flag] ?? self::QOS_UNKNOWN;
607 * @deprecated since 1.43, not used anywhere.
608 * @return int|float The chunk size, in bytes, of segmented objects (INF for no limit)
609 * @since 1.34
611 public function getSegmentationSize() {
612 wfDeprecated( __METHOD__, '1.43' );
614 return INF;
618 * @deprecated since 1.43, not used anywhere.
619 * @return int|float Maximum total segmented object size in bytes (INF for no limit)
620 * @since 1.34
622 public function getSegmentedValueMaxSize() {
623 wfDeprecated( __METHOD__, '1.43' );
625 return INF;
629 * @param int $field
630 * @param int $flags
632 * @return bool
633 * @since 1.34
635 final protected function fieldHasFlags( $field, $flags ) {
636 return ( ( $field & $flags ) === $flags );
640 * Merge the flag maps of one or more BagOStuff objects into a "lowest common denominator" map
642 * @param BagOStuff[] $bags
644 * @return int[] Resulting flag map (class ATTR_* constant => class QOS_* constant)
646 final protected function mergeFlagMaps( array $bags ) {
647 $map = [];
648 foreach ( $bags as $bag ) {
649 foreach ( $bag->attrMap as $attr => $rank ) {
650 if ( isset( $map[$attr] ) ) {
651 $map[$attr] = min( $map[$attr], $rank );
652 } else {
653 $map[$attr] = $rank;
658 return $map;
662 * Make a cache key for the given keyspace and components
664 * Subclasses may override this method in order to apply different escaping,
665 * or to deal with size constraints (such as MemcachedBagOStuff). For example
666 * by converting long components into hashes.
668 * If you override this method, you MUST override ::requireConvertGenericKey()
669 * to return true. This ensures that wrapping classes (e.g. MultiWriteBagOStuff)
670 * know to re-encode keys before calling read/write methods. See also ::proxyCall().
672 * @see BagOStuff::proxyCall
673 * @since 1.27
675 * @param string $keyspace
676 * @param string[]|int[] $components Key group and other components
678 * @return string
680 protected function makeKeyInternal( $keyspace, $components ) {
681 if ( count( $components ) < 1 ) {
682 throw new InvalidArgumentException( "Missing key group" );
685 $key = $keyspace;
686 foreach ( $components as $component ) {
687 // Escape delimiter (":") and escape ("%") characters
688 $key .= ':' . strtr( $component, [ '%' => '%25', ':' => '%3A' ] );
691 return $key;
695 * Whether ::proxyCall() must re-encode cache keys before calling read/write methods.
697 * @stable to override
698 * @see BagOStuff::makeKeyInternal
699 * @see BagOStuff::proxyCall
700 * @since 1.41
701 * @return bool
703 protected function requireConvertGenericKey(): bool {
704 return false;
708 * Convert a key from BagOStuff::makeKeyInternal into one for the current subclass
710 * @see BagOStuff::proxyCall
712 * @param string $key Result from BagOStuff::makeKeyInternal
714 * @return string Result from current subclass override of BagOStuff::makeKeyInternal
716 private function convertGenericKey( $key ) {
717 if ( !$this->requireConvertGenericKey() ) {
718 // If subclass doesn't overwrite makeKeyInternal, no re-encoding is needed.
719 return $key;
722 // Extract the components from a "generic" key formatted by BagOStuff::makeKeyInternal()
723 // Note that the order of each corresponding search/replace pair matters!
724 $components = str_replace( [ '%3A', '%25' ], [ ':', '%' ], explode( ':', $key ) );
725 if ( count( $components ) < 2 ) {
726 // Legacy key, not even formatted by makeKey()/makeGlobalKey(). Keep as-is.
727 return $key;
730 $keyspace = array_shift( $components );
732 return $this->makeKeyInternal( $keyspace, $components );
736 * Call a method on behalf of wrapper BagOStuff instance
738 * The "wrapper" BagOStuff subclass that calls proxyCall() MUST NOT override
739 * the default makeKeyInternal() implementation, because proxyCall() needs
740 * to turn the "generic" key back into an array, and re-format it according
741 * to the backend-specific BagOStuff::makeKey implementation.
743 * For example, when using MultiWriteBagOStuff with Memcached as a backend,
744 * writes will go via MemcachedBagOStuff::proxyCall(), which then reformats
745 * the "generic" result of BagOStuff::makeKey (called as MultiWriteBagOStuff::makeKey)
746 * using MemcachedBagOStuff::makeKeyInternal.
748 * @param string $method Name of a non-final public method that reads/changes keys
749 * @param int $arg0Sig BagOStuff::ARG0_* constant describing argument 0
750 * @param int $resSig BagOStuff::RES_* constant describing the return value
751 * @param array $genericArgs Method arguments passed to the wrapper instance
752 * @param BagOStuff $wrapper The wrapper BagOStuff instance using this result
754 * @return mixed Method result with any keys remapped to "generic" keys
756 protected function proxyCall(
757 string $method,
758 int $arg0Sig,
759 int $resSig,
760 array $genericArgs,
761 BagOStuff $wrapper
763 // Get the corresponding store-specific cache keys...
764 $storeArgs = $genericArgs;
765 switch ( $arg0Sig ) {
766 case self::ARG0_KEY:
767 $storeArgs[0] = $this->convertGenericKey( $genericArgs[0] );
768 break;
769 case self::ARG0_KEYARR:
770 foreach ( $genericArgs[0] as $i => $genericKey ) {
771 $storeArgs[0][$i] = $this->convertGenericKey( $genericKey );
773 break;
774 case self::ARG0_KEYMAP:
775 $storeArgs[0] = [];
776 foreach ( $genericArgs[0] as $genericKey => $v ) {
777 $storeArgs[0][$this->convertGenericKey( $genericKey )] = $v;
779 break;
782 // Result of invoking the method with the corresponding store-specific cache keys
783 $watchPoint = $this->watchErrors();
784 $storeRes = $this->$method( ...$storeArgs );
785 $lastError = $this->getLastError( $watchPoint );
786 if ( $lastError !== self::ERR_NONE ) {
787 $wrapper->setLastError( $lastError );
790 // Convert any store-specific cache keys in the result back to generic cache keys
791 if ( $resSig === self::RES_KEYMAP ) {
792 // Map of (store-specific cache key => generic cache key)
793 $genericKeyByStoreKey = array_combine( $storeArgs[0], $genericArgs[0] );
795 $genericRes = [];
796 foreach ( $storeRes as $storeKey => $value ) {
797 $genericRes[$genericKeyByStoreKey[$storeKey]] = $value;
799 } else {
800 $genericRes = $storeRes;
803 return $genericRes;
807 * @internal For testing only
808 * @return float UNIX timestamp
809 * @codeCoverageIgnore
811 public function getCurrentTime() {
812 return $this->wallClockOverride ?: microtime( true );
816 * @internal For testing only
818 * @param float|null &$time Mock UNIX timestamp
820 * @codeCoverageIgnore
822 public function setMockTime( &$time ) {
823 $this->wallClockOverride =& $time;
827 /** @deprecated class alias since 1.43 */
828 class_alias( BagOStuff::class, 'BagOStuff' );