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