Merge "maintenance: Script to rename titles for Unicode uppercasing changes"
[lhc/web/wiklou.git] / includes / libs / objectcache / BagOStuff.php
1 <?php
2 /**
3 * Copyright © 2003-2004 Brion Vibber <brion@pobox.com>
4 * https://www.mediawiki.org/
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @file
22 * @ingroup Cache
23 */
24
25 /**
26 * @defgroup Cache Cache
27 */
28
29 use Psr\Log\LoggerAwareInterface;
30 use Psr\Log\LoggerInterface;
31 use Psr\Log\NullLogger;
32 use Wikimedia\ScopedCallback;
33 use Wikimedia\WaitConditionLoop;
34
35 /**
36 * Class representing a cache/ephemeral data store
37 *
38 * This interface is intended to be more or less compatible with the PHP memcached client.
39 *
40 * Instances of this class should be created with an intended access scope, such as:
41 * - a) A single PHP thread on a server (e.g. stored in a PHP variable)
42 * - b) A single application server (e.g. stored in APC or sqlite)
43 * - c) All application servers in datacenter (e.g. stored in memcached or mysql)
44 * - d) All application servers in all datacenters (e.g. stored via mcrouter or dynomite)
45 *
46 * Callers should use the proper factory methods that yield BagOStuff instances. Site admins
47 * should make sure the configuration for those factory methods matches their access scope.
48 * BagOStuff subclasses have widely varying levels of support for replication features.
49 *
50 * For any given instance, methods like lock(), unlock(), merge(), and set() with WRITE_SYNC
51 * should semantically operate over its entire access scope; any nodes/threads in that scope
52 * should serialize appropriately when using them. Likewise, a call to get() with READ_LATEST
53 * from one node in its access scope should reflect the prior changes of any other node its
54 * access scope. Any get() should reflect the changes of any prior set() with WRITE_SYNC.
55 *
56 * Subclasses should override the default "segmentationSize" field with an appropriate value.
57 * The value should not be larger than what the storage backend (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.
61 *
62 * @ingroup Cache
63 */
64 abstract class BagOStuff implements IExpiringStore, IStoreKeyEncoder, LoggerAwareInterface {
65 /** @var array[] Lock tracking */
66 protected $locks = [];
67 /** @var int ERR_* class constant */
68 protected $lastError = self::ERR_NONE;
69 /** @var string */
70 protected $keyspace = 'local';
71 /** @var LoggerInterface */
72 protected $logger;
73 /** @var callable|null */
74 protected $asyncHandler;
75 /** @var int Seconds */
76 protected $syncTimeout;
77 /** @var int Bytes; chunk size of segmented cache values */
78 protected $segmentationSize;
79 /** @var int Bytes; maximum total size of a segmented cache value */
80 protected $segmentedValueMaxSize;
81
82 /** @var bool */
83 private $debugMode = false;
84 /** @var array */
85 private $duplicateKeyLookups = [];
86 /** @var bool */
87 private $reportDupes = false;
88 /** @var bool */
89 private $dupeTrackScheduled = false;
90
91 /** @var callable[] */
92 protected $busyCallbacks = [];
93
94 /** @var float|null */
95 private $wallClockOverride;
96
97 /** @var int[] Map of (ATTR_* class constant => QOS_* class constant) */
98 protected $attrMap = [];
99
100 /** Bitfield constants for get()/getMulti() */
101 const READ_LATEST = 1; // use latest data for replicated stores
102 const READ_VERIFIED = 2; // promise that caller can tell when keys are stale
103 /** Bitfield constants for set()/merge() */
104 const WRITE_SYNC = 4; // synchronously write to all locations for replicated stores
105 const WRITE_CACHE_ONLY = 8; // Only change state of the in-memory cache
106 const WRITE_ALLOW_SEGMENTS = 16; // Allow partitioning of the value if it is large
107 const WRITE_PRUNE_SEGMENTS = 32; // Delete all partition segments of the value
108
109 /** @var string Component to use for key construction of blob segment keys */
110 const SEGMENT_COMPONENT = 'segment';
111
112 /**
113 * $params include:
114 * - logger: Psr\Log\LoggerInterface instance
115 * - keyspace: Default keyspace for $this->makeKey()
116 * - asyncHandler: Callable to use for scheduling tasks after the web request ends.
117 * In CLI mode, it should run the task immediately.
118 * - reportDupes: Whether to emit warning log messages for all keys that were
119 * requested more than once (requires an asyncHandler).
120 * - syncTimeout: How long to wait with WRITE_SYNC in seconds.
121 * - segmentationSize: The chunk size, in bytes, of segmented values. The value should
122 * not exceed the maximum size of values in the storage backend, as configured by
123 * the site administrator.
124 * - segmentedValueMaxSize: The maximum total size, in bytes, of segmented values.
125 * This should be configured to a reasonable size give the site traffic and the
126 * amount of I/O between application and cache servers that the network can handle.
127 * @param array $params
128 */
129 public function __construct( array $params = [] ) {
130 $this->setLogger( $params['logger'] ?? new NullLogger() );
131
132 if ( isset( $params['keyspace'] ) ) {
133 $this->keyspace = $params['keyspace'];
134 }
135
136 $this->asyncHandler = $params['asyncHandler'] ?? null;
137
138 if ( !empty( $params['reportDupes'] ) && is_callable( $this->asyncHandler ) ) {
139 $this->reportDupes = true;
140 }
141
142 $this->syncTimeout = $params['syncTimeout'] ?? 3;
143 $this->segmentationSize = $params['segmentationSize'] ?? 8388608; // 8MiB
144 $this->segmentedValueMaxSize = $params['segmentedValueMaxSize'] ?? 67108864; // 64MiB
145 }
146
147 /**
148 * @param LoggerInterface $logger
149 * @return void
150 */
151 public function setLogger( LoggerInterface $logger ) {
152 $this->logger = $logger;
153 }
154
155 /**
156 * @param bool $bool
157 */
158 public function setDebug( $bool ) {
159 $this->debugMode = $bool;
160 }
161
162 /**
163 * Get an item with the given key, regenerating and setting it if not found
164 *
165 * Nothing is stored nor deleted if the callback returns false
166 *
167 * @param string $key
168 * @param int $ttl Time-to-live (seconds)
169 * @param callable $callback Callback that derives the new value
170 * @param int $flags Bitfield of BagOStuff::READ_* or BagOStuff::WRITE_* constants [optional]
171 * @return mixed The cached value if found or the result of $callback otherwise
172 * @since 1.27
173 */
174 final public function getWithSetCallback( $key, $ttl, $callback, $flags = 0 ) {
175 $value = $this->get( $key, $flags );
176
177 if ( $value === false ) {
178 if ( !is_callable( $callback ) ) {
179 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
180 }
181 $value = call_user_func( $callback );
182 if ( $value !== false ) {
183 $this->set( $key, $value, $ttl, $flags );
184 }
185 }
186
187 return $value;
188 }
189
190 /**
191 * Get an item with the given key
192 *
193 * If the key includes a deterministic input hash (e.g. the key can only have
194 * the correct value) or complete staleness checks are handled by the caller
195 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
196 * This lets tiered backends know they can safely upgrade a cached value to
197 * higher tiers using standard TTLs.
198 *
199 * @param string $key
200 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
201 * @return mixed Returns false on failure or if the item does not exist
202 */
203 public function get( $key, $flags = 0 ) {
204 $this->trackDuplicateKeys( $key );
205
206 return $this->resolveSegments( $key, $this->doGet( $key, $flags ) );
207 }
208
209 /**
210 * Track the number of times that a given key has been used.
211 * @param string $key
212 */
213 private function trackDuplicateKeys( $key ) {
214 if ( !$this->reportDupes ) {
215 return;
216 }
217
218 if ( !isset( $this->duplicateKeyLookups[$key] ) ) {
219 // Track that we have seen this key. This N-1 counting style allows
220 // easy filtering with array_filter() later.
221 $this->duplicateKeyLookups[$key] = 0;
222 } else {
223 $this->duplicateKeyLookups[$key] += 1;
224
225 if ( $this->dupeTrackScheduled === false ) {
226 $this->dupeTrackScheduled = true;
227 // Schedule a callback that logs keys processed more than once by get().
228 call_user_func( $this->asyncHandler, function () {
229 $dups = array_filter( $this->duplicateKeyLookups );
230 foreach ( $dups as $key => $count ) {
231 $this->logger->warning(
232 'Duplicate get(): "{key}" fetched {count} times',
233 // Count is N-1 of the actual lookup count
234 [ 'key' => $key, 'count' => $count + 1, ]
235 );
236 }
237 } );
238 }
239 }
240 }
241
242 /**
243 * @param string $key
244 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
245 * @param mixed|null &$casToken Token to use for check-and-set comparisons
246 * @return mixed Returns false on failure or if the item does not exist
247 */
248 abstract protected function doGet( $key, $flags = 0, &$casToken = null );
249
250 /**
251 * Set an item
252 *
253 * @param string $key
254 * @param mixed $value
255 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
256 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
257 * @return bool Success
258 */
259 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
260 if (
261 ( $flags & self::WRITE_ALLOW_SEGMENTS ) != self::WRITE_ALLOW_SEGMENTS ||
262 is_infinite( $this->segmentationSize )
263 ) {
264 return $this->doSet( $key, $value, $exptime, $flags );
265 }
266
267 $serialized = $this->serialize( $value );
268 $segmentSize = $this->getSegmentationSize();
269 $maxTotalSize = $this->getSegmentedValueMaxSize();
270
271 $size = strlen( $serialized );
272 if ( $size <= $segmentSize ) {
273 // Since the work of serializing it was already done, just use it inline
274 return $this->doSet(
275 $key,
276 SerializedValueContainer::newUnified( $serialized ),
277 $exptime,
278 $flags
279 );
280 } elseif ( $size > $maxTotalSize ) {
281 $this->setLastError( "Key $key exceeded $maxTotalSize bytes." );
282
283 return false;
284 }
285
286 $chunksByKey = [];
287 $segmentHashes = [];
288 $count = intdiv( $size, $segmentSize ) + ( ( $size % $segmentSize ) ? 1 : 0 );
289 for ( $i = 0; $i < $count; ++$i ) {
290 $segment = substr( $serialized, $i * $segmentSize, $segmentSize );
291 $hash = sha1( $segment );
292 $chunkKey = $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $hash );
293 $chunksByKey[$chunkKey] = $segment;
294 $segmentHashes[] = $hash;
295 }
296
297 $ok = $this->setMulti( $chunksByKey, $exptime, $flags );
298 if ( $ok ) {
299 // Only when all segments are stored should the main key be changed
300 $ok = $this->doSet(
301 $key,
302 SerializedValueContainer::newSegmented( $segmentHashes ),
303 $exptime,
304 $flags
305 );
306 }
307
308 return $ok;
309 }
310
311 /**
312 * Set an item
313 *
314 * @param string $key
315 * @param mixed $value
316 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
317 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
318 * @return bool Success
319 */
320 abstract protected function doSet( $key, $value, $exptime = 0, $flags = 0 );
321
322 /**
323 * Delete an item
324 *
325 * For large values written using WRITE_ALLOW_SEGMENTS, this only deletes the main
326 * segment list key unless WRITE_PRUNE_SEGMENTS is in the flags. While deleting the segment
327 * list key has the effect of functionally deleting the key, it leaves unused blobs in cache.
328 *
329 * @param string $key
330 * @return bool True if the item was deleted or not found, false on failure
331 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
332 */
333 public function delete( $key, $flags = 0 ) {
334 if ( ( $flags & self::WRITE_PRUNE_SEGMENTS ) != self::WRITE_PRUNE_SEGMENTS ) {
335 return $this->doDelete( $key, $flags );
336 }
337
338 $mainValue = $this->doGet( $key, self::READ_LATEST );
339 if ( !$this->doDelete( $key, $flags ) ) {
340 return false;
341 }
342
343 if ( !SerializedValueContainer::isSegmented( $mainValue ) ) {
344 return true; // no segments to delete
345 }
346
347 $orderedKeys = array_map(
348 function ( $segmentHash ) use ( $key ) {
349 return $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash );
350 },
351 $mainValue->{SerializedValueContainer::SEGMENTED_HASHES}
352 );
353
354 return $this->deleteMulti( $orderedKeys, $flags );
355 }
356
357 /**
358 * Delete an item
359 *
360 * @param string $key
361 * @return bool True if the item was deleted or not found, false on failure
362 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
363 */
364 abstract protected function doDelete( $key, $flags = 0 );
365
366 /**
367 * Insert an item if it does not already exist
368 *
369 * @param string $key
370 * @param mixed $value
371 * @param int $exptime
372 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
373 * @return bool Success
374 */
375 abstract public function add( $key, $value, $exptime = 0, $flags = 0 );
376
377 /**
378 * Merge changes into the existing cache value (possibly creating a new one)
379 *
380 * The callback function returns the new value given the current value
381 * (which will be false if not present), and takes the arguments:
382 * (this BagOStuff, cache key, current value, TTL).
383 * The TTL parameter is reference set to $exptime. It can be overriden in the callback.
384 * Nothing is stored nor deleted if the callback returns false.
385 *
386 * @param string $key
387 * @param callable $callback Callback method to be executed
388 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
389 * @param int $attempts The amount of times to attempt a merge in case of failure
390 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
391 * @return bool Success
392 * @throws InvalidArgumentException
393 */
394 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
395 return $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
396 }
397
398 /**
399 * @see BagOStuff::merge()
400 *
401 * @param string $key
402 * @param callable $callback Callback method to be executed
403 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
404 * @param int $attempts The amount of times to attempt a merge in case of failure
405 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
406 * @return bool Success
407 */
408 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
409 do {
410 $casToken = null; // passed by reference
411 // Get the old value and CAS token from cache
412 $this->clearLastError();
413 $currentValue = $this->resolveSegments(
414 $key,
415 $this->doGet( $key, self::READ_LATEST, $casToken )
416 );
417 if ( $this->getLastError() ) {
418 $this->logger->warning(
419 __METHOD__ . ' failed due to I/O error on get() for {key}.',
420 [ 'key' => $key ]
421 );
422
423 return false; // don't spam retries (retry only on races)
424 }
425
426 // Derive the new value from the old value
427 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
428 $hadNoCurrentValue = ( $currentValue === false );
429 unset( $currentValue ); // free RAM in case the value is large
430
431 $this->clearLastError();
432 if ( $value === false ) {
433 $success = true; // do nothing
434 } elseif ( $hadNoCurrentValue ) {
435 // Try to create the key, failing if it gets created in the meantime
436 $success = $this->add( $key, $value, $exptime, $flags );
437 } else {
438 // Try to update the key, failing if it gets changed in the meantime
439 $success = $this->cas( $casToken, $key, $value, $exptime, $flags );
440 }
441 if ( $this->getLastError() ) {
442 $this->logger->warning(
443 __METHOD__ . ' failed due to I/O error for {key}.',
444 [ 'key' => $key ]
445 );
446
447 return false; // IO error; don't spam retries
448 }
449
450 } while ( !$success && --$attempts );
451
452 return $success;
453 }
454
455 /**
456 * Check and set an item
457 *
458 * @param mixed $casToken
459 * @param string $key
460 * @param mixed $value
461 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
462 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
463 * @return bool Success
464 */
465 protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
466 if ( !$this->lock( $key, 0 ) ) {
467 return false; // non-blocking
468 }
469
470 $curCasToken = null; // passed by reference
471 $this->doGet( $key, self::READ_LATEST, $curCasToken );
472 if ( $casToken === $curCasToken ) {
473 $success = $this->set( $key, $value, $exptime, $flags );
474 } else {
475 $this->logger->info(
476 __METHOD__ . ' failed due to race condition for {key}.',
477 [ 'key' => $key ]
478 );
479
480 $success = false; // mismatched or failed
481 }
482
483 $this->unlock( $key );
484
485 return $success;
486 }
487
488 /**
489 * Change the expiration on a key if it exists
490 *
491 * If an expiry in the past is given then the key will immediately be expired
492 *
493 * For large values written using WRITE_ALLOW_SEGMENTS, this only changes the TTL of the
494 * main segment list key. While lowering the TTL of the segment list key has the effect of
495 * functionally lowering the TTL of the key, it might leave unused blobs in cache for longer.
496 * Raising the TTL of such keys is not effective, since the expiration of a single segment
497 * key effectively expires the entire value.
498 *
499 * @param string $key
500 * @param int $exptime TTL or UNIX timestamp
501 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
502 * @return bool Success Returns false on failure or if the item does not exist
503 * @since 1.28
504 */
505 public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
506 $expiry = $this->convertToExpiry( $exptime );
507 $delete = ( $expiry != 0 && $expiry < $this->getCurrentTime() );
508
509 if ( !$this->lock( $key, 0 ) ) {
510 return false;
511 }
512 // Use doGet() to avoid having to trigger resolveSegments()
513 $blob = $this->doGet( $key, self::READ_LATEST );
514 if ( $blob ) {
515 if ( $delete ) {
516 $ok = $this->doDelete( $key, $flags );
517 } else {
518 $ok = $this->doSet( $key, $blob, $exptime, $flags );
519 }
520 } else {
521 $ok = false;
522 }
523
524 $this->unlock( $key );
525
526 return $ok;
527 }
528
529 /**
530 * Acquire an advisory lock on a key string
531 *
532 * Note that if reentry is enabled, duplicate calls ignore $expiry
533 *
534 * @param string $key
535 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
536 * @param int $expiry Lock expiry [optional]; 1 day maximum
537 * @param string $rclass Allow reentry if set and the current lock used this value
538 * @return bool Success
539 */
540 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
541 // Avoid deadlocks and allow lock reentry if specified
542 if ( isset( $this->locks[$key] ) ) {
543 if ( $rclass != '' && $this->locks[$key]['class'] === $rclass ) {
544 ++$this->locks[$key]['depth'];
545 return true;
546 } else {
547 return false;
548 }
549 }
550
551 $fname = __METHOD__;
552 $expiry = min( $expiry ?: INF, self::TTL_DAY );
553 $loop = new WaitConditionLoop(
554 function () use ( $key, $expiry, $fname ) {
555 $this->clearLastError();
556 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
557 return WaitConditionLoop::CONDITION_REACHED; // locked!
558 } elseif ( $this->getLastError() ) {
559 $this->logger->warning(
560 $fname . ' failed due to I/O error for {key}.',
561 [ 'key' => $key ]
562 );
563
564 return WaitConditionLoop::CONDITION_ABORTED; // network partition?
565 }
566
567 return WaitConditionLoop::CONDITION_CONTINUE;
568 },
569 $timeout
570 );
571
572 $code = $loop->invoke();
573 $locked = ( $code === $loop::CONDITION_REACHED );
574 if ( $locked ) {
575 $this->locks[$key] = [ 'class' => $rclass, 'depth' => 1 ];
576 } elseif ( $code === $loop::CONDITION_TIMED_OUT ) {
577 $this->logger->warning(
578 "$fname failed due to timeout for {key}.",
579 [ 'key' => $key, 'timeout' => $timeout ]
580 );
581 }
582
583 return $locked;
584 }
585
586 /**
587 * Release an advisory lock on a key string
588 *
589 * @param string $key
590 * @return bool Success
591 */
592 public function unlock( $key ) {
593 if ( !isset( $this->locks[$key] ) ) {
594 return false;
595 }
596
597 if ( --$this->locks[$key]['depth'] <= 0 ) {
598 unset( $this->locks[$key] );
599
600 $ok = $this->doDelete( "{$key}:lock" );
601 if ( !$ok ) {
602 $this->logger->warning(
603 __METHOD__ . ' failed to release lock for {key}.',
604 [ 'key' => $key ]
605 );
606 }
607
608 return $ok;
609 }
610
611 return true;
612 }
613
614 /**
615 * Get a lightweight exclusive self-unlocking lock
616 *
617 * Note that the same lock cannot be acquired twice.
618 *
619 * This is useful for task de-duplication or to avoid obtrusive
620 * (though non-corrupting) DB errors like INSERT key conflicts
621 * or deadlocks when using LOCK IN SHARE MODE.
622 *
623 * @param string $key
624 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
625 * @param int $expiry Lock expiry [optional]; 1 day maximum
626 * @param string $rclass Allow reentry if set and the current lock used this value
627 * @return ScopedCallback|null Returns null on failure
628 * @since 1.26
629 */
630 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
631 $expiry = min( $expiry ?: INF, self::TTL_DAY );
632
633 if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
634 return null;
635 }
636
637 $lSince = $this->getCurrentTime(); // lock timestamp
638
639 return new ScopedCallback( function () use ( $key, $lSince, $expiry ) {
640 $latency = 0.050; // latency skew (err towards keeping lock present)
641 $age = ( $this->getCurrentTime() - $lSince + $latency );
642 if ( ( $age + $latency ) >= $expiry ) {
643 $this->logger->warning(
644 "Lock for {key} held too long ({age} sec).",
645 [ 'key' => $key, 'age' => $age ]
646 );
647 return; // expired; it's not "safe" to delete the key
648 }
649 $this->unlock( $key );
650 } );
651 }
652
653 /**
654 * Delete all objects expiring before a certain date.
655 * @param string|int $timestamp The reference date in MW or TS_UNIX format
656 * @param callable|null $progressCallback Optional, a function which will be called
657 * regularly during long-running operations with the percentage progress
658 * as the first parameter. [optional]
659 * @param int $limit Maximum number of keys to delete [default: INF]
660 *
661 * @return bool Success, false if unimplemented
662 */
663 public function deleteObjectsExpiringBefore(
664 $timestamp,
665 callable $progressCallback = null,
666 $limit = INF
667 ) {
668 // stub
669 return false;
670 }
671
672 /**
673 * Get an associative array containing the item for each of the keys that have items.
674 * @param string[] $keys List of keys
675 * @param int $flags Bitfield; supports READ_LATEST [optional]
676 * @return array
677 */
678 public function getMulti( array $keys, $flags = 0 ) {
679 $valuesBykey = $this->doGetMulti( $keys, $flags );
680 foreach ( $valuesBykey as $key => $value ) {
681 // Resolve one blob at a time (avoids too much I/O at once)
682 $valuesBykey[$key] = $this->resolveSegments( $key, $value );
683 }
684
685 return $valuesBykey;
686 }
687
688 /**
689 * Get an associative array containing the item for each of the keys that have items.
690 * @param string[] $keys List of keys
691 * @param int $flags Bitfield; supports READ_LATEST [optional]
692 * @return array
693 */
694 protected function doGetMulti( array $keys, $flags = 0 ) {
695 $res = [];
696 foreach ( $keys as $key ) {
697 $val = $this->doGet( $key, $flags );
698 if ( $val !== false ) {
699 $res[$key] = $val;
700 }
701 }
702
703 return $res;
704 }
705
706 /**
707 * Batch insertion/replace
708 *
709 * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O
710 *
711 * @param mixed[] $data Map of (key => value)
712 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
713 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
714 * @return bool Success
715 * @since 1.24
716 */
717 public function setMulti( array $data, $exptime = 0, $flags = 0 ) {
718 if ( ( $flags & self::WRITE_ALLOW_SEGMENTS ) === self::WRITE_ALLOW_SEGMENTS ) {
719 throw new InvalidArgumentException( __METHOD__ . ' got WRITE_ALLOW_SEGMENTS' );
720 }
721
722 $res = true;
723 foreach ( $data as $key => $value ) {
724 $res = $this->doSet( $key, $value, $exptime, $flags ) && $res;
725 }
726
727 return $res;
728 }
729
730 /**
731 * Batch deletion
732 *
733 * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O
734 *
735 * @param string[] $keys List of keys
736 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
737 * @return bool Success
738 * @since 1.33
739 */
740 public function deleteMulti( array $keys, $flags = 0 ) {
741 $res = true;
742 foreach ( $keys as $key ) {
743 $res = $this->doDelete( $key, $flags ) && $res;
744 }
745
746 return $res;
747 }
748
749 /**
750 * Increase stored value of $key by $value while preserving its TTL
751 * @param string $key Key to increase
752 * @param int $value Value to add to $key (default: 1) [optional]
753 * @return int|bool New value or false on failure
754 */
755 abstract public function incr( $key, $value = 1 );
756
757 /**
758 * Decrease stored value of $key by $value while preserving its TTL
759 * @param string $key
760 * @param int $value Value to subtract from $key (default: 1) [optional]
761 * @return int|bool New value or false on failure
762 */
763 public function decr( $key, $value = 1 ) {
764 return $this->incr( $key, - $value );
765 }
766
767 /**
768 * Increase stored value of $key by $value while preserving its TTL
769 *
770 * This will create the key with value $init and TTL $ttl instead if not present
771 *
772 * @param string $key
773 * @param int $ttl
774 * @param int $value
775 * @param int $init
776 * @return int|bool New value or false on failure
777 * @since 1.24
778 */
779 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
780 $this->clearLastError();
781 $newValue = $this->incr( $key, $value );
782 if ( $newValue === false && !$this->getLastError() ) {
783 // No key set; initialize
784 $newValue = $this->add( $key, (int)$init, $ttl ) ? $init : false;
785 if ( $newValue === false && !$this->getLastError() ) {
786 // Raced out initializing; increment
787 $newValue = $this->incr( $key, $value );
788 }
789 }
790
791 return $newValue;
792 }
793
794 /**
795 * Get and reassemble the chunks of blob at the given key
796 *
797 * @param string $key
798 * @param mixed $mainValue
799 * @return string|null|bool The combined string, false if missing, null on error
800 */
801 protected function resolveSegments( $key, $mainValue ) {
802 if ( SerializedValueContainer::isUnified( $mainValue ) ) {
803 return $this->unserialize( $mainValue->{SerializedValueContainer::UNIFIED_DATA} );
804 }
805
806 if ( SerializedValueContainer::isSegmented( $mainValue ) ) {
807 $orderedKeys = array_map(
808 function ( $segmentHash ) use ( $key ) {
809 return $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash );
810 },
811 $mainValue->{SerializedValueContainer::SEGMENTED_HASHES}
812 );
813
814 $segmentsByKey = $this->doGetMulti( $orderedKeys );
815
816 $parts = [];
817 foreach ( $orderedKeys as $segmentKey ) {
818 if ( isset( $segmentsByKey[$segmentKey] ) ) {
819 $parts[] = $segmentsByKey[$segmentKey];
820 } else {
821 return false; // missing segment
822 }
823 }
824
825 return $this->unserialize( implode( '', $parts ) );
826 }
827
828 return $mainValue;
829 }
830
831 /**
832 * Get the "last error" registered; clearLastError() should be called manually
833 * @return int ERR_* constant for the "last error" registry
834 * @since 1.23
835 */
836 public function getLastError() {
837 return $this->lastError;
838 }
839
840 /**
841 * Clear the "last error" registry
842 * @since 1.23
843 */
844 public function clearLastError() {
845 $this->lastError = self::ERR_NONE;
846 }
847
848 /**
849 * Set the "last error" registry
850 * @param int $err ERR_* constant
851 * @since 1.23
852 */
853 protected function setLastError( $err ) {
854 $this->lastError = $err;
855 }
856
857 /**
858 * Let a callback be run to avoid wasting time on special blocking calls
859 *
860 * The callbacks may or may not be called ever, in any particular order.
861 * They are likely to be invoked when something WRITE_SYNC is used used.
862 * They should follow a caching pattern as shown below, so that any code
863 * using the work will get it's result no matter what happens.
864 * @code
865 * $result = null;
866 * $workCallback = function () use ( &$result ) {
867 * if ( !$result ) {
868 * $result = ....
869 * }
870 * return $result;
871 * }
872 * @endcode
873 *
874 * @param callable $workCallback
875 * @since 1.28
876 */
877 public function addBusyCallback( callable $workCallback ) {
878 $this->busyCallbacks[] = $workCallback;
879 }
880
881 /**
882 * @param string $text
883 */
884 protected function debug( $text ) {
885 if ( $this->debugMode ) {
886 $this->logger->debug( "{class} debug: $text", [
887 'class' => static::class,
888 ] );
889 }
890 }
891
892 /**
893 * @param int $exptime
894 * @return bool
895 */
896 protected function expiryIsRelative( $exptime ) {
897 return ( $exptime != 0 && $exptime < ( 10 * self::TTL_YEAR ) );
898 }
899
900 /**
901 * Convert an optionally relative time to an absolute time
902 * @param int $exptime
903 * @return int
904 */
905 protected function convertToExpiry( $exptime ) {
906 if ( $this->expiryIsRelative( $exptime ) ) {
907 return (int)$this->getCurrentTime() + $exptime;
908 } else {
909 return $exptime;
910 }
911 }
912
913 /**
914 * Convert an optionally absolute expiry time to a relative time. If an
915 * absolute time is specified which is in the past, use a short expiry time.
916 *
917 * @param int $exptime
918 * @return int
919 */
920 protected function convertToRelative( $exptime ) {
921 if ( $exptime >= ( 10 * self::TTL_YEAR ) ) {
922 $exptime -= (int)$this->getCurrentTime();
923 if ( $exptime <= 0 ) {
924 $exptime = 1;
925 }
926 return $exptime;
927 } else {
928 return $exptime;
929 }
930 }
931
932 /**
933 * Check if a value is an integer
934 *
935 * @param mixed $value
936 * @return bool
937 */
938 protected function isInteger( $value ) {
939 if ( is_int( $value ) ) {
940 return true;
941 } elseif ( !is_string( $value ) ) {
942 return false;
943 }
944
945 $integer = (int)$value;
946
947 return ( $value === (string)$integer );
948 }
949
950 /**
951 * Construct a cache key.
952 *
953 * @since 1.27
954 * @param string $keyspace
955 * @param array $args
956 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
957 */
958 public function makeKeyInternal( $keyspace, $args ) {
959 $key = $keyspace;
960 foreach ( $args as $arg ) {
961 $key .= ':' . str_replace( ':', '%3A', $arg );
962 }
963 return strtr( $key, ' ', '_' );
964 }
965
966 /**
967 * Make a global cache key.
968 *
969 * @since 1.27
970 * @param string $class Key class
971 * @param string|null $component [optional] Key component (starting with a key collection name)
972 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
973 */
974 public function makeGlobalKey( $class, $component = null ) {
975 return $this->makeKeyInternal( 'global', func_get_args() );
976 }
977
978 /**
979 * Make a cache key, scoped to this instance's keyspace.
980 *
981 * @since 1.27
982 * @param string $class Key class
983 * @param string|null $component [optional] Key component (starting with a key collection name)
984 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
985 */
986 public function makeKey( $class, $component = null ) {
987 return $this->makeKeyInternal( $this->keyspace, func_get_args() );
988 }
989
990 /**
991 * @param int $flag ATTR_* class constant
992 * @return int QOS_* class constant
993 * @since 1.28
994 */
995 public function getQoS( $flag ) {
996 return $this->attrMap[$flag] ?? self::QOS_UNKNOWN;
997 }
998
999 /**
1000 * @return int|float The chunk size, in bytes, of segmented objects (INF for no limit)
1001 * @since 1.34
1002 */
1003 public function getSegmentationSize() {
1004 return $this->segmentationSize;
1005 }
1006
1007 /**
1008 * @return int|float Maximum total segmented object size in bytes (INF for no limit)
1009 * @since 1.34
1010 */
1011 public function getSegmentedValueMaxSize() {
1012 return $this->segmentedValueMaxSize;
1013 }
1014
1015 /**
1016 * Merge the flag maps of one or more BagOStuff objects into a "lowest common denominator" map
1017 *
1018 * @param BagOStuff[] $bags
1019 * @return int[] Resulting flag map (class ATTR_* constant => class QOS_* constant)
1020 */
1021 protected function mergeFlagMaps( array $bags ) {
1022 $map = [];
1023 foreach ( $bags as $bag ) {
1024 foreach ( $bag->attrMap as $attr => $rank ) {
1025 if ( isset( $map[$attr] ) ) {
1026 $map[$attr] = min( $map[$attr], $rank );
1027 } else {
1028 $map[$attr] = $rank;
1029 }
1030 }
1031 }
1032
1033 return $map;
1034 }
1035
1036 /**
1037 * @internal For testing only
1038 * @return float UNIX timestamp
1039 * @codeCoverageIgnore
1040 */
1041 public function getCurrentTime() {
1042 return $this->wallClockOverride ?: microtime( true );
1043 }
1044
1045 /**
1046 * @internal For testing only
1047 * @param float|null &$time Mock UNIX timestamp
1048 * @codeCoverageIgnore
1049 */
1050 public function setMockTime( &$time ) {
1051 $this->wallClockOverride =& $time;
1052 }
1053
1054 /**
1055 * @param mixed $value
1056 * @return string|int String/integer representation
1057 * @note Special handling is usually needed for integers so incr()/decr() work
1058 */
1059 protected function serialize( $value ) {
1060 return is_int( $value ) ? $value : serialize( $value );
1061 }
1062
1063 /**
1064 * @param string|int $value
1065 * @return mixed Original value or false on error
1066 * @note Special handling is usually needed for integers so incr()/decr() work
1067 */
1068 protected function unserialize( $value ) {
1069 return $this->isInteger( $value ) ? (int)$value : unserialize( $value );
1070 }
1071 }