Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
16.28% |
14 / 86 |
|
19.05% |
4 / 21 |
CRAP | |
0.00% |
0 / 1 |
| BagOStuff | |
16.47% |
14 / 85 |
|
19.05% |
4 / 21 |
1448.30 | |
0.00% |
0 / 1 |
| __construct | |
83.33% |
5 / 6 |
|
0.00% |
0 / 1 |
2.02 | |||
| setLogger | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| getLogger | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| getWithSetCallback | |
0.00% |
0 / 6 |
|
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% |
0 / 6 |
|
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% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| getLastError | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
6 | |||
| setLastError | |
0.00% |
0 / 2 |
|
0.00% |
0 / 1 |
2 | |||
| makeGlobalKey | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| makeKey | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| isKeyGlobal | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| getQoS | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| getSegmentationSize | |
0.00% |
0 / 2 |
|
0.00% |
0 / 1 |
2 | |||
| getSegmentedValueMaxSize | |
0.00% |
0 / 2 |
|
0.00% |
0 / 1 |
2 | |||
| fieldHasFlags | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| mergeFlagMaps | |
0.00% |
0 / 7 |
|
0.00% |
0 / 1 |
20 | |||
| makeKeyInternal | |
83.33% |
5 / 6 |
|
0.00% |
0 / 1 |
3.04 | |||
| makeFallbackKey | |
0.00% |
0 / 9 |
|
0.00% |
0 / 1 |
20 | |||
| requireConvertGenericKey | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| convertGenericKey | |
0.00% |
0 / 7 |
|
0.00% |
0 / 1 |
12 | |||
| proxyCall | |
0.00% |
0 / 22 |
|
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 | |
| 17 | namespace Wikimedia\ObjectCache; |
| 18 | |
| 19 | use InvalidArgumentException; |
| 20 | use Psr\Log\LoggerAwareInterface; |
| 21 | use Psr\Log\LoggerInterface; |
| 22 | use Psr\Log\NullLogger; |
| 23 | use Wikimedia\LightweightObjectStore\ExpirationAwareness; |
| 24 | use Wikimedia\ScopedCallback; |
| 25 | use 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 | */ |
| 69 | abstract 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 | * succesful 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 | * - asyncHandler: Callable to use for scheduling tasks after the web request ends. |
| 196 | * In CLI mode, it should run the task immediately. [Default: null] |
| 197 | * - stats: IStatsdDataFactory instance. [optional] |
| 198 | * - logger: \Psr\Log\LoggerInterface instance. [optional] |
| 199 | * |
| 200 | * @phan-param array{keyspace?:string,logger?:\Psr\Log\LoggerInterface,asyncHandler?:callable} $params |
| 201 | */ |
| 202 | public function __construct( array $params = [] ) { |
| 203 | $this->keyspace = $params['keyspace'] ?? 'local'; |
| 204 | $this->stats = $params['stats'] ?? StatsFactory::newNull(); |
| 205 | $this->setLogger( $params['logger'] ?? new NullLogger() ); |
| 206 | |
| 207 | $asyncHandler = $params['asyncHandler'] ?? null; |
| 208 | if ( is_callable( $asyncHandler ) ) { |
| 209 | $this->asyncHandler = $asyncHandler; |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | /** |
| 214 | * @param LoggerInterface $logger |
| 215 | * |
| 216 | * @return void |
| 217 | */ |
| 218 | public function setLogger( LoggerInterface $logger ): void { |
| 219 | $this->logger = $logger; |
| 220 | } |
| 221 | |
| 222 | /** |
| 223 | * @since 1.35 |
| 224 | * @return LoggerInterface |
| 225 | */ |
| 226 | public function getLogger(): LoggerInterface { |
| 227 | return $this->logger; |
| 228 | } |
| 229 | |
| 230 | /** |
| 231 | * Get an item, regenerating and setting it if not found |
| 232 | * |
| 233 | * The callback can take $exptime as argument by reference and modify it. |
| 234 | * Nothing is stored nor deleted if the callback returns false. |
| 235 | * |
| 236 | * @param string $key |
| 237 | * @param int $exptime Time-to-live (seconds) |
| 238 | * @param callable $callback Callback that derives the new value |
| 239 | * @param int $flags Bitfield of BagOStuff::READ_* or BagOStuff::WRITE_* constants [optional] |
| 240 | * |
| 241 | * @return mixed The cached value if found or the result of $callback otherwise |
| 242 | * @since 1.27 |
| 243 | */ |
| 244 | final public function getWithSetCallback( $key, $exptime, $callback, $flags = 0 ) { |
| 245 | $value = $this->get( $key, $flags ); |
| 246 | |
| 247 | if ( $value === false ) { |
| 248 | $value = $callback( $exptime ); |
| 249 | if ( $value !== false && $exptime >= 0 ) { |
| 250 | $this->set( $key, $value, $exptime, $flags ); |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | return $value; |
| 255 | } |
| 256 | |
| 257 | /** |
| 258 | * Get an item |
| 259 | * |
| 260 | * If the key includes a deterministic input hash (e.g. the key can only have |
| 261 | * the correct value) or complete staleness checks are handled by the caller |
| 262 | * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set. |
| 263 | * This lets tiered backends know they can safely upgrade a cached value to |
| 264 | * higher tiers using standard TTLs. |
| 265 | * |
| 266 | * @param string $key |
| 267 | * @param int $flags Bitfield of BagOStuff::READ_* constants [optional] |
| 268 | * |
| 269 | * @return mixed Returns false on failure or if the item does not exist |
| 270 | */ |
| 271 | abstract public function get( $key, $flags = 0 ); |
| 272 | |
| 273 | /** |
| 274 | * Set an item |
| 275 | * |
| 276 | * @param string $key |
| 277 | * @param mixed $value |
| 278 | * @param int $exptime Either an interval in seconds or a unix timestamp for expiry |
| 279 | * @param int $flags Bitfield of BagOStuff::WRITE_* constants |
| 280 | * If setting WRITE_ALLOW_SEGMENTS, remember to also set it in any delete() calls. |
| 281 | * @return bool Success |
| 282 | */ |
| 283 | abstract public function set( $key, $value, $exptime = 0, $flags = 0 ); |
| 284 | |
| 285 | /** |
| 286 | * Delete an item if it exists |
| 287 | * |
| 288 | * For large values set with WRITE_ALLOW_SEGMENTS, this only deletes the placeholder |
| 289 | * key with the segment list. To delete the underlying blobs, include WRITE_ALLOW_SEGMENTS |
| 290 | * in the flags for delete() as well. While deleting the segment list key has the effect of |
| 291 | * functionally deleting the key, it leaves unused blobs in storage. |
| 292 | * |
| 293 | * The reason that this is not done automatically, is that to delete underlying blobs, |
| 294 | * requires first fetching the current segment list. Given that 99% of keys don't use |
| 295 | * WRITE_ALLOW_SEGMENTS, this would be wasteful. |
| 296 | * |
| 297 | * @param string $key |
| 298 | * @param int $flags Bitfield of BagOStuff::WRITE_* constants |
| 299 | * @return bool Success (item deleted or not found) |
| 300 | */ |
| 301 | abstract public function delete( $key, $flags = 0 ); |
| 302 | |
| 303 | /** |
| 304 | * Insert an item if it does not already exist |
| 305 | * |
| 306 | * @param string $key |
| 307 | * @param mixed $value |
| 308 | * @param int $exptime |
| 309 | * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33) |
| 310 | * |
| 311 | * @return bool Success (item created) |
| 312 | */ |
| 313 | abstract public function add( $key, $value, $exptime = 0, $flags = 0 ); |
| 314 | |
| 315 | /** |
| 316 | * Merge changes into the existing cache value (possibly creating a new one) |
| 317 | * |
| 318 | * The callback function returns the new value given the current value |
| 319 | * (which will be false if not present), and takes the arguments: |
| 320 | * (this BagOStuff, cache key, current value, TTL). |
| 321 | * The TTL parameter is reference set to $exptime. It can be overridden in the callback. |
| 322 | * Nothing is stored nor deleted if the callback returns false. |
| 323 | * |
| 324 | * @param string $key |
| 325 | * @param callable $callback Callback method to be executed |
| 326 | * @param int $exptime Either an interval in seconds or a unix timestamp for expiry |
| 327 | * @param int $attempts The amount of times to attempt a merge in case of failure |
| 328 | * @param int $flags Bitfield of BagOStuff::WRITE_* constants |
| 329 | * |
| 330 | * @return bool Success |
| 331 | */ |
| 332 | abstract public function merge( |
| 333 | $key, |
| 334 | callable $callback, |
| 335 | $exptime = 0, |
| 336 | $attempts = 10, |
| 337 | $flags = 0 |
| 338 | ); |
| 339 | |
| 340 | /** |
| 341 | * Change the expiration on an item |
| 342 | * |
| 343 | * If an expiry in the past is given then the key will immediately be expired |
| 344 | * |
| 345 | * For large values written using WRITE_ALLOW_SEGMENTS, this only changes the TTL of the |
| 346 | * main segment list key. While lowering the TTL of the segment list key has the effect of |
| 347 | * functionally lowering the TTL of the key, it might leave unused blobs in cache for longer. |
| 348 | * Raising the TTL of such keys is not effective, since the expiration of a single segment |
| 349 | * key effectively expires the entire value. |
| 350 | * |
| 351 | * @param string $key |
| 352 | * @param int $exptime TTL or UNIX timestamp |
| 353 | * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33) |
| 354 | * |
| 355 | * @return bool Success (item found and updated) |
| 356 | * @since 1.28 |
| 357 | */ |
| 358 | abstract public function changeTTL( $key, $exptime = 0, $flags = 0 ); |
| 359 | |
| 360 | /** |
| 361 | * Acquire an advisory lock on a key string, exclusive to the caller |
| 362 | * |
| 363 | * @param string $key |
| 364 | * @param int $timeout Lock wait timeout; 0 for non-blocking [optional] |
| 365 | * @param int $exptime Lock time-to-live in seconds; 1 day maximum [optional] |
| 366 | * @param string $rclass If this thread already holds the lock, and the lock was acquired |
| 367 | * using the same value for this parameter, then return true and use reference counting so |
| 368 | * that only the unlock() call from the outermost lock() caller actually releases the lock |
| 369 | * (note that only the outermost time-to-live is used) [optional] |
| 370 | * |
| 371 | * @return bool Success |
| 372 | */ |
| 373 | abstract public function lock( $key, $timeout = 6, $exptime = 6, $rclass = '' ); |
| 374 | |
| 375 | /** |
| 376 | * Release an advisory lock on a key string |
| 377 | * |
| 378 | * @param string $key |
| 379 | * |
| 380 | * @return bool Success |
| 381 | */ |
| 382 | abstract public function unlock( $key ); |
| 383 | |
| 384 | /** |
| 385 | * Get a lightweight exclusive self-unlocking lock |
| 386 | * |
| 387 | * Note that the same lock cannot be acquired twice. |
| 388 | * |
| 389 | * This is useful for task de-duplication or to avoid obtrusive |
| 390 | * (though non-corrupting) DB errors like INSERT key conflicts |
| 391 | * or deadlocks when using LOCK IN SHARE MODE. |
| 392 | * |
| 393 | * @param string $key |
| 394 | * @param int $timeout Lock wait timeout; 0 for non-blocking [optional] |
| 395 | * @param int $exptime Lock time-to-live [optional]; 1 day maximum |
| 396 | * @param string $rclass Allow reentry if set and the current lock used this value |
| 397 | * |
| 398 | * @return ScopedCallback|null Returns null on failure |
| 399 | * @since 1.26 |
| 400 | */ |
| 401 | final public function getScopedLock( $key, $timeout = 6, $exptime = 30, $rclass = '' ) { |
| 402 | $exptime = min( $exptime ?: INF, self::TTL_DAY ); |
| 403 | |
| 404 | if ( !$this->lock( $key, $timeout, $exptime, $rclass ) ) { |
| 405 | return null; |
| 406 | } |
| 407 | |
| 408 | return new ScopedCallback( function () use ( $key ) { |
| 409 | $this->unlock( $key ); |
| 410 | } ); |
| 411 | } |
| 412 | |
| 413 | /** |
| 414 | * Delete all objects expiring before a certain date |
| 415 | * |
| 416 | * @param string|int $timestamp The reference date in MW or TS::UNIX format |
| 417 | * @param callable|null $progress Optional, a function which will be called |
| 418 | * regularly during long-running operations with the percentage progress |
| 419 | * as the first parameter. [optional] |
| 420 | * @param int|float $limit Maximum number of keys to delete [default: INF] |
| 421 | * @param string|null $tag Tag to purge a single shard only. |
| 422 | * This is only supported when server tags are used in configuration. |
| 423 | * |
| 424 | * @return bool Success; false if unimplemented |
| 425 | */ |
| 426 | abstract public function deleteObjectsExpiringBefore( |
| 427 | $timestamp, |
| 428 | ?callable $progress = null, |
| 429 | $limit = INF, |
| 430 | ?string $tag = null |
| 431 | ); |
| 432 | |
| 433 | /** |
| 434 | * Get a batch of items |
| 435 | * |
| 436 | * @param string[] $keys List of keys |
| 437 | * @param int $flags Bitfield; supports READ_LATEST [optional] |
| 438 | * |
| 439 | * @return mixed[] Map of (key => value) for existing keys |
| 440 | */ |
| 441 | abstract public function getMulti( array $keys, $flags = 0 ); |
| 442 | |
| 443 | /** |
| 444 | * Set a batch of items |
| 445 | * |
| 446 | * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O |
| 447 | * |
| 448 | * WRITE_BACKGROUND can be used for bulk insertion where the response is not vital |
| 449 | * |
| 450 | * @param mixed[] $valueByKey Map of (key => value) |
| 451 | * @param int $exptime Either an interval in seconds or a unix timestamp for expiry |
| 452 | * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33) |
| 453 | * |
| 454 | * @return bool Success |
| 455 | * @since 1.24 |
| 456 | */ |
| 457 | abstract public function setMulti( array $valueByKey, $exptime = 0, $flags = 0 ); |
| 458 | |
| 459 | /** |
| 460 | * Delete a batch of items |
| 461 | * |
| 462 | * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O |
| 463 | * |
| 464 | * WRITE_BACKGROUND can be used for bulk deletion where the response is not vital |
| 465 | * |
| 466 | * @param string[] $keys List of keys |
| 467 | * @param int $flags Bitfield of BagOStuff::WRITE_* constants |
| 468 | * @return bool Success (items deleted and/or not found) |
| 469 | * @since 1.33 |
| 470 | */ |
| 471 | abstract public function deleteMulti( array $keys, $flags = 0 ); |
| 472 | |
| 473 | /** |
| 474 | * Change the expiration of multiple items |
| 475 | * |
| 476 | * @see BagOStuff::changeTTL() |
| 477 | * |
| 478 | * @param string[] $keys List of keys |
| 479 | * @param int $exptime TTL or UNIX timestamp |
| 480 | * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33) |
| 481 | * |
| 482 | * @return bool Success (all items found and updated) |
| 483 | * @since 1.34 |
| 484 | */ |
| 485 | abstract public function changeTTLMulti( array $keys, $exptime, $flags = 0 ); |
| 486 | |
| 487 | /** |
| 488 | * Increase the value of the given key (no TTL change) if it exists or create it otherwise |
| 489 | * |
| 490 | * This will create the key with the value $init and TTL $exptime instead if not present. |
| 491 | * Callers should make sure that both ($init - $step) and $exptime are invariants for all |
| 492 | * operations to any given key. The value of $init should be at least that of $step. |
| 493 | * |
| 494 | * The new value is returned, except if the WRITE_BACKGROUND flag is given, in which case |
| 495 | * the handler may choose to return true to indicate that the operation has been dispatched. |
| 496 | * |
| 497 | * @param string $key Key built via makeKey() or makeGlobalKey() |
| 498 | * @param int $exptime Time-to-live (in seconds) or a UNIX timestamp expiration |
| 499 | * @param int $step Amount to increase the key value by [default: 1] |
| 500 | * @param int|null $init Value to initialize the key to if it does not exist [default: $step] |
| 501 | * @param int $flags Bit field of class WRITE_* constants [optional] |
| 502 | * |
| 503 | * @return int|bool New value (or true if asynchronous) on success; false on failure |
| 504 | * @since 1.24 |
| 505 | */ |
| 506 | abstract public function incrWithInit( $key, $exptime, $step = 1, $init = null, $flags = 0 ); |
| 507 | |
| 508 | /** |
| 509 | * Get a "watch point" token that can be used to get the "last error" to occur after now |
| 510 | * |
| 511 | * @return int A token to that can be used with getLastError() |
| 512 | * @since 1.38 |
| 513 | */ |
| 514 | public function watchErrors() { |
| 515 | return self::$nextErrorMonitorId++; |
| 516 | } |
| 517 | |
| 518 | /** |
| 519 | * Get the "last error" registry |
| 520 | * |
| 521 | * The method should be invoked by a caller as part of the following pattern: |
| 522 | * - The caller invokes watchErrors() to get a "since token" |
| 523 | * - The caller invokes a sequence of cache operation methods |
| 524 | * - The caller invokes getLastError() with the "since token" |
| 525 | * |
| 526 | * External callers can also invoke this method as part of the following pattern: |
| 527 | * - The caller invokes clearLastError() |
| 528 | * - The caller invokes a sequence of cache operation methods |
| 529 | * - The caller invokes getLastError() |
| 530 | * |
| 531 | * @param int $watchPoint Only consider errors from after this "watch point" [optional] |
| 532 | * |
| 533 | * @return int BagOStuff:ERR_* constant for the "last error" registry |
| 534 | * @note Parameters added in 1.38: $watchPoint |
| 535 | * @since 1.23 |
| 536 | */ |
| 537 | public function getLastError( $watchPoint = 0 ) { |
| 538 | return ( $this->lastErrorId > $watchPoint ) ? $this->lastError : self::ERR_NONE; |
| 539 | } |
| 540 | |
| 541 | /** |
| 542 | * Set the "last error" registry due to a problem encountered during an attempted operation |
| 543 | * |
| 544 | * @param int $error BagOStuff:ERR_* constant |
| 545 | * |
| 546 | * @since 1.23 |
| 547 | */ |
| 548 | protected function setLastError( $error ) { |
| 549 | $this->lastError = $error; |
| 550 | $this->lastErrorId = self::$nextErrorMonitorId++; |
| 551 | } |
| 552 | |
| 553 | /** |
| 554 | * Make a cache key from the given components, in the "global" keyspace |
| 555 | * |
| 556 | * Global keys are shared with and visible to all sites hosted in the same |
| 557 | * infrastructure (e.g. cross-wiki within the same wiki farm). Others sites |
| 558 | * may read the stored value from their requests, and they must be able to |
| 559 | * correctly compute new values from their own request context. |
| 560 | * |
| 561 | * @see BagOStuff::makeKeyInternal |
| 562 | * @since 1.27 |
| 563 | * @param string $keygroup Key group component, should be under 48 characters. |
| 564 | * @param string|int ...$components Additional, ordered, key components for entity IDs |
| 565 | * @return string Colon-separated, keyspace-prepended, ordered list of encoded components |
| 566 | */ |
| 567 | public function makeGlobalKey( $keygroup, ...$components ) { |
| 568 | return $this->makeKeyInternal( self::GLOBAL_KEYSPACE, func_get_args() ); |
| 569 | } |
| 570 | |
| 571 | /** |
| 572 | * Make a cache key from the given components, in the default keyspace |
| 573 | * |
| 574 | * The default keyspace is unique to a given site. Subsequent web requests |
| 575 | * to the same site (e.g. local wiki, or same domain name) will interact |
| 576 | * with the same keyspace. |
| 577 | * |
| 578 | * Requests to other sites hosted on the same infrastructure (e.g. cross-wiki |
| 579 | * or cross-domain), have their own keyspace that naturally avoids conflicts. |
| 580 | * |
| 581 | * As caller you are responsible for: |
| 582 | * - Limit the key group (first component) to 48 characters |
| 583 | * |
| 584 | * Internally, the colon is used as delimiter (":"), and this is |
| 585 | * automatically escaped in supplied components to avoid ambiguity or |
| 586 | * key conflicts. BagOStuff subclasses are responsible for applying any |
| 587 | * additional escaping or limits as-needed before sending commands over |
| 588 | * the network. |
| 589 | * |
| 590 | * @see BagOStuff::makeKeyInternal |
| 591 | * @since 1.27 |
| 592 | * @param string $keygroup Key group component, should be under 48 characters. |
| 593 | * @param string|int ...$components Additional, ordered, key components for entity IDs |
| 594 | * @return string Colon-separated, keyspace-prepended, ordered list of encoded components |
| 595 | */ |
| 596 | public function makeKey( $keygroup, ...$components ) { |
| 597 | return $this->makeKeyInternal( $this->keyspace, func_get_args() ); |
| 598 | } |
| 599 | |
| 600 | /** |
| 601 | * Check whether a cache key is in the global keyspace |
| 602 | * |
| 603 | * @param string $key |
| 604 | * @return bool |
| 605 | * @since 1.35 |
| 606 | */ |
| 607 | public function isKeyGlobal( $key ) { |
| 608 | return str_starts_with( $key, self::GLOBAL_PREFIX ); |
| 609 | } |
| 610 | |
| 611 | /** |
| 612 | * @param int $flag BagOStuff::ATTR_* constant |
| 613 | * |
| 614 | * @return int BagOStuff:QOS_* constant |
| 615 | * @since 1.28 |
| 616 | */ |
| 617 | public function getQoS( $flag ) { |
| 618 | return $this->attrMap[$flag] ?? self::QOS_UNKNOWN; |
| 619 | } |
| 620 | |
| 621 | /** |
| 622 | * @deprecated since 1.43, not used anywhere. |
| 623 | * @return int|float The chunk size, in bytes, of segmented objects (INF for no limit) |
| 624 | * @since 1.34 |
| 625 | */ |
| 626 | public function getSegmentationSize() { |
| 627 | wfDeprecated( __METHOD__, '1.43' ); |
| 628 | |
| 629 | return INF; |
| 630 | } |
| 631 | |
| 632 | /** |
| 633 | * @deprecated since 1.43, not used anywhere. |
| 634 | * @return int|float Maximum total segmented object size in bytes (INF for no limit) |
| 635 | * @since 1.34 |
| 636 | */ |
| 637 | public function getSegmentedValueMaxSize() { |
| 638 | wfDeprecated( __METHOD__, '1.43' ); |
| 639 | |
| 640 | return INF; |
| 641 | } |
| 642 | |
| 643 | /** |
| 644 | * @param int $field |
| 645 | * @param int $flags |
| 646 | * |
| 647 | * @return bool |
| 648 | * @since 1.34 |
| 649 | */ |
| 650 | final protected function fieldHasFlags( $field, $flags ) { |
| 651 | return ( ( $field & $flags ) === $flags ); |
| 652 | } |
| 653 | |
| 654 | /** |
| 655 | * Merge the flag maps of one or more BagOStuff objects into a "lowest common denominator" map |
| 656 | * |
| 657 | * @param BagOStuff[] $bags |
| 658 | * |
| 659 | * @return int[] Resulting flag map (class ATTR_* constant => class QOS_* constant) |
| 660 | */ |
| 661 | final protected function mergeFlagMaps( array $bags ) { |
| 662 | $map = []; |
| 663 | foreach ( $bags as $bag ) { |
| 664 | foreach ( $bag->attrMap as $attr => $rank ) { |
| 665 | if ( isset( $map[$attr] ) ) { |
| 666 | $map[$attr] = min( $map[$attr], $rank ); |
| 667 | } else { |
| 668 | $map[$attr] = $rank; |
| 669 | } |
| 670 | } |
| 671 | } |
| 672 | |
| 673 | return $map; |
| 674 | } |
| 675 | |
| 676 | /** |
| 677 | * Make a cache key for the given keyspace and components |
| 678 | * |
| 679 | * Subclasses may override this method to apply different escaping, |
| 680 | * or to deal with size constraints (such as MemcachedBagOStuff). |
| 681 | * For example, by converting long components into hashes. |
| 682 | * |
| 683 | * If you override this method, you MUST override ::requireConvertGenericKey() |
| 684 | * to return true. This ensures that wrapping classes (e.g. MultiWriteBagOStuff) |
| 685 | * know to re-encode keys before calling read/write methods. See also ::proxyCall(). |
| 686 | * |
| 687 | * @see BagOStuff::proxyCall |
| 688 | * @since 1.27 |
| 689 | * |
| 690 | * @param string $keyspace |
| 691 | * @param string[]|int[]|null[] $components Key group and other components |
| 692 | * |
| 693 | * @return string |
| 694 | */ |
| 695 | protected function makeKeyInternal( $keyspace, $components ) { |
| 696 | if ( count( $components ) < 1 ) { |
| 697 | throw new InvalidArgumentException( "Missing key group" ); |
| 698 | } |
| 699 | |
| 700 | $key = $keyspace; |
| 701 | foreach ( $components as $component ) { |
| 702 | // Escape delimiter (":") and escape ("%") characters |
| 703 | $key .= ':' . strtr( $component ?? '', [ '%' => '%25', ':' => '%3A' ] ); |
| 704 | } |
| 705 | |
| 706 | return $key; |
| 707 | } |
| 708 | |
| 709 | /** |
| 710 | * Re-format a cache key that is too long. |
| 711 | * |
| 712 | * @since 1.45 |
| 713 | * @see BagOStuff::makeKeyInternal |
| 714 | * @param string $key |
| 715 | * @param int $maxLength |
| 716 | * @return string |
| 717 | */ |
| 718 | protected function makeFallbackKey( string $key, int $maxLength ) { |
| 719 | if ( strlen( $key ) > $maxLength ) { |
| 720 | // Components are "<0=keyspace>:<1=keygroup>:<others...>" |
| 721 | $components = str_replace( [ '%3A', '%25' ], [ ':', '%' ], explode( ':', $key ) ); |
| 722 | if ( count( $components ) < 2 ) { |
| 723 | throw new InvalidArgumentException( 'Key lacks keyspace' ); |
| 724 | } |
| 725 | |
| 726 | // Prefer to preserve the keygroup for statistics. |
| 727 | // Try "mywiki:mykeygroup:#<64-char hash>" |
| 728 | // This gives 138 chars (205-64-3) for the keyspace and keygroup. |
| 729 | $hash = hash( 'sha256', $key ); |
| 730 | $key = $components[0] . ':' . $components[1] . ':#' . $hash; |
| 731 | if ( strlen( $key ) > $maxLength ) { |
| 732 | // Try "mywiki:BagOStuff-long-key:##<64-char hash>" |
| 733 | // Might be legacy code that passes a long string as the key without a keygroup. |
| 734 | $key = $components[0] . ':BagOStuff-long-key:##' . $hash; |
| 735 | } |
| 736 | } |
| 737 | |
| 738 | return $key; |
| 739 | } |
| 740 | |
| 741 | /** |
| 742 | * Whether ::proxyCall() must re-encode cache keys before calling read/write methods. |
| 743 | * |
| 744 | * @stable to override |
| 745 | * @see BagOStuff::makeKeyInternal |
| 746 | * @see BagOStuff::proxyCall |
| 747 | * @since 1.41 |
| 748 | * @return bool |
| 749 | */ |
| 750 | protected function requireConvertGenericKey(): bool { |
| 751 | return false; |
| 752 | } |
| 753 | |
| 754 | /** |
| 755 | * Convert a key from BagOStuff::makeKeyInternal into one for the current subclass |
| 756 | * |
| 757 | * @see BagOStuff::proxyCall |
| 758 | * |
| 759 | * @param string $key Result from BagOStuff::makeKeyInternal |
| 760 | * |
| 761 | * @return string Result from current subclass override of BagOStuff::makeKeyInternal |
| 762 | */ |
| 763 | private function convertGenericKey( $key ) { |
| 764 | if ( !$this->requireConvertGenericKey() ) { |
| 765 | // If subclass doesn't overwrite makeKeyInternal, no re-encoding is needed. |
| 766 | return $key; |
| 767 | } |
| 768 | |
| 769 | // Extract the components from a "generic" key formatted by BagOStuff::makeKeyInternal() |
| 770 | // Note that the order of each corresponding search/replace pair matters! |
| 771 | $components = str_replace( [ '%3A', '%25' ], [ ':', '%' ], explode( ':', $key ) ); |
| 772 | if ( count( $components ) < 2 ) { |
| 773 | // Legacy key, not even formatted by makeKey()/makeGlobalKey(). Keep as-is. |
| 774 | return $key; |
| 775 | } |
| 776 | |
| 777 | $keyspace = array_shift( $components ); |
| 778 | |
| 779 | return $this->makeKeyInternal( $keyspace, $components ); |
| 780 | } |
| 781 | |
| 782 | /** |
| 783 | * Call a method on behalf of wrapper BagOStuff instance |
| 784 | * |
| 785 | * The "wrapper" BagOStuff subclass that calls proxyCall() MUST NOT override |
| 786 | * the default makeKeyInternal() implementation, because proxyCall() needs |
| 787 | * to turn the "generic" key back into an array, and re-format it according |
| 788 | * to the backend-specific BagOStuff::makeKey implementation. |
| 789 | * |
| 790 | * For example, when using MultiWriteBagOStuff with Memcached as a backend, |
| 791 | * writes will go via MemcachedBagOStuff::proxyCall(), which then reformats |
| 792 | * the "generic" result of BagOStuff::makeKey (called as MultiWriteBagOStuff::makeKey) |
| 793 | * using MemcachedBagOStuff::makeKeyInternal. |
| 794 | * |
| 795 | * @param string $method Name of a non-final public method that reads/changes keys |
| 796 | * @param int $arg0Sig BagOStuff::ARG0_* constant describing argument 0 |
| 797 | * @param int $resSig BagOStuff::RES_* constant describing the return value |
| 798 | * @param array $genericArgs Method arguments passed to the wrapper instance |
| 799 | * @param BagOStuff $wrapper The wrapper BagOStuff instance using this result |
| 800 | * |
| 801 | * @return mixed Method result with any keys remapped to "generic" keys |
| 802 | */ |
| 803 | protected function proxyCall( |
| 804 | string $method, |
| 805 | int $arg0Sig, |
| 806 | int $resSig, |
| 807 | array $genericArgs, |
| 808 | BagOStuff $wrapper |
| 809 | ) { |
| 810 | // Get the corresponding store-specific cache keys... |
| 811 | $storeArgs = $genericArgs; |
| 812 | switch ( $arg0Sig ) { |
| 813 | case self::ARG0_KEY: |
| 814 | $storeArgs[0] = $this->convertGenericKey( $genericArgs[0] ); |
| 815 | break; |
| 816 | case self::ARG0_KEYARR: |
| 817 | foreach ( $genericArgs[0] as $i => $genericKey ) { |
| 818 | $storeArgs[0][$i] = $this->convertGenericKey( $genericKey ); |
| 819 | } |
| 820 | break; |
| 821 | case self::ARG0_KEYMAP: |
| 822 | $storeArgs[0] = []; |
| 823 | foreach ( $genericArgs[0] as $genericKey => $v ) { |
| 824 | $storeArgs[0][$this->convertGenericKey( $genericKey )] = $v; |
| 825 | } |
| 826 | break; |
| 827 | } |
| 828 | |
| 829 | // Result of invoking the method with the corresponding store-specific cache keys |
| 830 | $watchPoint = $this->watchErrors(); |
| 831 | $storeRes = $this->$method( ...$storeArgs ); |
| 832 | $lastError = $this->getLastError( $watchPoint ); |
| 833 | if ( $lastError !== self::ERR_NONE ) { |
| 834 | $wrapper->setLastError( $lastError ); |
| 835 | } |
| 836 | |
| 837 | // Convert any store-specific cache keys in the result back to generic cache keys |
| 838 | if ( $resSig === self::RES_KEYMAP ) { |
| 839 | // Map of (store-specific cache key => generic cache key) |
| 840 | $genericKeyByStoreKey = array_combine( $storeArgs[0], $genericArgs[0] ); |
| 841 | |
| 842 | $genericRes = []; |
| 843 | foreach ( $storeRes as $storeKey => $value ) { |
| 844 | $genericRes[$genericKeyByStoreKey[$storeKey]] = $value; |
| 845 | } |
| 846 | } else { |
| 847 | $genericRes = $storeRes; |
| 848 | } |
| 849 | |
| 850 | return $genericRes; |
| 851 | } |
| 852 | |
| 853 | /** |
| 854 | * @internal For testing only |
| 855 | * @return float UNIX timestamp |
| 856 | * @codeCoverageIgnore |
| 857 | */ |
| 858 | public function getCurrentTime() { |
| 859 | return $this->wallClockOverride ?: microtime( true ); |
| 860 | } |
| 861 | |
| 862 | /** |
| 863 | * @internal For testing only |
| 864 | * |
| 865 | * @param float|null &$time Mock UNIX timestamp |
| 866 | * |
| 867 | * @codeCoverageIgnore |
| 868 | */ |
| 869 | public function setMockTime( &$time ) { |
| 870 | $this->wallClockOverride =& $time; |
| 871 | } |
| 872 | } |
| 873 | |
| 874 | /** @deprecated class alias since 1.43 */ |
| 875 | class_alias( BagOStuff::class, 'BagOStuff' ); |