Exclude redirects from Special:Fewestrevisions
[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 $date The reference date in MW format
656 * @param callable|bool $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( $date, $progressCallback = false, $limit = INF ) {
664 // stub
665 return false;
666 }
667
668 /**
669 * Get an associative array containing the item for each of the keys that have items.
670 * @param string[] $keys List of keys
671 * @param int $flags Bitfield; supports READ_LATEST [optional]
672 * @return array
673 */
674 public function getMulti( array $keys, $flags = 0 ) {
675 $valuesBykey = $this->doGetMulti( $keys, $flags );
676 foreach ( $valuesBykey as $key => $value ) {
677 // Resolve one blob at a time (avoids too much I/O at once)
678 $valuesBykey[$key] = $this->resolveSegments( $key, $value );
679 }
680
681 return $valuesBykey;
682 }
683
684 /**
685 * Get an associative array containing the item for each of the keys that have items.
686 * @param string[] $keys List of keys
687 * @param int $flags Bitfield; supports READ_LATEST [optional]
688 * @return array
689 */
690 protected function doGetMulti( array $keys, $flags = 0 ) {
691 $res = [];
692 foreach ( $keys as $key ) {
693 $val = $this->doGet( $key, $flags );
694 if ( $val !== false ) {
695 $res[$key] = $val;
696 }
697 }
698
699 return $res;
700 }
701
702 /**
703 * Batch insertion/replace
704 *
705 * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O
706 *
707 * @param mixed[] $data Map of (key => value)
708 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
709 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
710 * @return bool Success
711 * @since 1.24
712 */
713 public function setMulti( array $data, $exptime = 0, $flags = 0 ) {
714 if ( ( $flags & self::WRITE_ALLOW_SEGMENTS ) === self::WRITE_ALLOW_SEGMENTS ) {
715 throw new InvalidArgumentException( __METHOD__ . ' got WRITE_ALLOW_SEGMENTS' );
716 }
717
718 $res = true;
719 foreach ( $data as $key => $value ) {
720 $res = $this->doSet( $key, $value, $exptime, $flags ) && $res;
721 }
722
723 return $res;
724 }
725
726 /**
727 * Batch deletion
728 *
729 * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O
730 *
731 * @param string[] $keys List of keys
732 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
733 * @return bool Success
734 * @since 1.33
735 */
736 public function deleteMulti( array $keys, $flags = 0 ) {
737 $res = true;
738 foreach ( $keys as $key ) {
739 $res = $this->doDelete( $key, $flags ) && $res;
740 }
741
742 return $res;
743 }
744
745 /**
746 * Increase stored value of $key by $value while preserving its TTL
747 * @param string $key Key to increase
748 * @param int $value Value to add to $key (default: 1) [optional]
749 * @return int|bool New value or false on failure
750 */
751 abstract public function incr( $key, $value = 1 );
752
753 /**
754 * Decrease stored value of $key by $value while preserving its TTL
755 * @param string $key
756 * @param int $value Value to subtract from $key (default: 1) [optional]
757 * @return int|bool New value or false on failure
758 */
759 public function decr( $key, $value = 1 ) {
760 return $this->incr( $key, - $value );
761 }
762
763 /**
764 * Increase stored value of $key by $value while preserving its TTL
765 *
766 * This will create the key with value $init and TTL $ttl instead if not present
767 *
768 * @param string $key
769 * @param int $ttl
770 * @param int $value
771 * @param int $init
772 * @return int|bool New value or false on failure
773 * @since 1.24
774 */
775 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
776 $this->clearLastError();
777 $newValue = $this->incr( $key, $value );
778 if ( $newValue === false && !$this->getLastError() ) {
779 // No key set; initialize
780 $newValue = $this->add( $key, (int)$init, $ttl ) ? $init : false;
781 if ( $newValue === false && !$this->getLastError() ) {
782 // Raced out initializing; increment
783 $newValue = $this->incr( $key, $value );
784 }
785 }
786
787 return $newValue;
788 }
789
790 /**
791 * Get and reassemble the chunks of blob at the given key
792 *
793 * @param string $key
794 * @param mixed $mainValue
795 * @return string|null|bool The combined string, false if missing, null on error
796 */
797 protected function resolveSegments( $key, $mainValue ) {
798 if ( SerializedValueContainer::isUnified( $mainValue ) ) {
799 return $this->unserialize( $mainValue->{SerializedValueContainer::UNIFIED_DATA} );
800 }
801
802 if ( SerializedValueContainer::isSegmented( $mainValue ) ) {
803 $orderedKeys = array_map(
804 function ( $segmentHash ) use ( $key ) {
805 return $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash );
806 },
807 $mainValue->{SerializedValueContainer::SEGMENTED_HASHES}
808 );
809
810 $segmentsByKey = $this->doGetMulti( $orderedKeys );
811
812 $parts = [];
813 foreach ( $orderedKeys as $segmentKey ) {
814 if ( isset( $segmentsByKey[$segmentKey] ) ) {
815 $parts[] = $segmentsByKey[$segmentKey];
816 } else {
817 return false; // missing segment
818 }
819 }
820
821 return $this->unserialize( implode( '', $parts ) );
822 }
823
824 return $mainValue;
825 }
826
827 /**
828 * Get the "last error" registered; clearLastError() should be called manually
829 * @return int ERR_* constant for the "last error" registry
830 * @since 1.23
831 */
832 public function getLastError() {
833 return $this->lastError;
834 }
835
836 /**
837 * Clear the "last error" registry
838 * @since 1.23
839 */
840 public function clearLastError() {
841 $this->lastError = self::ERR_NONE;
842 }
843
844 /**
845 * Set the "last error" registry
846 * @param int $err ERR_* constant
847 * @since 1.23
848 */
849 protected function setLastError( $err ) {
850 $this->lastError = $err;
851 }
852
853 /**
854 * Let a callback be run to avoid wasting time on special blocking calls
855 *
856 * The callbacks may or may not be called ever, in any particular order.
857 * They are likely to be invoked when something WRITE_SYNC is used used.
858 * They should follow a caching pattern as shown below, so that any code
859 * using the work will get it's result no matter what happens.
860 * @code
861 * $result = null;
862 * $workCallback = function () use ( &$result ) {
863 * if ( !$result ) {
864 * $result = ....
865 * }
866 * return $result;
867 * }
868 * @endcode
869 *
870 * @param callable $workCallback
871 * @since 1.28
872 */
873 public function addBusyCallback( callable $workCallback ) {
874 $this->busyCallbacks[] = $workCallback;
875 }
876
877 /**
878 * @param string $text
879 */
880 protected function debug( $text ) {
881 if ( $this->debugMode ) {
882 $this->logger->debug( "{class} debug: $text", [
883 'class' => static::class,
884 ] );
885 }
886 }
887
888 /**
889 * @param int $exptime
890 * @return bool
891 */
892 protected function expiryIsRelative( $exptime ) {
893 return ( $exptime != 0 && $exptime < ( 10 * self::TTL_YEAR ) );
894 }
895
896 /**
897 * Convert an optionally relative time to an absolute time
898 * @param int $exptime
899 * @return int
900 */
901 protected function convertToExpiry( $exptime ) {
902 if ( $this->expiryIsRelative( $exptime ) ) {
903 return (int)$this->getCurrentTime() + $exptime;
904 } else {
905 return $exptime;
906 }
907 }
908
909 /**
910 * Convert an optionally absolute expiry time to a relative time. If an
911 * absolute time is specified which is in the past, use a short expiry time.
912 *
913 * @param int $exptime
914 * @return int
915 */
916 protected function convertToRelative( $exptime ) {
917 if ( $exptime >= ( 10 * self::TTL_YEAR ) ) {
918 $exptime -= (int)$this->getCurrentTime();
919 if ( $exptime <= 0 ) {
920 $exptime = 1;
921 }
922 return $exptime;
923 } else {
924 return $exptime;
925 }
926 }
927
928 /**
929 * Check if a value is an integer
930 *
931 * @param mixed $value
932 * @return bool
933 */
934 protected function isInteger( $value ) {
935 if ( is_int( $value ) ) {
936 return true;
937 } elseif ( !is_string( $value ) ) {
938 return false;
939 }
940
941 $integer = (int)$value;
942
943 return ( $value === (string)$integer );
944 }
945
946 /**
947 * Construct a cache key.
948 *
949 * @since 1.27
950 * @param string $keyspace
951 * @param array $args
952 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
953 */
954 public function makeKeyInternal( $keyspace, $args ) {
955 $key = $keyspace;
956 foreach ( $args as $arg ) {
957 $key .= ':' . str_replace( ':', '%3A', $arg );
958 }
959 return strtr( $key, ' ', '_' );
960 }
961
962 /**
963 * Make a global cache key.
964 *
965 * @since 1.27
966 * @param string $class Key class
967 * @param string|null $component [optional] Key component (starting with a key collection name)
968 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
969 */
970 public function makeGlobalKey( $class, $component = null ) {
971 return $this->makeKeyInternal( 'global', func_get_args() );
972 }
973
974 /**
975 * Make a cache key, scoped to this instance's keyspace.
976 *
977 * @since 1.27
978 * @param string $class Key class
979 * @param string|null $component [optional] Key component (starting with a key collection name)
980 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
981 */
982 public function makeKey( $class, $component = null ) {
983 return $this->makeKeyInternal( $this->keyspace, func_get_args() );
984 }
985
986 /**
987 * @param int $flag ATTR_* class constant
988 * @return int QOS_* class constant
989 * @since 1.28
990 */
991 public function getQoS( $flag ) {
992 return $this->attrMap[$flag] ?? self::QOS_UNKNOWN;
993 }
994
995 /**
996 * @return int|float The chunk size, in bytes, of segmented objects (INF for no limit)
997 * @since 1.34
998 */
999 public function getSegmentationSize() {
1000 return $this->segmentationSize;
1001 }
1002
1003 /**
1004 * @return int|float Maximum total segmented object size in bytes (INF for no limit)
1005 * @since 1.34
1006 */
1007 public function getSegmentedValueMaxSize() {
1008 return $this->segmentedValueMaxSize;
1009 }
1010
1011 /**
1012 * Merge the flag maps of one or more BagOStuff objects into a "lowest common denominator" map
1013 *
1014 * @param BagOStuff[] $bags
1015 * @return int[] Resulting flag map (class ATTR_* constant => class QOS_* constant)
1016 */
1017 protected function mergeFlagMaps( array $bags ) {
1018 $map = [];
1019 foreach ( $bags as $bag ) {
1020 foreach ( $bag->attrMap as $attr => $rank ) {
1021 if ( isset( $map[$attr] ) ) {
1022 $map[$attr] = min( $map[$attr], $rank );
1023 } else {
1024 $map[$attr] = $rank;
1025 }
1026 }
1027 }
1028
1029 return $map;
1030 }
1031
1032 /**
1033 * @internal For testing only
1034 * @return float UNIX timestamp
1035 * @codeCoverageIgnore
1036 */
1037 public function getCurrentTime() {
1038 return $this->wallClockOverride ?: microtime( true );
1039 }
1040
1041 /**
1042 * @internal For testing only
1043 * @param float|null &$time Mock UNIX timestamp
1044 * @codeCoverageIgnore
1045 */
1046 public function setMockTime( &$time ) {
1047 $this->wallClockOverride =& $time;
1048 }
1049
1050 /**
1051 * @param mixed $value
1052 * @return string|int String/integer representation
1053 * @note Special handling is usually needed for integers so incr()/decr() work
1054 */
1055 protected function serialize( $value ) {
1056 return is_int( $value ) ? $value : serialize( $value );
1057 }
1058
1059 /**
1060 * @param string|int $value
1061 * @return mixed Original value or false on error
1062 * @note Special handling is usually needed for integers so incr()/decr() work
1063 */
1064 protected function unserialize( $value ) {
1065 return $this->isInteger( $value ) ? (int)$value : unserialize( $value );
1066 }
1067 }