MediaWiki REL1_39
MediumSpecificBagOStuff.php
Go to the documentation of this file.
1<?php
24use Wikimedia\WaitConditionLoop;
25
34abstract class MediumSpecificBagOStuff extends BagOStuff {
36 protected $locks = [];
41
43 private $duplicateKeyLookups = [];
45 private $reportDupes = false;
47 private $dupeTrackScheduled = false;
48
50 protected $preparedValues = [];
51
53 private const SEGMENT_COMPONENT = 'segment';
54
56 protected const PASS_BY_REF = -1;
57
58 protected const METRIC_OP_GET = 'get';
59 protected const METRIC_OP_SET = 'set';
60 protected const METRIC_OP_DELETE = 'delete';
61 protected const METRIC_OP_CHANGE_TTL = 'change_ttl';
62 protected const METRIC_OP_ADD = 'add';
63 protected const METRIC_OP_INCR = 'incr';
64 protected const METRIC_OP_DECR = 'decr';
65 protected const METRIC_OP_CAS = 'cas';
66
67 protected const LOCK_RCLASS = 0;
68 protected const LOCK_DEPTH = 1;
69 protected const LOCK_TIME = 2;
70 protected const LOCK_EXPIRY = 3;
71
88 public function __construct( array $params = [] ) {
89 parent::__construct( $params );
90
91 if ( !empty( $params['reportDupes'] ) && $this->asyncHandler ) {
92 $this->reportDupes = true;
93 }
94
95 // Default to 8MiB if segmentationSize is not set
96 $this->segmentationSize = $params['segmentationSize'] ?? 8388608;
97 // Default to 64MiB if segmentedValueMaxSize is not set
98 $this->segmentedValueMaxSize = $params['segmentedValueMaxSize'] ?? 67108864;
99 }
100
114 public function get( $key, $flags = 0 ) {
115 $this->trackDuplicateKeys( $key );
116
117 return $this->resolveSegments( $key, $this->doGet( $key, $flags ) );
118 }
119
124 private function trackDuplicateKeys( $key ) {
125 if ( !$this->reportDupes ) {
126 return;
127 }
128
129 if ( !isset( $this->duplicateKeyLookups[$key] ) ) {
130 // Track that we have seen this key. This N-1 counting style allows
131 // easy filtering with array_filter() later.
132 $this->duplicateKeyLookups[$key] = 0;
133 } else {
134 $this->duplicateKeyLookups[$key] += 1;
135
136 if ( $this->dupeTrackScheduled === false ) {
137 $this->dupeTrackScheduled = true;
138 // Schedule a callback that logs keys processed more than once by get().
139 call_user_func( $this->asyncHandler, function () {
140 $dups = array_filter( $this->duplicateKeyLookups );
141 foreach ( $dups as $key => $count ) {
142 $this->logger->warning(
143 'Duplicate get(): "{key}" fetched {count} times',
144 // Count is N-1 of the actual lookup count
145 [ 'key' => $key, 'count' => $count + 1, ]
146 );
147 }
148 } );
149 }
150 }
151 }
152
163 abstract protected function doGet( $key, $flags = 0, &$casToken = null );
164
174 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
175 $entry = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags, $ok );
176 // Only when all segments (if any) are stored should the main key be changed
177 return $ok ? $this->doSet( $key, $entry, $exptime, $flags ) : false;
178 }
179
189 abstract protected function doSet( $key, $value, $exptime = 0, $flags = 0 );
190
202 public function delete( $key, $flags = 0 ) {
203 if ( !$this->fieldHasFlags( $flags, self::WRITE_PRUNE_SEGMENTS ) ) {
204 return $this->doDelete( $key, $flags );
205 }
206
207 $mainValue = $this->doGet( $key, self::READ_LATEST );
208 if ( !$this->doDelete( $key, $flags ) ) {
209 return false;
210 }
211
212 if ( !SerializedValueContainer::isSegmented( $mainValue ) ) {
213 // no segments to delete
214 return true;
215 }
216
217 $orderedKeys = array_map(
218 function ( $segmentHash ) use ( $key ) {
219 return $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash );
220 },
222 );
223
224 return $this->deleteMulti( $orderedKeys, $flags & ~self::WRITE_PRUNE_SEGMENTS );
225 }
226
234 abstract protected function doDelete( $key, $flags = 0 );
235
236 public function add( $key, $value, $exptime = 0, $flags = 0 ) {
237 $entry = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags, $ok );
238 // Only when all segments (if any) are stored should the main key be changed
239 return $ok ? $this->doAdd( $key, $entry, $exptime, $flags ) : false;
240 }
241
251 abstract protected function doAdd( $key, $value, $exptime = 0, $flags = 0 );
252
269 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
270 return $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
271 }
272
282 final protected function mergeViaCas( $key, callable $callback, $exptime, $attempts, $flags ) {
283 $attemptsLeft = $attempts;
284 do {
285 $token = self::PASS_BY_REF;
286 // Get the old value and CAS token from cache
287 $watchPoint = $this->watchErrors();
288 $currentValue = $this->resolveSegments(
289 $key,
290 $this->doGet( $key, $flags, $token )
291 );
292 if ( $this->getLastError( $watchPoint ) ) {
293 // Don't spam slow retries due to network problems (retry only on races)
294 $this->logger->warning(
295 __METHOD__ . ' failed due to read I/O error on get() for {key}.',
296 [ 'key' => $key ]
297 );
298 $success = false;
299 break;
300 }
301
302 // Derive the new value from the old value
303 $value = $callback( $this, $key, $currentValue, $exptime );
304 $keyWasNonexistant = ( $currentValue === false );
305 $valueMatchesOldValue = ( $value === $currentValue );
306 // free RAM in case the value is large
307 unset( $currentValue );
308
309 $watchPoint = $this->watchErrors();
310 if ( $value === false || $exptime < 0 ) {
311 // do nothing
312 $success = true;
313 } elseif ( $valueMatchesOldValue && $attemptsLeft !== $attempts ) {
314 // recently set by another thread to the same value
315 $success = true;
316 } elseif ( $keyWasNonexistant ) {
317 // Try to create the key, failing if it gets created in the meantime
318 $success = $this->add( $key, $value, $exptime, $flags );
319 } else {
320 // Try to update the key, failing if it gets changed in the meantime
321 $success = $this->cas( $token, $key, $value, $exptime, $flags );
322 }
323 if ( $this->getLastError( $watchPoint ) ) {
324 // Don't spam slow retries due to network problems (retry only on races)
325 $this->logger->warning(
326 __METHOD__ . ' failed due to write I/O error for {key}.',
327 [ 'key' => $key ]
328 );
329 $success = false;
330 break;
331 }
332
333 } while ( !$success && --$attemptsLeft );
334
335 return $success;
336 }
337
348 protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
349 if ( $casToken === null ) {
350 $this->logger->warning(
351 __METHOD__ . ' got empty CAS token for {key}.',
352 [ 'key' => $key ]
353 );
354
355 // caller may have meant to use add()?
356 return false;
357 }
358
359 $entry = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags, $ok );
360 // Only when all segments (if any) are stored should the main key be changed
361 return $ok ? $this->doCas( $casToken, $key, $entry, $exptime, $flags ) : false;
362 }
363
374 protected function doCas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
375 // @TODO: the use of lock() assumes that all other relevant sets() use a lock
376 if ( !$this->lock( $key, 0 ) ) {
377 // non-blocking
378 return false;
379 }
380
381 $curCasToken = self::PASS_BY_REF;
382 $watchPoint = $this->watchErrors();
383 $exists = ( $this->doGet( $key, self::READ_LATEST, $curCasToken ) !== false );
384 if ( $this->getLastError( $watchPoint ) ) {
385 // Fail if the old CAS token could not be read
386 $success = false;
387 $this->logger->warning(
388 __METHOD__ . ' failed due to write I/O error for {key}.',
389 [ 'key' => $key ]
390 );
391 } elseif ( $exists && $this->tokensMatch( $casToken, $curCasToken ) ) {
392 $success = $this->doSet( $key, $value, $exptime, $flags );
393 } else {
394 // mismatched or failed
395 $success = false;
396 $this->logger->info(
397 __METHOD__ . ' failed due to race condition for {key}.',
398 [ 'key' => $key, 'key_exists' => $exists ]
399 );
400 }
401
402 $this->unlock( $key );
403
404 return $success;
405 }
406
412 final protected function tokensMatch( $value, $otherValue ) {
413 $type = gettype( $value );
414 // Ideally, tokens are counters, timestamps, hashes, or serialized PHP values.
415 // However, some classes might use the PHP values themselves.
416 if ( $type !== gettype( $otherValue ) ) {
417 return false;
418 }
419 // Serialize both tokens to strictly compare objects or arrays (which might objects
420 // nested inside). Note that this will not apply if integer/string CAS tokens are used.
421 if ( $type === 'array' || $type === 'object' ) {
422 return ( serialize( $value ) === serialize( $otherValue ) );
423 }
424 // For string/integer tokens, use a simple comparison
425 return ( $value === $otherValue );
426 }
427
445 public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
446 return $this->doChangeTTL( $key, $exptime, $flags );
447 }
448
455 protected function doChangeTTL( $key, $exptime, $flags ) {
456 // @TODO: the use of lock() assumes that all other relevant sets() use a lock
457 if ( !$this->lock( $key, 0 ) ) {
458 return false;
459 }
460
461 $expiry = $this->getExpirationAsTimestamp( $exptime );
462 $delete = ( $expiry != self::TTL_INDEFINITE && $expiry < $this->getCurrentTime() );
463
464 // Use doGet() to avoid having to trigger resolveSegments()
465 $blob = $this->doGet( $key, self::READ_LATEST );
466 if ( $blob ) {
467 if ( $delete ) {
468 $ok = $this->doDelete( $key, $flags );
469 } else {
470 $ok = $this->doSet( $key, $blob, $exptime, $flags );
471 }
472 } else {
473 $ok = false;
474 }
475
476 $this->unlock( $key );
477
478 return $ok;
479 }
480
481 public function incrWithInit( $key, $exptime, $step = 1, $init = null, $flags = 0 ) {
482 $step = (int)$step;
483 $init = is_int( $init ) ? $init : $step;
484
485 return $this->doIncrWithInit( $key, $exptime, $step, $init, $flags );
486 }
487
496 abstract protected function doIncrWithInit( $key, $exptime, $step, $init, $flags );
497
505 public function lock( $key, $timeout = 6, $exptime = 6, $rclass = '' ) {
506 $exptime = min( $exptime ?: INF, self::TTL_DAY );
507
508 $acquired = false;
509
510 if ( isset( $this->locks[$key] ) ) {
511 // Already locked; avoid deadlocks and allow lock reentry if specified
512 if ( $rclass != '' && $this->locks[$key][self::LOCK_RCLASS] === $rclass ) {
513 ++$this->locks[$key][self::LOCK_DEPTH];
514 $acquired = true;
515 }
516 } else {
517 // Not already locked; acquire a lock on the backend
518 $lockTsUnix = $this->doLock( $key, $timeout, $exptime );
519 if ( $lockTsUnix !== null ) {
520 $this->locks[$key] = [
521 self::LOCK_RCLASS => $rclass,
522 self::LOCK_DEPTH => 1,
523 self::LOCK_TIME => $lockTsUnix,
524 self::LOCK_EXPIRY => $lockTsUnix + $exptime
525 ];
526 $acquired = true;
527 }
528 }
529
530 return $acquired;
531 }
532
541 protected function doLock( $key, $timeout, $exptime ) {
542 $lockTsUnix = null;
543
544 $fname = __METHOD__;
545 $loop = new WaitConditionLoop(
546 function () use ( $key, $exptime, $fname, &$lockTsUnix ) {
547 $watchPoint = $this->watchErrors();
548 if ( $this->add( $this->makeLockKey( $key ), 1, $exptime ) ) {
549 $lockTsUnix = microtime( true );
550
551 // locked!
552 return WaitConditionLoop::CONDITION_REACHED;
553 } elseif ( $this->getLastError( $watchPoint ) ) {
554 $this->logger->warning(
555 "$fname failed due to I/O error for {key}.",
556 [ 'key' => $key ]
557 );
558
559 // network partition?
560 return WaitConditionLoop::CONDITION_ABORTED;
561 }
562
563 return WaitConditionLoop::CONDITION_CONTINUE;
564 },
565 $timeout
566 );
567 $code = $loop->invoke();
568
569 if ( $code === $loop::CONDITION_TIMED_OUT ) {
570 $this->logger->warning(
571 "$fname failed due to timeout for {key}.",
572 [ 'key' => $key, 'timeout' => $timeout ]
573 );
574 }
575
576 return $lockTsUnix;
577 }
578
585 public function unlock( $key ) {
586 $released = false;
587
588 if ( isset( $this->locks[$key] ) ) {
589 if ( --$this->locks[$key][self::LOCK_DEPTH] > 0 ) {
590 $released = true;
591 } else {
592 $released = $this->doUnlock( $key );
593 unset( $this->locks[$key] );
594 if ( !$released ) {
595 $this->logger->warning(
596 __METHOD__ . ' failed to release lock for {key}.',
597 [ 'key' => $key ]
598 );
599 }
600 }
601 } else {
602 $this->logger->warning(
603 __METHOD__ . ' no lock to release for {key}.',
604 [ 'key' => $key ]
605 );
606 }
607
608 return $released;
609 }
610
617 protected function doUnlock( $key ) {
618 // Estimate the remaining TTL of the lock key
619 $curTTL = $this->locks[$key][self::LOCK_EXPIRY] - $this->getCurrentTime();
620 // Maximum expected one-way-delay for a query to reach the backend
621 $maxOWD = 0.050;
622
623 $released = false;
624
625 if ( ( $curTTL - $maxOWD ) > 0 ) {
626 // The lock key is extremely unlikely to expire before a deletion operation
627 // sent from this method arrives on the relevant backend server
628 $released = $this->doDelete( $this->makeLockKey( $key ) );
629 } else {
630 // It is unsafe for this method to delete the lock key due to the risk of it
631 // expiring and being claimed by another thread before the deletion operation
632 // arrives on the backend server
633 $this->logger->warning(
634 "Lock for {key} held too long ({age} sec).",
635 [ 'key' => $key, 'curTTL' => $curTTL ]
636 );
637 }
638
639 return $released;
640 }
641
646 protected function makeLockKey( $key ) {
647 return "$key:lock";
648 }
649
651 $timestamp,
652 callable $progress = null,
653 $limit = INF,
654 string $tag = null
655 ) {
656 return false;
657 }
658
665 public function getMulti( array $keys, $flags = 0 ) {
666 $foundByKey = $this->doGetMulti( $keys, $flags );
667
668 $res = [];
669 foreach ( $keys as $key ) {
670 // Resolve one blob at a time (avoids too much I/O at once)
671 if ( array_key_exists( $key, $foundByKey ) ) {
672 // A value should not appear in the key if a segment is missing
673 $value = $this->resolveSegments( $key, $foundByKey[$key] );
674 if ( $value !== false ) {
675 $res[$key] = $value;
676 }
677 }
678 }
679
680 return $res;
681 }
682
689 protected function doGetMulti( array $keys, $flags = 0 ) {
690 $res = [];
691 foreach ( $keys as $key ) {
692 $val = $this->doGet( $key, $flags );
693 if ( $val !== false ) {
694 $res[$key] = $val;
695 }
696 }
697
698 return $res;
699 }
700
712 public function setMulti( array $valueByKey, $exptime = 0, $flags = 0 ) {
713 if ( $this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS ) ) {
714 throw new InvalidArgumentException( __METHOD__ . ' got WRITE_ALLOW_SEGMENTS' );
715 }
716
717 return $this->doSetMulti( $valueByKey, $exptime, $flags );
718 }
719
726 protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
727 $res = true;
728 foreach ( $data as $key => $value ) {
729 $res = $this->doSet( $key, $value, $exptime, $flags ) && $res;
730 }
731
732 return $res;
733 }
734
745 public function deleteMulti( array $keys, $flags = 0 ) {
746 if ( $this->fieldHasFlags( $flags, self::WRITE_PRUNE_SEGMENTS ) ) {
747 throw new InvalidArgumentException( __METHOD__ . ' got WRITE_PRUNE_SEGMENTS' );
748 }
749
750 return $this->doDeleteMulti( $keys, $flags );
751 }
752
758 protected function doDeleteMulti( array $keys, $flags = 0 ) {
759 $res = true;
760 foreach ( $keys as $key ) {
761 $res = $this->doDelete( $key, $flags ) && $res;
762 }
763 return $res;
764 }
765
776 public function changeTTLMulti( array $keys, $exptime, $flags = 0 ) {
777 return $this->doChangeTTLMulti( $keys, $exptime, $flags );
778 }
779
786 protected function doChangeTTLMulti( array $keys, $exptime, $flags = 0 ) {
787 $res = true;
788 foreach ( $keys as $key ) {
789 $res = $this->doChangeTTL( $key, $exptime, $flags ) && $res;
790 }
791
792 return $res;
793 }
794
802 final protected function resolveSegments( $key, $mainValue ) {
803 if ( SerializedValueContainer::isUnified( $mainValue ) ) {
804 return $this->unserialize( $mainValue->{SerializedValueContainer::UNIFIED_DATA} );
805 }
806
807 if ( SerializedValueContainer::isSegmented( $mainValue ) ) {
808 $orderedKeys = array_map(
809 function ( $segmentHash ) use ( $key ) {
810 return $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash );
811 },
813 );
814
815 $segmentsByKey = $this->doGetMulti( $orderedKeys );
816
817 $parts = [];
818 foreach ( $orderedKeys as $segmentKey ) {
819 if ( isset( $segmentsByKey[$segmentKey] ) ) {
820 $parts[] = $segmentsByKey[$segmentKey];
821 } else {
822 // missing segment
823 return false;
824 }
825 }
826
827 return $this->unserialize( implode( '', $parts ) );
828 }
829
830 return $mainValue;
831 }
832
833 final public function addBusyCallback( callable $workCallback ) {
834 wfDeprecated( __METHOD__, '1.39' );
835 }
836
849 private function useSegmentationWrapper( $value, $flags ) {
850 if (
851 $this->segmentationSize === INF ||
852 !$this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS )
853 ) {
854 return false;
855 }
856
857 if ( is_string( $value ) ) {
858 return ( strlen( $value ) >= $this->segmentationSize );
859 }
860
861 if ( is_array( $value ) ) {
862 // Expect that the contained value will be one of the first array entries
863 foreach ( array_slice( $value, 0, 4 ) as $v ) {
864 if ( is_string( $v ) && strlen( $v ) >= $this->segmentationSize ) {
865 return true;
866 }
867 }
868 }
869
870 // Avoid breaking functions for incrementing/decrementing integer key values
871 return false;
872 }
873
885 final protected function makeValueOrSegmentList( $key, $value, $exptime, $flags, &$ok ) {
886 $entry = $value;
887 $ok = true;
888
889 if ( $this->useSegmentationWrapper( $value, $flags ) ) {
890 $segmentSize = $this->segmentationSize;
891 $maxTotalSize = $this->segmentedValueMaxSize;
892 $serialized = $this->getSerialized( $value, $key );
893 $size = strlen( $serialized );
894 if ( $size > $maxTotalSize ) {
895 $this->logger->warning(
896 "Value for {key} exceeds $maxTotalSize bytes; cannot segment.",
897 [ 'key' => $key ]
898 );
899 } else {
900 // Split the serialized value into chunks and store them at different keys
901 $chunksByKey = [];
902 $segmentHashes = [];
903 $count = intdiv( $size, $segmentSize ) + ( ( $size % $segmentSize ) ? 1 : 0 );
904 for ( $i = 0; $i < $count; ++$i ) {
905 $segment = substr( $serialized, $i * $segmentSize, $segmentSize );
906 $hash = sha1( $segment );
907 $chunkKey = $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $hash );
908 $chunksByKey[$chunkKey] = $segment;
909 $segmentHashes[] = $hash;
910 }
911 $flags &= ~self::WRITE_ALLOW_SEGMENTS;
912 $ok = $this->setMulti( $chunksByKey, $exptime, $flags );
913 $entry = SerializedValueContainer::newSegmented( $segmentHashes );
914 }
915 }
916
917 return $entry;
918 }
919
925 final protected function isRelativeExpiration( $exptime ) {
926 return ( $exptime !== self::TTL_INDEFINITE && $exptime < ( 10 * self::TTL_YEAR ) );
927 }
928
942 final protected function getExpirationAsTimestamp( $exptime ) {
943 if ( $exptime == self::TTL_INDEFINITE ) {
944 return $exptime;
945 }
946
947 return $this->isRelativeExpiration( $exptime )
948 ? intval( $this->getCurrentTime() + $exptime )
949 : $exptime;
950 }
951
966 final protected function getExpirationAsTTL( $exptime ) {
967 if ( $exptime == self::TTL_INDEFINITE ) {
968 return $exptime;
969 }
970
971 return $this->isRelativeExpiration( $exptime )
972 ? $exptime
973 : (int)max( $exptime - $this->getCurrentTime(), 1 );
974 }
975
982 final protected function isInteger( $value ) {
983 if ( is_int( $value ) ) {
984 return true;
985 } elseif ( !is_string( $value ) ) {
986 return false;
987 }
988
989 $integer = (int)$value;
990
991 return ( $value === (string)$integer );
992 }
993
994 public function makeGlobalKey( $collection, ...$components ) {
995 return $this->makeKeyInternal( self::GLOBAL_KEYSPACE, func_get_args() );
996 }
997
998 public function makeKey( $collection, ...$components ) {
999 return $this->makeKeyInternal( $this->keyspace, func_get_args() );
1000 }
1001
1002 protected function convertGenericKey( $key ) {
1003 $components = $this->componentsFromGenericKey( $key );
1004 if ( count( $components ) < 2 ) {
1005 // Legacy key not from makeKey()/makeGlobalKey(); keep it as-is
1006 return $key;
1007 }
1008
1009 $keyspace = array_shift( $components );
1010
1011 return $this->makeKeyInternal( $keyspace, $components );
1012 }
1013
1014 public function getQoS( $flag ) {
1015 return $this->attrMap[$flag] ?? self::QOS_UNKNOWN;
1016 }
1017
1018 public function getSegmentationSize() {
1019 return $this->segmentationSize;
1020 }
1021
1022 public function getSegmentedValueMaxSize() {
1023 return $this->segmentedValueMaxSize;
1024 }
1025
1026 public function setNewPreparedValues( array $valueByKey ) {
1027 $this->preparedValues = [];
1028
1029 $sizes = [];
1030 foreach ( $valueByKey as $key => $value ) {
1031 if ( $value === false ) {
1032 // not storable, don't bother
1033 $sizes[] = null;
1034 continue;
1035 }
1036
1037 $serialized = $this->serialize( $value );
1038 $sizes[] = ( $serialized !== false ) ? strlen( $serialized ) : null;
1039
1040 $this->preparedValues[$key] = [ $value, $serialized ];
1041 }
1042
1043 return $sizes;
1044 }
1045
1056 protected function getSerialized( $value, $key ) {
1057 // Reuse any available prepared (serialized) value
1058 if ( array_key_exists( $key, $this->preparedValues ) ) {
1059 list( $prepValue, $prepSerialized ) = $this->preparedValues[$key];
1060 // Normally, this comparison should only take a few microseconds to confirm a match.
1061 // Using "===" on variables of different types is always fast. It is also fast for
1062 // variables of matching type int, float, bool, null, and object. Lastly, it is fast
1063 // for comparing arrays/strings if they are copy-on-write references, which should be
1064 // the case at this point, assuming prepareValues() was called correctly.
1065 if ( $prepValue === $value ) {
1066 unset( $this->preparedValues[$key] );
1067
1068 return $prepSerialized;
1069 }
1070 }
1071
1072 $this->checkValueSerializability( $value, $key );
1073
1074 return $this->serialize( $value );
1075 }
1076
1086 protected function guessSerialValueSize( $value, $depth = 0, &$loops = 0 ) {
1087 if ( is_string( $value ) ) {
1088 // E.g. "<type><delim1><quote><value><quote><delim2>"
1089 return strlen( $value ) + 5;
1090 } else {
1091 return strlen( serialize( $value ) );
1092 }
1093 }
1094
1102 protected function guessSerialSizeOfValues( array $values ) {
1103 $sizes = [];
1104 foreach ( $values as $value ) {
1105 $sizes[] = $this->guessSerialValueSize( $value );
1106 }
1107
1108 return $sizes;
1109 }
1110
1131 private function checkValueSerializability( $value, $key ) {
1132 if ( is_array( $value ) ) {
1133 $this->checkIterableMapSerializability( $value, $key );
1134 } elseif ( is_object( $value ) ) {
1135 // Note that Closure instances count as objects
1136 if ( $value instanceof stdClass ) {
1137 $this->checkIterableMapSerializability( $value, $key );
1138 } elseif ( !( $value instanceof JsonSerializable ) ) {
1139 $this->logger->warning(
1140 "{class} value for '{cachekey}'; serialization is suspect.",
1141 [ 'cachekey' => $key, 'class' => get_class( $value ) ]
1142 );
1143 }
1144 }
1145 }
1146
1151 private function checkIterableMapSerializability( $value, $key ) {
1152 foreach ( $value as $index => $entry ) {
1153 if ( is_object( $entry ) ) {
1154 // Note that Closure instances count as objects
1155 if (
1156 !( $entry instanceof stdClass ) &&
1157 !( $entry instanceof JsonSerializable )
1158 ) {
1159 $this->logger->warning(
1160 "{class} value for '{cachekey}' at '$index'; serialization is suspect.",
1161 [ 'cachekey' => $key, 'class' => get_class( $entry ) ]
1162 );
1163
1164 return;
1165 }
1166 }
1167 }
1168 }
1169
1175 protected function serialize( $value ) {
1176 return is_int( $value ) ? $value : serialize( $value );
1177 }
1178
1184 protected function unserialize( $value ) {
1185 return $this->isInteger( $value ) ? (int)$value : unserialize( $value );
1186 }
1187
1191 protected function debug( $text ) {
1192 $this->logger->debug( "{class} debug: $text", [ 'class' => static::class ] );
1193 }
1194
1202 protected function updateOpStats( string $op, array $keyInfo ) {
1203 $deltasByMetric = [];
1204
1205 foreach ( $keyInfo as $indexOrKey => $keyOrSizes ) {
1206 if ( is_array( $keyOrSizes ) ) {
1207 $key = $indexOrKey;
1208 list( $sPayloadSize, $rPayloadSize ) = $keyOrSizes;
1209 } else {
1210 $key = $keyOrSizes;
1211 $sPayloadSize = 0;
1212 $rPayloadSize = 0;
1213 }
1214
1215 // Metric prefix for the cache wrapper and key collection name
1216 $prefix = $this->determineKeyPrefixForStats( $key );
1217
1218 if ( $op === self::METRIC_OP_GET ) {
1219 // This operation was either a "hit" or "miss" for this key
1220 $name = "{$prefix}.{$op}_" . ( $rPayloadSize === false ? 'miss_rate' : 'hit_rate' );
1221 } else {
1222 // There is no concept of "hit" or "miss" for this operation
1223 $name = "{$prefix}.{$op}_call_rate";
1224 }
1225 $deltasByMetric[$name] = ( $deltasByMetric[$name] ?? 0 ) + 1;
1226
1227 if ( $sPayloadSize > 0 ) {
1228 $name = "{$prefix}.{$op}_bytes_sent";
1229 $deltasByMetric[$name] = ( $deltasByMetric[$name] ?? 0 ) + $sPayloadSize;
1230 }
1231
1232 if ( $rPayloadSize > 0 ) {
1233 $name = "{$prefix}.{$op}_bytes_read";
1234 $deltasByMetric[$name] = ( $deltasByMetric[$name] ?? 0 ) + $rPayloadSize;
1235 }
1236 }
1237
1238 foreach ( $deltasByMetric as $name => $delta ) {
1239 $this->stats->updateCount( $name, $delta );
1240 }
1241 }
1242}
serialize()
unserialize( $serialized)
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
Class representing a cache/ephemeral data store.
Definition BagOStuff.php:85
fieldHasFlags( $field, $flags)
Storage medium specific cache for storing items (e.g.
doSet( $key, $value, $exptime=0, $flags=0)
Set an item.
int $segmentationSize
Bytes; chunk size of segmented cache values.
cas( $casToken, $key, $value, $exptime=0, $flags=0)
Set an item if the current CAS token matches the provided CAS token.
doDeleteMulti(array $keys, $flags=0)
const PASS_BY_REF
Idiom for doGet() to return extra information by reference.
setMulti(array $valueByKey, $exptime=0, $flags=0)
Batch insertion/replace.
guessSerialValueSize( $value, $depth=0, &$loops=0)
Estimate the size of a variable once serialized.
doChangeTTLMulti(array $keys, $exptime, $flags=0)
getExpirationAsTimestamp( $exptime)
Convert an optionally relative timestamp to an absolute time.
getMulti(array $keys, $flags=0)
Get an associative array containing the item for each of the keys that have items.
add( $key, $value, $exptime=0, $flags=0)
Insert an item if it does not already exist.
deleteMulti(array $keys, $flags=0)
Batch deletion.
tokensMatch( $value, $otherValue)
addBusyCallback(callable $workCallback)
Let a callback be run to avoid wasting time on special blocking calls.
getSerialized( $value, $key)
Get the serialized form a value, using any applicable prepared value.
doSetMulti(array $data, $exptime=0, $flags=0)
doChangeTTL( $key, $exptime, $flags)
makeKey( $collection,... $components)
Make a cache key for the global keyspace and given components.
merge( $key, callable $callback, $exptime=0, $attempts=10, $flags=0)
Merge changes into the existing cache value (possibly creating a new one)
unlock( $key)
Release an advisory lock on a key string.
doGetMulti(array $keys, $flags=0)
Get an associative array containing the item for each of the keys that have items.
doIncrWithInit( $key, $exptime, $step, $init, $flags)
updateOpStats(string $op, array $keyInfo)
array< string, array > $locks
Map of (key => (class, depth, expiry)
doCas( $casToken, $key, $value, $exptime=0, $flags=0)
Set an item if the current CAS token matches the provided CAS token.
doDelete( $key, $flags=0)
Delete an item.
doLock( $key, $timeout, $exptime)
convertGenericKey( $key)
Convert a "generic" reversible cache key into one for this cache.
mergeViaCas( $key, callable $callback, $exptime, $attempts, $flags)
doAdd( $key, $value, $exptime=0, $flags=0)
Insert an item if it does not already exist.
getExpirationAsTTL( $exptime)
Convert an optionally absolute expiry time to a relative time.
resolveSegments( $key, $mainValue)
Get and reassemble the chunks of blob at the given key.
changeTTLMulti(array $keys, $exptime, $flags=0)
Change the expiration of multiple keys that exist.
changeTTL( $key, $exptime=0, $flags=0)
Change the expiration on a key if it exists.
incrWithInit( $key, $exptime, $step=1, $init=null, $flags=0)
Increase the value of the given key (no TTL change) if it exists or create it otherwise.
isInteger( $value)
Check if a value is an integer.
makeGlobalKey( $collection,... $components)
Make a cache key for the default keyspace and given components.
lock( $key, $timeout=6, $exptime=6, $rclass='')
makeValueOrSegmentList( $key, $value, $exptime, $flags, &$ok)
Make the entry to store at a key (inline or segment list), storing any segments.
deleteObjectsExpiringBefore( $timestamp, callable $progress=null, $limit=INF, string $tag=null)
Delete all objects expiring before a certain date.
int $segmentedValueMaxSize
Bytes; maximum total size of a segmented cache value.
guessSerialSizeOfValues(array $values)
Estimate the size of a each variable once serialized.
array[] $preparedValues
Map of (key => (PHP variable value, serialized value))
setNewPreparedValues(array $valueByKey)
Stage a set of new key values for storage and estimate the amount of bytes needed.
doGet( $key, $flags=0, &$casToken=null)
Get an item.
static newSegmented(array $segmentHashList)
foreach( $res as $row) $serialized