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