Merge "Make DBAccessBase use DBConnRef, rename $wiki, and hide getLoadBalancer()"
[lhc/web/wiklou.git] / includes / libs / objectcache / MediumSpecificBagOStuff.php
1 <?php
2 /**
3 * Storage medium specific cache for storing items.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Cache
22 */
23
24 use Wikimedia\WaitConditionLoop;
25
26 /**
27 * Storage medium specific cache for storing items (e.g. redis, memcached, ...)
28 *
29 * This should not be used for proxy classes that simply wrap other cache instances
30 *
31 * @ingroup Cache
32 * @since 1.34
33 */
34 abstract class MediumSpecificBagOStuff extends BagOStuff {
35 /** @var array[] Lock tracking */
36 protected $locks = [];
37 /** @var int ERR_* class constant */
38 protected $lastError = self::ERR_NONE;
39 /** @var string */
40 protected $keyspace = 'local';
41 /** @var int Seconds */
42 protected $syncTimeout;
43 /** @var int Bytes; chunk size of segmented cache values */
44 protected $segmentationSize;
45 /** @var int Bytes; maximum total size of a segmented cache value */
46 protected $segmentedValueMaxSize;
47
48 /** @var array */
49 private $duplicateKeyLookups = [];
50 /** @var bool */
51 private $reportDupes = false;
52 /** @var bool */
53 private $dupeTrackScheduled = false;
54
55 /** @var callable[] */
56 protected $busyCallbacks = [];
57
58 /** @var string Component to use for key construction of blob segment keys */
59 const SEGMENT_COMPONENT = 'segment';
60
61 /**
62 * @see BagOStuff::__construct()
63 * Additional $params options include:
64 * - logger: Psr\Log\LoggerInterface instance
65 * - keyspace: Default keyspace for $this->makeKey()
66 * - reportDupes: Whether to emit warning log messages for all keys that were
67 * requested more than once (requires an asyncHandler).
68 * - syncTimeout: How long to wait with WRITE_SYNC in seconds.
69 * - segmentationSize: The chunk size, in bytes, of segmented values. The value should
70 * not exceed the maximum size of values in the storage backend, as configured by
71 * the site administrator.
72 * - segmentedValueMaxSize: The maximum total size, in bytes, of segmented values.
73 * This should be configured to a reasonable size give the site traffic and the
74 * amount of I/O between application and cache servers that the network can handle.
75 * @param array $params
76 * @codingStandardsIgnoreStart
77 * @phan-param array{logger?:Psr\Log\LoggerInterface,asyncHandler?:callable,keyspace?:string,reportDupes?:bool,syncTimeout?:int,segmentationSize?:int,segmentedValueMaxSize?:int} $params
78 * @codingStandardsIgnoreEnd
79 */
80 public function __construct( array $params = [] ) {
81 parent::__construct( $params );
82
83 if ( isset( $params['keyspace'] ) ) {
84 $this->keyspace = $params['keyspace'];
85 }
86
87 if ( !empty( $params['reportDupes'] ) && is_callable( $this->asyncHandler ) ) {
88 $this->reportDupes = true;
89 }
90
91 $this->syncTimeout = $params['syncTimeout'] ?? 3;
92 $this->segmentationSize = $params['segmentationSize'] ?? 8388608; // 8MiB
93 $this->segmentedValueMaxSize = $params['segmentedValueMaxSize'] ?? 67108864; // 64MiB
94 }
95
96 /**
97 * Get an item with the given key
98 *
99 * If the key includes a deterministic input hash (e.g. the key can only have
100 * the correct value) or complete staleness checks are handled by the caller
101 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
102 * This lets tiered backends know they can safely upgrade a cached value to
103 * higher tiers using standard TTLs.
104 *
105 * @param string $key
106 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
107 * @return mixed Returns false on failure or if the item does not exist
108 */
109 public function get( $key, $flags = 0 ) {
110 $this->trackDuplicateKeys( $key );
111
112 return $this->resolveSegments( $key, $this->doGet( $key, $flags ) );
113 }
114
115 /**
116 * Track the number of times that a given key has been used.
117 * @param string $key
118 */
119 private function trackDuplicateKeys( $key ) {
120 if ( !$this->reportDupes ) {
121 return;
122 }
123
124 if ( !isset( $this->duplicateKeyLookups[$key] ) ) {
125 // Track that we have seen this key. This N-1 counting style allows
126 // easy filtering with array_filter() later.
127 $this->duplicateKeyLookups[$key] = 0;
128 } else {
129 $this->duplicateKeyLookups[$key] += 1;
130
131 if ( $this->dupeTrackScheduled === false ) {
132 $this->dupeTrackScheduled = true;
133 // Schedule a callback that logs keys processed more than once by get().
134 call_user_func( $this->asyncHandler, function () {
135 $dups = array_filter( $this->duplicateKeyLookups );
136 foreach ( $dups as $key => $count ) {
137 $this->logger->warning(
138 'Duplicate get(): "{key}" fetched {count} times',
139 // Count is N-1 of the actual lookup count
140 [ 'key' => $key, 'count' => $count + 1, ]
141 );
142 }
143 } );
144 }
145 }
146 }
147
148 /**
149 * @param string $key
150 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
151 * @param mixed|null &$casToken Token to use for check-and-set comparisons
152 * @return mixed Returns false on failure or if the item does not exist
153 */
154 abstract protected function doGet( $key, $flags = 0, &$casToken = null );
155
156 /**
157 * Set an item
158 *
159 * @param string $key
160 * @param mixed $value
161 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
162 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
163 * @return bool Success
164 */
165 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
166 list( $entry, $usable ) = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags );
167 // Only when all segments (if any) are stored should the main key be changed
168 return $usable ? $this->doSet( $key, $entry, $exptime, $flags ) : false;
169 }
170
171 /**
172 * Set an item
173 *
174 * @param string $key
175 * @param mixed $value
176 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
177 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
178 * @return bool Success
179 */
180 abstract protected function doSet( $key, $value, $exptime = 0, $flags = 0 );
181
182 /**
183 * Delete an item
184 *
185 * For large values written using WRITE_ALLOW_SEGMENTS, this only deletes the main
186 * segment list key unless WRITE_PRUNE_SEGMENTS is in the flags. While deleting the segment
187 * list key has the effect of functionally deleting the key, it leaves unused blobs in cache.
188 *
189 * @param string $key
190 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
191 * @return bool True if the item was deleted or not found, false on failure
192 */
193 public function delete( $key, $flags = 0 ) {
194 if ( !$this->fieldHasFlags( $flags, self::WRITE_PRUNE_SEGMENTS ) ) {
195 return $this->doDelete( $key, $flags );
196 }
197
198 $mainValue = $this->doGet( $key, self::READ_LATEST );
199 if ( !$this->doDelete( $key, $flags ) ) {
200 return false;
201 }
202
203 if ( !SerializedValueContainer::isSegmented( $mainValue ) ) {
204 return true; // no segments to delete
205 }
206
207 $orderedKeys = array_map(
208 function ( $segmentHash ) use ( $key ) {
209 return $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash );
210 },
211 $mainValue->{SerializedValueContainer::SEGMENTED_HASHES}
212 );
213
214 return $this->deleteMulti( $orderedKeys, $flags & ~self::WRITE_PRUNE_SEGMENTS );
215 }
216
217 /**
218 * Delete an item
219 *
220 * @param string $key
221 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
222 * @return bool True if the item was deleted or not found, false on failure
223 */
224 abstract protected function doDelete( $key, $flags = 0 );
225
226 public function add( $key, $value, $exptime = 0, $flags = 0 ) {
227 list( $entry, $usable ) = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags );
228 // Only when all segments (if any) are stored should the main key be changed
229 return $usable ? $this->doAdd( $key, $entry, $exptime, $flags ) : false;
230 }
231
232 /**
233 * Insert an item if it does not already exist
234 *
235 * @param string $key
236 * @param mixed $value
237 * @param int $exptime
238 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
239 * @return bool Success
240 */
241 abstract protected function doAdd( $key, $value, $exptime = 0, $flags = 0 );
242
243 /**
244 * Merge changes into the existing cache value (possibly creating a new one)
245 *
246 * The callback function returns the new value given the current value
247 * (which will be false if not present), and takes the arguments:
248 * (this BagOStuff, cache key, current value, TTL).
249 * The TTL parameter is reference set to $exptime. It can be overriden in the callback.
250 * Nothing is stored nor deleted if the callback returns false.
251 *
252 * @param string $key
253 * @param callable $callback Callback method to be executed
254 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
255 * @param int $attempts The amount of times to attempt a merge in case of failure
256 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
257 * @return bool Success
258 */
259 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
260 return $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
261 }
262
263 /**
264 * @param string $key
265 * @param callable $callback Callback method to be executed
266 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
267 * @param int $attempts The amount of times to attempt a merge in case of failure
268 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
269 * @return bool Success
270 * @see BagOStuff::merge()
271 */
272 final protected function mergeViaCas( $key, callable $callback, $exptime, $attempts, $flags ) {
273 $attemptsLeft = $attempts;
274 do {
275 $token = null; // passed by reference
276 // Get the old value and CAS token from cache
277 $this->clearLastError();
278 $currentValue = $this->resolveSegments(
279 $key,
280 $this->doGet( $key, $flags, $token )
281 );
282 if ( $this->getLastError() ) {
283 // Don't spam slow retries due to network problems (retry only on races)
284 $this->logger->warning(
285 __METHOD__ . ' failed due to read I/O error on get() for {key}.',
286 [ 'key' => $key ]
287 );
288 $success = false;
289 break;
290 }
291
292 // Derive the new value from the old value
293 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
294 $keyWasNonexistant = ( $currentValue === false );
295 $valueMatchesOldValue = ( $value === $currentValue );
296 unset( $currentValue ); // free RAM in case the value is large
297
298 $this->clearLastError();
299 if ( $value === false || $exptime < 0 ) {
300 $success = true; // do nothing
301 } elseif ( $valueMatchesOldValue && $attemptsLeft !== $attempts ) {
302 $success = true; // recently set by another thread to the same value
303 } elseif ( $keyWasNonexistant ) {
304 // Try to create the key, failing if it gets created in the meantime
305 $success = $this->add( $key, $value, $exptime, $flags );
306 } else {
307 // Try to update the key, failing if it gets changed in the meantime
308 $success = $this->cas( $token, $key, $value, $exptime, $flags );
309 }
310 if ( $this->getLastError() ) {
311 // Don't spam slow retries due to network problems (retry only on races)
312 $this->logger->warning(
313 __METHOD__ . ' failed due to write I/O error for {key}.',
314 [ 'key' => $key ]
315 );
316 $success = false;
317 break;
318 }
319
320 } while ( !$success && --$attemptsLeft );
321
322 return $success;
323 }
324
325 /**
326 * Check and set an item
327 *
328 * @param mixed $casToken
329 * @param string $key
330 * @param mixed $value
331 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
332 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
333 * @return bool Success
334 */
335 protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
336 if ( $casToken === null ) {
337 $this->logger->warning(
338 __METHOD__ . ' got empty CAS token for {key}.',
339 [ 'key' => $key ]
340 );
341
342 return false; // caller may have meant to use add()?
343 }
344
345 list( $entry, $usable ) = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags );
346 // Only when all segments (if any) are stored should the main key be changed
347 return $usable ? $this->doCas( $casToken, $key, $entry, $exptime, $flags ) : false;
348 }
349
350 /**
351 * Check and set an item
352 *
353 * @param mixed $casToken
354 * @param string $key
355 * @param mixed $value
356 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
357 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
358 * @return bool Success
359 */
360 protected function doCas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
361 // @TODO: the lock() call assumes that all other relavent sets() use one
362 if ( !$this->lock( $key, 0 ) ) {
363 return false; // non-blocking
364 }
365
366 $curCasToken = null; // passed by reference
367 $this->clearLastError();
368 $this->doGet( $key, self::READ_LATEST, $curCasToken );
369 if ( is_object( $curCasToken ) ) {
370 // Using === does not work with objects since it checks for instance identity
371 throw new UnexpectedValueException( "CAS token cannot be an object" );
372 }
373 if ( $this->getLastError() ) {
374 // Fail if the old CAS token could not be read
375 $success = false;
376 $this->logger->warning(
377 __METHOD__ . ' failed due to write I/O error for {key}.',
378 [ 'key' => $key ]
379 );
380 } elseif ( $casToken === $curCasToken ) {
381 $success = $this->doSet( $key, $value, $exptime, $flags );
382 } else {
383 $success = false; // mismatched or failed
384 $this->logger->info(
385 __METHOD__ . ' failed due to race condition for {key}.',
386 [ 'key' => $key ]
387 );
388 }
389
390 $this->unlock( $key );
391
392 return $success;
393 }
394
395 /**
396 * Change the expiration on a key if it exists
397 *
398 * If an expiry in the past is given then the key will immediately be expired
399 *
400 * For large values written using WRITE_ALLOW_SEGMENTS, this only changes the TTL of the
401 * main segment list key. While lowering the TTL of the segment list key has the effect of
402 * functionally lowering the TTL of the key, it might leave unused blobs in cache for longer.
403 * Raising the TTL of such keys is not effective, since the expiration of a single segment
404 * key effectively expires the entire value.
405 *
406 * @param string $key
407 * @param int $exptime TTL or UNIX timestamp
408 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
409 * @return bool Success Returns false on failure or if the item does not exist
410 * @since 1.28
411 */
412 public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
413 return $this->doChangeTTL( $key, $exptime, $flags );
414 }
415
416 /**
417 * @param string $key
418 * @param int $exptime
419 * @param int $flags
420 * @return bool
421 */
422 protected function doChangeTTL( $key, $exptime, $flags ) {
423 if ( !$this->lock( $key, 0 ) ) {
424 return false;
425 }
426
427 $expiry = $this->getExpirationAsTimestamp( $exptime );
428 $delete = ( $expiry != self::TTL_INDEFINITE && $expiry < $this->getCurrentTime() );
429
430 // Use doGet() to avoid having to trigger resolveSegments()
431 $blob = $this->doGet( $key, self::READ_LATEST );
432 if ( $blob ) {
433 if ( $delete ) {
434 $ok = $this->doDelete( $key, $flags );
435 } else {
436 $ok = $this->doSet( $key, $blob, $exptime, $flags );
437 }
438 } else {
439 $ok = false;
440 }
441
442 $this->unlock( $key );
443
444 return $ok;
445 }
446
447 /**
448 * Acquire an advisory lock on a key string
449 *
450 * Note that if reentry is enabled, duplicate calls ignore $expiry
451 *
452 * @param string $key
453 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
454 * @param int $expiry Lock expiry [optional]; 1 day maximum
455 * @param string $rclass Allow reentry if set and the current lock used this value
456 * @return bool Success
457 */
458 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
459 // Avoid deadlocks and allow lock reentry if specified
460 if ( isset( $this->locks[$key] ) ) {
461 if ( $rclass != '' && $this->locks[$key]['class'] === $rclass ) {
462 ++$this->locks[$key]['depth'];
463 return true;
464 } else {
465 return false;
466 }
467 }
468
469 $fname = __METHOD__;
470 $expiry = min( $expiry ?: INF, self::TTL_DAY );
471 $loop = new WaitConditionLoop(
472 function () use ( $key, $expiry, $fname ) {
473 $this->clearLastError();
474 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
475 return WaitConditionLoop::CONDITION_REACHED; // locked!
476 } elseif ( $this->getLastError() ) {
477 $this->logger->warning(
478 $fname . ' failed due to I/O error for {key}.',
479 [ 'key' => $key ]
480 );
481
482 return WaitConditionLoop::CONDITION_ABORTED; // network partition?
483 }
484
485 return WaitConditionLoop::CONDITION_CONTINUE;
486 },
487 $timeout
488 );
489
490 $code = $loop->invoke();
491 $locked = ( $code === $loop::CONDITION_REACHED );
492 if ( $locked ) {
493 $this->locks[$key] = [ 'class' => $rclass, 'depth' => 1 ];
494 } elseif ( $code === $loop::CONDITION_TIMED_OUT ) {
495 $this->logger->warning(
496 "$fname failed due to timeout for {key}.",
497 [ 'key' => $key, 'timeout' => $timeout ]
498 );
499 }
500
501 return $locked;
502 }
503
504 /**
505 * Release an advisory lock on a key string
506 *
507 * @param string $key
508 * @return bool Success
509 */
510 public function unlock( $key ) {
511 if ( !isset( $this->locks[$key] ) ) {
512 return false;
513 }
514
515 if ( --$this->locks[$key]['depth'] <= 0 ) {
516 unset( $this->locks[$key] );
517
518 $ok = $this->doDelete( "{$key}:lock" );
519 if ( !$ok ) {
520 $this->logger->warning(
521 __METHOD__ . ' failed to release lock for {key}.',
522 [ 'key' => $key ]
523 );
524 }
525
526 return $ok;
527 }
528
529 return true;
530 }
531
532 /**
533 * Delete all objects expiring before a certain date.
534 * @param string|int $timestamp The reference date in MW or TS_UNIX format
535 * @param callable|null $progress Optional, a function which will be called
536 * regularly during long-running operations with the percentage progress
537 * as the first parameter. [optional]
538 * @param int $limit Maximum number of keys to delete [default: INF]
539 *
540 * @return bool Success; false if unimplemented
541 */
542 public function deleteObjectsExpiringBefore(
543 $timestamp,
544 callable $progress = null,
545 $limit = INF
546 ) {
547 return false;
548 }
549
550 /**
551 * Get an associative array containing the item for each of the keys that have items.
552 * @param string[] $keys List of keys; can be a map of (unused => key) for convenience
553 * @param int $flags Bitfield; supports READ_LATEST [optional]
554 * @return mixed[] Map of (key => value) for existing keys; preserves the order of $keys
555 */
556 public function getMulti( array $keys, $flags = 0 ) {
557 $foundByKey = $this->doGetMulti( $keys, $flags );
558
559 $res = [];
560 foreach ( $keys as $key ) {
561 // Resolve one blob at a time (avoids too much I/O at once)
562 if ( array_key_exists( $key, $foundByKey ) ) {
563 // A value should not appear in the key if a segment is missing
564 $value = $this->resolveSegments( $key, $foundByKey[$key] );
565 if ( $value !== false ) {
566 $res[$key] = $value;
567 }
568 }
569 }
570
571 return $res;
572 }
573
574 /**
575 * Get an associative array containing the item for each of the keys that have items.
576 * @param string[] $keys List of keys
577 * @param int $flags Bitfield; supports READ_LATEST [optional]
578 * @return array Map of (key => value) for existing keys
579 */
580 protected function doGetMulti( array $keys, $flags = 0 ) {
581 $res = [];
582 foreach ( $keys as $key ) {
583 $val = $this->doGet( $key, $flags );
584 if ( $val !== false ) {
585 $res[$key] = $val;
586 }
587 }
588
589 return $res;
590 }
591
592 /**
593 * Batch insertion/replace
594 *
595 * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O
596 *
597 * @param mixed[] $data Map of (key => value)
598 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
599 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
600 * @return bool Success
601 * @since 1.24
602 */
603 public function setMulti( array $data, $exptime = 0, $flags = 0 ) {
604 if ( $this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS ) ) {
605 throw new InvalidArgumentException( __METHOD__ . ' got WRITE_ALLOW_SEGMENTS' );
606 }
607
608 return $this->doSetMulti( $data, $exptime, $flags );
609 }
610
611 /**
612 * @param mixed[] $data Map of (key => value)
613 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
614 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
615 * @return bool Success
616 */
617 protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
618 $res = true;
619 foreach ( $data as $key => $value ) {
620 $res = $this->doSet( $key, $value, $exptime, $flags ) && $res;
621 }
622
623 return $res;
624 }
625
626 /**
627 * Batch deletion
628 *
629 * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O
630 *
631 * @param string[] $keys List of keys
632 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
633 * @return bool Success
634 * @since 1.33
635 */
636 public function deleteMulti( array $keys, $flags = 0 ) {
637 if ( $this->fieldHasFlags( $flags, self::WRITE_PRUNE_SEGMENTS ) ) {
638 throw new InvalidArgumentException( __METHOD__ . ' got WRITE_PRUNE_SEGMENTS' );
639 }
640
641 return $this->doDeleteMulti( $keys, $flags );
642 }
643
644 /**
645 * @param string[] $keys List of keys
646 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
647 * @return bool Success
648 */
649 protected function doDeleteMulti( array $keys, $flags = 0 ) {
650 $res = true;
651 foreach ( $keys as $key ) {
652 $res = $this->doDelete( $key, $flags ) && $res;
653 }
654 return $res;
655 }
656
657 /**
658 * Change the expiration of multiple keys that exist
659 *
660 * @param string[] $keys List of keys
661 * @param int $exptime TTL or UNIX timestamp
662 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
663 * @return bool Success
664 * @see BagOStuff::changeTTL()
665 *
666 * @since 1.34
667 */
668 public function changeTTLMulti( array $keys, $exptime, $flags = 0 ) {
669 $res = true;
670 foreach ( $keys as $key ) {
671 $res = $this->doChangeTTL( $key, $exptime, $flags ) && $res;
672 }
673
674 return $res;
675 }
676
677 public function incrWithInit( $key, $exptime, $value = 1, $init = null, $flags = 0 ) {
678 $init = is_int( $init ) ? $init : $value;
679 $this->clearLastError();
680 $newValue = $this->incr( $key, $value, $flags );
681 if ( $newValue === false && !$this->getLastError() ) {
682 // No key set; initialize
683 $newValue = $this->add( $key, (int)$init, $exptime, $flags ) ? $init : false;
684 if ( $newValue === false && !$this->getLastError() ) {
685 // Raced out initializing; increment
686 $newValue = $this->incr( $key, $value, $flags );
687 }
688 }
689
690 return $newValue;
691 }
692
693 /**
694 * Get and reassemble the chunks of blob at the given key
695 *
696 * @param string $key
697 * @param mixed $mainValue
698 * @return string|null|bool The combined string, false if missing, null on error
699 */
700 final protected function resolveSegments( $key, $mainValue ) {
701 if ( SerializedValueContainer::isUnified( $mainValue ) ) {
702 return $this->unserialize( $mainValue->{SerializedValueContainer::UNIFIED_DATA} );
703 }
704
705 if ( SerializedValueContainer::isSegmented( $mainValue ) ) {
706 $orderedKeys = array_map(
707 function ( $segmentHash ) use ( $key ) {
708 return $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash );
709 },
710 $mainValue->{SerializedValueContainer::SEGMENTED_HASHES}
711 );
712
713 $segmentsByKey = $this->doGetMulti( $orderedKeys );
714
715 $parts = [];
716 foreach ( $orderedKeys as $segmentKey ) {
717 if ( isset( $segmentsByKey[$segmentKey] ) ) {
718 $parts[] = $segmentsByKey[$segmentKey];
719 } else {
720 return false; // missing segment
721 }
722 }
723
724 return $this->unserialize( implode( '', $parts ) );
725 }
726
727 return $mainValue;
728 }
729
730 /**
731 * Get the "last error" registered; clearLastError() should be called manually
732 * @return int ERR_* constant for the "last error" registry
733 * @since 1.23
734 */
735 public function getLastError() {
736 return $this->lastError;
737 }
738
739 /**
740 * Clear the "last error" registry
741 * @since 1.23
742 */
743 public function clearLastError() {
744 $this->lastError = self::ERR_NONE;
745 }
746
747 /**
748 * Set the "last error" registry
749 * @param int $err ERR_* constant
750 * @since 1.23
751 */
752 protected function setLastError( $err ) {
753 $this->lastError = $err;
754 }
755
756 final public function addBusyCallback( callable $workCallback ) {
757 $this->busyCallbacks[] = $workCallback;
758 }
759
760 /**
761 * Determine the entry (inline or segment list) to store under a key to save the value
762 *
763 * @param string $key
764 * @param mixed $value
765 * @param int $exptime
766 * @param int $flags
767 * @return array (inline value or segment list, whether the entry is usable)
768 * @since 1.34
769 */
770 final protected function makeValueOrSegmentList( $key, $value, $exptime, $flags ) {
771 $entry = $value;
772 $usable = true;
773
774 if (
775 $this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS ) &&
776 !is_int( $value ) && // avoid breaking incr()/decr()
777 is_finite( $this->segmentationSize )
778 ) {
779 $segmentSize = $this->segmentationSize;
780 $maxTotalSize = $this->segmentedValueMaxSize;
781
782 $serialized = $this->serialize( $value );
783 $size = strlen( $serialized );
784 if ( $size > $maxTotalSize ) {
785 $this->logger->warning(
786 "Value for {key} exceeds $maxTotalSize bytes; cannot segment.",
787 [ 'key' => $key ]
788 );
789 } elseif ( $size <= $segmentSize ) {
790 // The serialized value was already computed, so just use it inline
791 $entry = SerializedValueContainer::newUnified( $serialized );
792 } else {
793 // Split the serialized value into chunks and store them at different keys
794 $chunksByKey = [];
795 $segmentHashes = [];
796 $count = intdiv( $size, $segmentSize ) + ( ( $size % $segmentSize ) ? 1 : 0 );
797 for ( $i = 0; $i < $count; ++$i ) {
798 $segment = substr( $serialized, $i * $segmentSize, $segmentSize );
799 $hash = sha1( $segment );
800 $chunkKey = $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $hash );
801 $chunksByKey[$chunkKey] = $segment;
802 $segmentHashes[] = $hash;
803 }
804 $flags &= ~self::WRITE_ALLOW_SEGMENTS; // sanity
805 $usable = $this->setMulti( $chunksByKey, $exptime, $flags );
806 $entry = SerializedValueContainer::newSegmented( $segmentHashes );
807 }
808 }
809
810 return [ $entry, $usable ];
811 }
812
813 /**
814 * @param int|float $exptime
815 * @return bool Whether the expiry is non-infinite, and, negative or not a UNIX timestamp
816 * @since 1.34
817 */
818 final protected function isRelativeExpiration( $exptime ) {
819 return ( $exptime !== self::TTL_INDEFINITE && $exptime < ( 10 * self::TTL_YEAR ) );
820 }
821
822 /**
823 * Convert an optionally relative timestamp to an absolute time
824 *
825 * The input value will be cast to an integer and interpreted as follows:
826 * - zero: no expiry; return zero (e.g. TTL_INDEFINITE)
827 * - negative: relative TTL; return UNIX timestamp offset by this value
828 * - positive (< 10 years): relative TTL; return UNIX timestamp offset by this value
829 * - positive (>= 10 years): absolute UNIX timestamp; return this value
830 *
831 * @param int $exptime
832 * @return int Expiration timestamp or TTL_INDEFINITE for indefinite
833 * @since 1.34
834 */
835 final protected function getExpirationAsTimestamp( $exptime ) {
836 if ( $exptime == self::TTL_INDEFINITE ) {
837 return $exptime;
838 }
839
840 return $this->isRelativeExpiration( $exptime )
841 ? intval( $this->getCurrentTime() + $exptime )
842 : $exptime;
843 }
844
845 /**
846 * Convert an optionally absolute expiry time to a relative time. If an
847 * absolute time is specified which is in the past, use a short expiry time.
848 *
849 * The input value will be cast to an integer and interpreted as follows:
850 * - zero: no expiry; return zero (e.g. TTL_INDEFINITE)
851 * - negative: relative TTL; return a short expiry time (1 second)
852 * - positive (< 10 years): relative TTL; return this value
853 * - positive (>= 10 years): absolute UNIX timestamp; return offset to current time
854 *
855 * @param int $exptime
856 * @return int Relative TTL or TTL_INDEFINITE for indefinite
857 * @since 1.34
858 */
859 final protected function getExpirationAsTTL( $exptime ) {
860 if ( $exptime == self::TTL_INDEFINITE ) {
861 return $exptime;
862 }
863
864 return $this->isRelativeExpiration( $exptime )
865 ? $exptime
866 : (int)max( $exptime - $this->getCurrentTime(), 1 );
867 }
868
869 /**
870 * Check if a value is an integer
871 *
872 * @param mixed $value
873 * @return bool
874 */
875 final protected function isInteger( $value ) {
876 if ( is_int( $value ) ) {
877 return true;
878 } elseif ( !is_string( $value ) ) {
879 return false;
880 }
881
882 $integer = (int)$value;
883
884 return ( $value === (string)$integer );
885 }
886
887 public function makeKeyInternal( $keyspace, $args ) {
888 $key = $keyspace;
889 foreach ( $args as $arg ) {
890 $key .= ':' . str_replace( ':', '%3A', $arg );
891 }
892 return strtr( $key, ' ', '_' );
893 }
894
895 /**
896 * Make a global cache key.
897 *
898 * @param string $class Key class
899 * @param string ...$components Key components (starting with a key collection name)
900 * @return string Colon-delimited list of $keyspace followed by escaped components
901 * @since 1.27
902 */
903 public function makeGlobalKey( $class, ...$components ) {
904 return $this->makeKeyInternal( 'global', func_get_args() );
905 }
906
907 /**
908 * Make a cache key, scoped to this instance's keyspace.
909 *
910 * @param string $class Key class
911 * @param string ...$components Key components (starting with a key collection name)
912 * @return string Colon-delimited list of $keyspace followed by escaped components
913 * @since 1.27
914 */
915 public function makeKey( $class, ...$components ) {
916 return $this->makeKeyInternal( $this->keyspace, func_get_args() );
917 }
918
919 /**
920 * @param int $flag ATTR_* class constant
921 * @return int QOS_* class constant
922 * @since 1.28
923 */
924 public function getQoS( $flag ) {
925 return $this->attrMap[$flag] ?? self::QOS_UNKNOWN;
926 }
927
928 public function getSegmentationSize() {
929 return $this->segmentationSize;
930 }
931
932 public function getSegmentedValueMaxSize() {
933 return $this->segmentedValueMaxSize;
934 }
935
936 /**
937 * @param mixed $value
938 * @return string|int String/integer representation
939 * @note Special handling is usually needed for integers so incr()/decr() work
940 */
941 protected function serialize( $value ) {
942 return is_int( $value ) ? $value : serialize( $value );
943 }
944
945 /**
946 * @param string|int $value
947 * @return mixed Original value or false on error
948 * @note Special handling is usually needed for integers so incr()/decr() work
949 */
950 protected function unserialize( $value ) {
951 return $this->isInteger( $value ) ? (int)$value : unserialize( $value );
952 }
953
954 /**
955 * @param string $text
956 */
957 protected function debug( $text ) {
958 if ( $this->debugMode ) {
959 $this->logger->debug( "{class} debug: $text", [ 'class' => static::class ] );
960 }
961 }
962 }