Merge "Title: Title::getSubpage should not lose the interwiki prefix"
[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 is_int( $value ) || // avoid breaking incr()/decr()
262 ( $flags & self::WRITE_ALLOW_SEGMENTS ) != self::WRITE_ALLOW_SEGMENTS ||
263 is_infinite( $this->segmentationSize )
264 ) {
265 return $this->doSet( $key, $value, $exptime, $flags );
266 }
267
268 $serialized = $this->serialize( $value );
269 $segmentSize = $this->getSegmentationSize();
270 $maxTotalSize = $this->getSegmentedValueMaxSize();
271
272 $size = strlen( $serialized );
273 if ( $size <= $segmentSize ) {
274 // Since the work of serializing it was already done, just use it inline
275 return $this->doSet(
276 $key,
277 SerializedValueContainer::newUnified( $serialized ),
278 $exptime,
279 $flags
280 );
281 } elseif ( $size > $maxTotalSize ) {
282 $this->setLastError( "Key $key exceeded $maxTotalSize bytes." );
283
284 return false;
285 }
286
287 $chunksByKey = [];
288 $segmentHashes = [];
289 $count = intdiv( $size, $segmentSize ) + ( ( $size % $segmentSize ) ? 1 : 0 );
290 for ( $i = 0; $i < $count; ++$i ) {
291 $segment = substr( $serialized, $i * $segmentSize, $segmentSize );
292 $hash = sha1( $segment );
293 $chunkKey = $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $hash );
294 $chunksByKey[$chunkKey] = $segment;
295 $segmentHashes[] = $hash;
296 }
297
298 $flags &= ~self::WRITE_ALLOW_SEGMENTS; // sanity
299 $ok = $this->setMulti( $chunksByKey, $exptime, $flags );
300 if ( $ok ) {
301 // Only when all segments are stored should the main key be changed
302 $ok = $this->doSet(
303 $key,
304 SerializedValueContainer::newSegmented( $segmentHashes ),
305 $exptime,
306 $flags
307 );
308 }
309
310 return $ok;
311 }
312
313 /**
314 * Set an item
315 *
316 * @param string $key
317 * @param mixed $value
318 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
319 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
320 * @return bool Success
321 */
322 abstract protected function doSet( $key, $value, $exptime = 0, $flags = 0 );
323
324 /**
325 * Delete an item
326 *
327 * For large values written using WRITE_ALLOW_SEGMENTS, this only deletes the main
328 * segment list key unless WRITE_PRUNE_SEGMENTS is in the flags. While deleting the segment
329 * list key has the effect of functionally deleting the key, it leaves unused blobs in cache.
330 *
331 * @param string $key
332 * @return bool True if the item was deleted or not found, false on failure
333 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
334 */
335 public function delete( $key, $flags = 0 ) {
336 if ( ( $flags & self::WRITE_PRUNE_SEGMENTS ) != self::WRITE_PRUNE_SEGMENTS ) {
337 return $this->doDelete( $key, $flags );
338 }
339
340 $mainValue = $this->doGet( $key, self::READ_LATEST );
341 if ( !$this->doDelete( $key, $flags ) ) {
342 return false;
343 }
344
345 if ( !SerializedValueContainer::isSegmented( $mainValue ) ) {
346 return true; // no segments to delete
347 }
348
349 $orderedKeys = array_map(
350 function ( $segmentHash ) use ( $key ) {
351 return $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash );
352 },
353 $mainValue->{SerializedValueContainer::SEGMENTED_HASHES}
354 );
355
356 return $this->deleteMulti( $orderedKeys, $flags );
357 }
358
359 /**
360 * Delete an item
361 *
362 * @param string $key
363 * @return bool True if the item was deleted or not found, false on failure
364 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
365 */
366 abstract protected function doDelete( $key, $flags = 0 );
367
368 /**
369 * Insert an item if it does not already exist
370 *
371 * @param string $key
372 * @param mixed $value
373 * @param int $exptime
374 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
375 * @return bool Success
376 */
377 abstract public function add( $key, $value, $exptime = 0, $flags = 0 );
378
379 /**
380 * Merge changes into the existing cache value (possibly creating a new one)
381 *
382 * The callback function returns the new value given the current value
383 * (which will be false if not present), and takes the arguments:
384 * (this BagOStuff, cache key, current value, TTL).
385 * The TTL parameter is reference set to $exptime. It can be overriden in the callback.
386 * Nothing is stored nor deleted if the callback returns false.
387 *
388 * @param string $key
389 * @param callable $callback Callback method to be executed
390 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
391 * @param int $attempts The amount of times to attempt a merge in case of failure
392 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
393 * @return bool Success
394 * @throws InvalidArgumentException
395 */
396 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
397 return $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
398 }
399
400 /**
401 * @see BagOStuff::merge()
402 *
403 * @param string $key
404 * @param callable $callback Callback method to be executed
405 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
406 * @param int $attempts The amount of times to attempt a merge in case of failure
407 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
408 * @return bool Success
409 */
410 final protected function mergeViaCas( $key, callable $callback, $exptime, $attempts, $flags ) {
411 do {
412 $casToken = null; // passed by reference
413 // Get the old value and CAS token from cache
414 $this->clearLastError();
415 $currentValue = $this->resolveSegments(
416 $key,
417 $this->doGet( $key, self::READ_LATEST, $casToken )
418 );
419 if ( $this->getLastError() ) {
420 $this->logger->warning(
421 __METHOD__ . ' failed due to I/O error on get() for {key}.',
422 [ 'key' => $key ]
423 );
424
425 return false; // don't spam retries (retry only on races)
426 }
427
428 // Derive the new value from the old value
429 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
430 $hadNoCurrentValue = ( $currentValue === false );
431 unset( $currentValue ); // free RAM in case the value is large
432
433 $this->clearLastError();
434 if ( $value === false ) {
435 $success = true; // do nothing
436 } elseif ( $hadNoCurrentValue ) {
437 // Try to create the key, failing if it gets created in the meantime
438 $success = $this->add( $key, $value, $exptime, $flags );
439 } else {
440 // Try to update the key, failing if it gets changed in the meantime
441 $success = $this->cas( $casToken, $key, $value, $exptime, $flags );
442 }
443 if ( $this->getLastError() ) {
444 $this->logger->warning(
445 __METHOD__ . ' failed due to I/O error for {key}.',
446 [ 'key' => $key ]
447 );
448
449 return false; // IO error; don't spam retries
450 }
451
452 } while ( !$success && --$attempts );
453
454 return $success;
455 }
456
457 /**
458 * Check and set an item
459 *
460 * @param mixed $casToken
461 * @param string $key
462 * @param mixed $value
463 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
464 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
465 * @return bool Success
466 */
467 protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
468 if ( !$this->lock( $key, 0 ) ) {
469 return false; // non-blocking
470 }
471
472 $curCasToken = null; // passed by reference
473 $this->doGet( $key, self::READ_LATEST, $curCasToken );
474 if ( $casToken === $curCasToken ) {
475 $success = $this->set( $key, $value, $exptime, $flags );
476 } else {
477 $this->logger->info(
478 __METHOD__ . ' failed due to race condition for {key}.',
479 [ 'key' => $key ]
480 );
481
482 $success = false; // mismatched or failed
483 }
484
485 $this->unlock( $key );
486
487 return $success;
488 }
489
490 /**
491 * Change the expiration on a key if it exists
492 *
493 * If an expiry in the past is given then the key will immediately be expired
494 *
495 * For large values written using WRITE_ALLOW_SEGMENTS, this only changes the TTL of the
496 * main segment list key. While lowering the TTL of the segment list key has the effect of
497 * functionally lowering the TTL of the key, it might leave unused blobs in cache for longer.
498 * Raising the TTL of such keys is not effective, since the expiration of a single segment
499 * key effectively expires the entire value.
500 *
501 * @param string $key
502 * @param int $exptime TTL or UNIX timestamp
503 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
504 * @return bool Success Returns false on failure or if the item does not exist
505 * @since 1.28
506 */
507 public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
508 return $this->doChangeTTL( $key, $exptime, $flags );
509 }
510
511 /**
512 * @param string $key
513 * @param int $exptime
514 * @param int $flags
515 * @return bool
516 */
517 protected function doChangeTTL( $key, $exptime, $flags ) {
518 $expiry = $this->convertToExpiry( $exptime );
519 $delete = ( $expiry != 0 && $expiry < $this->getCurrentTime() );
520
521 if ( !$this->lock( $key, 0 ) ) {
522 return false;
523 }
524 // Use doGet() to avoid having to trigger resolveSegments()
525 $blob = $this->doGet( $key, self::READ_LATEST );
526 if ( $blob ) {
527 if ( $delete ) {
528 $ok = $this->doDelete( $key, $flags );
529 } else {
530 $ok = $this->doSet( $key, $blob, $exptime, $flags );
531 }
532 } else {
533 $ok = false;
534 }
535
536 $this->unlock( $key );
537
538 return $ok;
539 }
540
541 /**
542 * Acquire an advisory lock on a key string
543 *
544 * Note that if reentry is enabled, duplicate calls ignore $expiry
545 *
546 * @param string $key
547 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
548 * @param int $expiry Lock expiry [optional]; 1 day maximum
549 * @param string $rclass Allow reentry if set and the current lock used this value
550 * @return bool Success
551 */
552 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
553 // Avoid deadlocks and allow lock reentry if specified
554 if ( isset( $this->locks[$key] ) ) {
555 if ( $rclass != '' && $this->locks[$key]['class'] === $rclass ) {
556 ++$this->locks[$key]['depth'];
557 return true;
558 } else {
559 return false;
560 }
561 }
562
563 $fname = __METHOD__;
564 $expiry = min( $expiry ?: INF, self::TTL_DAY );
565 $loop = new WaitConditionLoop(
566 function () use ( $key, $expiry, $fname ) {
567 $this->clearLastError();
568 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
569 return WaitConditionLoop::CONDITION_REACHED; // locked!
570 } elseif ( $this->getLastError() ) {
571 $this->logger->warning(
572 $fname . ' failed due to I/O error for {key}.',
573 [ 'key' => $key ]
574 );
575
576 return WaitConditionLoop::CONDITION_ABORTED; // network partition?
577 }
578
579 return WaitConditionLoop::CONDITION_CONTINUE;
580 },
581 $timeout
582 );
583
584 $code = $loop->invoke();
585 $locked = ( $code === $loop::CONDITION_REACHED );
586 if ( $locked ) {
587 $this->locks[$key] = [ 'class' => $rclass, 'depth' => 1 ];
588 } elseif ( $code === $loop::CONDITION_TIMED_OUT ) {
589 $this->logger->warning(
590 "$fname failed due to timeout for {key}.",
591 [ 'key' => $key, 'timeout' => $timeout ]
592 );
593 }
594
595 return $locked;
596 }
597
598 /**
599 * Release an advisory lock on a key string
600 *
601 * @param string $key
602 * @return bool Success
603 */
604 public function unlock( $key ) {
605 if ( !isset( $this->locks[$key] ) ) {
606 return false;
607 }
608
609 if ( --$this->locks[$key]['depth'] <= 0 ) {
610 unset( $this->locks[$key] );
611
612 $ok = $this->doDelete( "{$key}:lock" );
613 if ( !$ok ) {
614 $this->logger->warning(
615 __METHOD__ . ' failed to release lock for {key}.',
616 [ 'key' => $key ]
617 );
618 }
619
620 return $ok;
621 }
622
623 return true;
624 }
625
626 /**
627 * Get a lightweight exclusive self-unlocking lock
628 *
629 * Note that the same lock cannot be acquired twice.
630 *
631 * This is useful for task de-duplication or to avoid obtrusive
632 * (though non-corrupting) DB errors like INSERT key conflicts
633 * or deadlocks when using LOCK IN SHARE MODE.
634 *
635 * @param string $key
636 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
637 * @param int $expiry Lock expiry [optional]; 1 day maximum
638 * @param string $rclass Allow reentry if set and the current lock used this value
639 * @return ScopedCallback|null Returns null on failure
640 * @since 1.26
641 */
642 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
643 $expiry = min( $expiry ?: INF, self::TTL_DAY );
644
645 if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
646 return null;
647 }
648
649 $lSince = $this->getCurrentTime(); // lock timestamp
650
651 return new ScopedCallback( function () use ( $key, $lSince, $expiry ) {
652 $latency = 0.050; // latency skew (err towards keeping lock present)
653 $age = ( $this->getCurrentTime() - $lSince + $latency );
654 if ( ( $age + $latency ) >= $expiry ) {
655 $this->logger->warning(
656 "Lock for {key} held too long ({age} sec).",
657 [ 'key' => $key, 'age' => $age ]
658 );
659 return; // expired; it's not "safe" to delete the key
660 }
661 $this->unlock( $key );
662 } );
663 }
664
665 /**
666 * Delete all objects expiring before a certain date.
667 * @param string|int $timestamp The reference date in MW or TS_UNIX format
668 * @param callable|null $progress Optional, a function which will be called
669 * regularly during long-running operations with the percentage progress
670 * as the first parameter. [optional]
671 * @param int $limit Maximum number of keys to delete [default: INF]
672 *
673 * @return bool Success; false if unimplemented
674 */
675 public function deleteObjectsExpiringBefore(
676 $timestamp,
677 callable $progress = null,
678 $limit = INF
679 ) {
680 return false;
681 }
682
683 /**
684 * Get an associative array containing the item for each of the keys that have items.
685 * @param string[] $keys List of keys
686 * @param int $flags Bitfield; supports READ_LATEST [optional]
687 * @return array Map of (key => value) for existing keys
688 */
689 public function getMulti( array $keys, $flags = 0 ) {
690 $valuesBykey = $this->doGetMulti( $keys, $flags );
691 foreach ( $valuesBykey as $key => $value ) {
692 // Resolve one blob at a time (avoids too much I/O at once)
693 $valuesBykey[$key] = $this->resolveSegments( $key, $value );
694 }
695
696 return $valuesBykey;
697 }
698
699 /**
700 * Get an associative array containing the item for each of the keys that have items.
701 * @param string[] $keys List of keys
702 * @param int $flags Bitfield; supports READ_LATEST [optional]
703 * @return array Map of (key => value) for existing keys
704 */
705 protected function doGetMulti( array $keys, $flags = 0 ) {
706 $res = [];
707 foreach ( $keys as $key ) {
708 $val = $this->doGet( $key, $flags );
709 if ( $val !== false ) {
710 $res[$key] = $val;
711 }
712 }
713
714 return $res;
715 }
716
717 /**
718 * Batch insertion/replace
719 *
720 * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O
721 *
722 * @param mixed[] $data Map of (key => value)
723 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
724 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
725 * @return bool Success
726 * @since 1.24
727 */
728 public function setMulti( array $data, $exptime = 0, $flags = 0 ) {
729 if ( ( $flags & self::WRITE_ALLOW_SEGMENTS ) === self::WRITE_ALLOW_SEGMENTS ) {
730 throw new InvalidArgumentException( __METHOD__ . ' got WRITE_ALLOW_SEGMENTS' );
731 }
732 return $this->doSetMulti( $data, $exptime, $flags );
733 }
734
735 /**
736 * @param mixed[] $data Map of (key => value)
737 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
738 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
739 * @return bool Success
740 */
741 protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
742 $res = true;
743 foreach ( $data as $key => $value ) {
744 $res = $this->doSet( $key, $value, $exptime, $flags ) && $res;
745 }
746 return $res;
747 }
748
749 /**
750 * Batch deletion
751 *
752 * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O
753 *
754 * @param string[] $keys List of keys
755 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
756 * @return bool Success
757 * @since 1.33
758 */
759 public function deleteMulti( array $keys, $flags = 0 ) {
760 if ( ( $flags & self::WRITE_ALLOW_SEGMENTS ) === self::WRITE_ALLOW_SEGMENTS ) {
761 throw new InvalidArgumentException( __METHOD__ . ' got WRITE_ALLOW_SEGMENTS' );
762 }
763 return $this->doDeleteMulti( $keys, $flags );
764 }
765
766 /**
767 * @param string[] $keys List of keys
768 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
769 * @return bool Success
770 */
771 protected function doDeleteMulti( array $keys, $flags = 0 ) {
772 $res = true;
773 foreach ( $keys as $key ) {
774 $res = $this->doDelete( $key, $flags ) && $res;
775 }
776 return $res;
777 }
778
779 /**
780 * Change the expiration of multiple keys that exist
781 *
782 * @see BagOStuff::changeTTL()
783 *
784 * @param string[] $keys List of keys
785 * @param int $exptime TTL or UNIX timestamp
786 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
787 * @return bool Success
788 * @since 1.34
789 */
790 public function changeTTLMulti( array $keys, $exptime, $flags = 0 ) {
791 $res = true;
792 foreach ( $keys as $key ) {
793 $res = $this->doChangeTTL( $key, $exptime, $flags ) && $res;
794 }
795
796 return $res;
797 }
798
799 /**
800 * Increase stored value of $key by $value while preserving its TTL
801 * @param string $key Key to increase
802 * @param int $value Value to add to $key (default: 1) [optional]
803 * @return int|bool New value or false on failure
804 */
805 abstract public function incr( $key, $value = 1 );
806
807 /**
808 * Decrease stored value of $key by $value while preserving its TTL
809 * @param string $key
810 * @param int $value Value to subtract from $key (default: 1) [optional]
811 * @return int|bool New value or false on failure
812 */
813 public function decr( $key, $value = 1 ) {
814 return $this->incr( $key, - $value );
815 }
816
817 /**
818 * Increase stored value of $key by $value while preserving its TTL
819 *
820 * This will create the key with value $init and TTL $ttl instead if not present
821 *
822 * @param string $key
823 * @param int $ttl
824 * @param int $value
825 * @param int $init
826 * @return int|bool New value or false on failure
827 * @since 1.24
828 */
829 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
830 $this->clearLastError();
831 $newValue = $this->incr( $key, $value );
832 if ( $newValue === false && !$this->getLastError() ) {
833 // No key set; initialize
834 $newValue = $this->add( $key, (int)$init, $ttl ) ? $init : false;
835 if ( $newValue === false && !$this->getLastError() ) {
836 // Raced out initializing; increment
837 $newValue = $this->incr( $key, $value );
838 }
839 }
840
841 return $newValue;
842 }
843
844 /**
845 * Get and reassemble the chunks of blob at the given key
846 *
847 * @param string $key
848 * @param mixed $mainValue
849 * @return string|null|bool The combined string, false if missing, null on error
850 */
851 final protected function resolveSegments( $key, $mainValue ) {
852 if ( SerializedValueContainer::isUnified( $mainValue ) ) {
853 return $this->unserialize( $mainValue->{SerializedValueContainer::UNIFIED_DATA} );
854 }
855
856 if ( SerializedValueContainer::isSegmented( $mainValue ) ) {
857 $orderedKeys = array_map(
858 function ( $segmentHash ) use ( $key ) {
859 return $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash );
860 },
861 $mainValue->{SerializedValueContainer::SEGMENTED_HASHES}
862 );
863
864 $segmentsByKey = $this->doGetMulti( $orderedKeys );
865
866 $parts = [];
867 foreach ( $orderedKeys as $segmentKey ) {
868 if ( isset( $segmentsByKey[$segmentKey] ) ) {
869 $parts[] = $segmentsByKey[$segmentKey];
870 } else {
871 return false; // missing segment
872 }
873 }
874
875 return $this->unserialize( implode( '', $parts ) );
876 }
877
878 return $mainValue;
879 }
880
881 /**
882 * Get the "last error" registered; clearLastError() should be called manually
883 * @return int ERR_* constant for the "last error" registry
884 * @since 1.23
885 */
886 public function getLastError() {
887 return $this->lastError;
888 }
889
890 /**
891 * Clear the "last error" registry
892 * @since 1.23
893 */
894 public function clearLastError() {
895 $this->lastError = self::ERR_NONE;
896 }
897
898 /**
899 * Set the "last error" registry
900 * @param int $err ERR_* constant
901 * @since 1.23
902 */
903 protected function setLastError( $err ) {
904 $this->lastError = $err;
905 }
906
907 /**
908 * Let a callback be run to avoid wasting time on special blocking calls
909 *
910 * The callbacks may or may not be called ever, in any particular order.
911 * They are likely to be invoked when something WRITE_SYNC is used used.
912 * They should follow a caching pattern as shown below, so that any code
913 * using the work will get it's result no matter what happens.
914 * @code
915 * $result = null;
916 * $workCallback = function () use ( &$result ) {
917 * if ( !$result ) {
918 * $result = ....
919 * }
920 * return $result;
921 * }
922 * @endcode
923 *
924 * @param callable $workCallback
925 * @since 1.28
926 */
927 final public function addBusyCallback( callable $workCallback ) {
928 $this->busyCallbacks[] = $workCallback;
929 }
930
931 /**
932 * @param string $text
933 */
934 protected function debug( $text ) {
935 if ( $this->debugMode ) {
936 $this->logger->debug( "{class} debug: $text", [ 'class' => static::class ] );
937 }
938 }
939
940 /**
941 * @param int $exptime
942 * @return bool
943 */
944 final protected function expiryIsRelative( $exptime ) {
945 return ( $exptime != 0 && $exptime < ( 10 * self::TTL_YEAR ) );
946 }
947
948 /**
949 * Convert an optionally relative timestamp to an absolute time
950 *
951 * The input value will be cast to an integer and interpreted as follows:
952 * - zero: no expiry; return zero (e.g. TTL_INDEFINITE)
953 * - negative: relative TTL; return UNIX timestamp offset by this value
954 * - positive (< 10 years): relative TTL; return UNIX timestamp offset by this value
955 * - positive (>= 10 years): absolute UNIX timestamp; return this value
956 *
957 * @param int $exptime Absolute TTL or 0 for indefinite
958 * @return int
959 */
960 final protected function convertToExpiry( $exptime ) {
961 return $this->expiryIsRelative( $exptime )
962 ? (int)$this->getCurrentTime() + $exptime
963 : $exptime;
964 }
965
966 /**
967 * Convert an optionally absolute expiry time to a relative time. If an
968 * absolute time is specified which is in the past, use a short expiry time.
969 *
970 * @param int $exptime
971 * @return int
972 */
973 final protected function convertToRelative( $exptime ) {
974 return $this->expiryIsRelative( $exptime )
975 ? (int)$exptime
976 : max( $exptime - (int)$this->getCurrentTime(), 1 );
977 }
978
979 /**
980 * Check if a value is an integer
981 *
982 * @param mixed $value
983 * @return bool
984 */
985 final protected function isInteger( $value ) {
986 if ( is_int( $value ) ) {
987 return true;
988 } elseif ( !is_string( $value ) ) {
989 return false;
990 }
991
992 $integer = (int)$value;
993
994 return ( $value === (string)$integer );
995 }
996
997 /**
998 * Construct a cache key.
999 *
1000 * @since 1.27
1001 * @param string $keyspace
1002 * @param array $args
1003 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
1004 */
1005 public function makeKeyInternal( $keyspace, $args ) {
1006 $key = $keyspace;
1007 foreach ( $args as $arg ) {
1008 $key .= ':' . str_replace( ':', '%3A', $arg );
1009 }
1010 return strtr( $key, ' ', '_' );
1011 }
1012
1013 /**
1014 * Make a global cache key.
1015 *
1016 * @since 1.27
1017 * @param string $class Key class
1018 * @param string|null $component [optional] Key component (starting with a key collection name)
1019 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
1020 */
1021 public function makeGlobalKey( $class, $component = null ) {
1022 return $this->makeKeyInternal( 'global', func_get_args() );
1023 }
1024
1025 /**
1026 * Make a cache key, scoped to this instance's keyspace.
1027 *
1028 * @since 1.27
1029 * @param string $class Key class
1030 * @param string|null $component [optional] Key component (starting with a key collection name)
1031 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
1032 */
1033 public function makeKey( $class, $component = null ) {
1034 return $this->makeKeyInternal( $this->keyspace, func_get_args() );
1035 }
1036
1037 /**
1038 * @param int $flag ATTR_* class constant
1039 * @return int QOS_* class constant
1040 * @since 1.28
1041 */
1042 public function getQoS( $flag ) {
1043 return $this->attrMap[$flag] ?? self::QOS_UNKNOWN;
1044 }
1045
1046 /**
1047 * @return int|float The chunk size, in bytes, of segmented objects (INF for no limit)
1048 * @since 1.34
1049 */
1050 public function getSegmentationSize() {
1051 return $this->segmentationSize;
1052 }
1053
1054 /**
1055 * @return int|float Maximum total segmented object size in bytes (INF for no limit)
1056 * @since 1.34
1057 */
1058 public function getSegmentedValueMaxSize() {
1059 return $this->segmentedValueMaxSize;
1060 }
1061
1062 /**
1063 * Merge the flag maps of one or more BagOStuff objects into a "lowest common denominator" map
1064 *
1065 * @param BagOStuff[] $bags
1066 * @return int[] Resulting flag map (class ATTR_* constant => class QOS_* constant)
1067 */
1068 final protected function mergeFlagMaps( array $bags ) {
1069 $map = [];
1070 foreach ( $bags as $bag ) {
1071 foreach ( $bag->attrMap as $attr => $rank ) {
1072 if ( isset( $map[$attr] ) ) {
1073 $map[$attr] = min( $map[$attr], $rank );
1074 } else {
1075 $map[$attr] = $rank;
1076 }
1077 }
1078 }
1079
1080 return $map;
1081 }
1082
1083 /**
1084 * @internal For testing only
1085 * @return float UNIX timestamp
1086 * @codeCoverageIgnore
1087 */
1088 public function getCurrentTime() {
1089 return $this->wallClockOverride ?: microtime( true );
1090 }
1091
1092 /**
1093 * @internal For testing only
1094 * @param float|null &$time Mock UNIX timestamp
1095 * @codeCoverageIgnore
1096 */
1097 public function setMockTime( &$time ) {
1098 $this->wallClockOverride =& $time;
1099 }
1100
1101 /**
1102 * @param mixed $value
1103 * @return string|int String/integer representation
1104 * @note Special handling is usually needed for integers so incr()/decr() work
1105 */
1106 protected function serialize( $value ) {
1107 return is_int( $value ) ? $value : serialize( $value );
1108 }
1109
1110 /**
1111 * @param string|int $value
1112 * @return mixed Original value or false on error
1113 * @note Special handling is usually needed for integers so incr()/decr() work
1114 */
1115 protected function unserialize( $value ) {
1116 return $this->isInteger( $value ) ? (int)$value : unserialize( $value );
1117 }
1118 }