MediaWiki  master
WANObjectCache.php
Go to the documentation of this file.
1 <?php
22 use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
23 use Psr\Log\LoggerAwareInterface;
24 use Psr\Log\LoggerInterface;
25 use Psr\Log\NullLogger;
28 
125 class WANObjectCache implements
129  LoggerAwareInterface
130 {
132  protected $cache;
134  protected $processCaches = [];
136  protected $logger;
138  protected $stats;
140  protected $asyncHandler;
141 
149  protected $broadcastRoute;
151  protected $useInterimHoldOffCaching = true;
153  protected $epoch;
155  protected $secret;
157  protected $coalesceScheme;
158 
160  private $keyHighQps;
162  private $keyHighByteSize;
164  private $keyHighUplinkBps;
165 
167  private $missLog;
168 
170  private $callbackDepth = 0;
172  private $warmupCache = [];
174  private $warmupKeyMisses = 0;
175 
177  private $wallClockOverride;
178 
180  private const MAX_COMMIT_DELAY = 3;
182  private const MAX_READ_LAG = 7;
184  public const HOLDOFF_TTL = self::MAX_COMMIT_DELAY + self::MAX_READ_LAG + 1;
185 
187  private const LOW_TTL = 60;
189  public const TTL_LAGGED = 30;
190 
192  private const HOT_TTR = 900;
194  private const AGE_NEW = 60;
195 
197  private const TSE_NONE = -1;
198 
200  public const STALE_TTL_NONE = 0;
202  public const GRACE_TTL_NONE = 0;
204  public const HOLDOFF_TTL_NONE = 0;
205 
207  public const MIN_TIMESTAMP_NONE = 0.0;
208 
210  private const PC_PRIMARY = 'primary:1000';
211 
213  public const PASS_BY_REF = [];
214 
216  private const SCHEME_HASH_TAG = 1;
218  private const SCHEME_HASH_STOP = 2;
219 
221  private const CHECK_KEY_TTL = self::TTL_YEAR;
223  private const INTERIM_KEY_TTL = 2;
224 
226  private const LOCK_TTL = 10;
228  private const COOLOFF_TTL = 2;
230  private const RAMPUP_TTL = 30;
231 
233  private const TINY_NEGATIVE = -0.000001;
235  private const TINY_POSTIVE = 0.000001;
236 
238  private const RECENT_SET_LOW_MS = 50;
240  private const RECENT_SET_HIGH_MS = 100;
241 
243  private const GENERATION_HIGH_SEC = 0.2;
244 
246  private const PURGE_TIME = 0;
248  private const PURGE_HOLDOFF = 1;
249 
251  private const VERSION = 1;
252 
254  public const KEY_VERSION = 'version';
256  public const KEY_AS_OF = 'asOf';
258  public const KEY_TTL = 'ttl';
260  public const KEY_CUR_TTL = 'curTTL';
262  public const KEY_TOMB_AS_OF = 'tombAsOf';
264  public const KEY_CHECK_AS_OF = 'lastCKPurge';
265 
267  private const RES_VALUE = 0;
269  private const RES_VERSION = 1;
271  private const RES_AS_OF = 2;
273  private const RES_TTL = 3;
275  private const RES_TOMB_AS_OF = 4;
277  private const RES_CHECK_AS_OF = 5;
279  private const RES_TOUCH_AS_OF = 6;
281  private const RES_CUR_TTL = 7;
282 
284  private const FLD_FORMAT_VERSION = 0;
286  private const FLD_VALUE = 1;
288  private const FLD_TTL = 2;
290  private const FLD_TIME = 3;
292  private const FLD_FLAGS = 4;
294  private const FLD_VALUE_VERSION = 5;
295  private const FLD_GENERATION_TIME = 6;
296 
298  private const TYPE_VALUE = 'v';
300  private const TYPE_TIMESTAMP = 't';
302  private const TYPE_MUTEX = 'm';
304  private const TYPE_INTERIM = 'i';
306  private const TYPE_COOLOFF = 'c';
307 
309  private const PURGE_VAL_PREFIX = 'PURGED';
310 
347  public function __construct( array $params ) {
348  $this->cache = $params['cache'];
349  $this->broadcastRoute = $params['broadcastRoutingPrefix'] ?? null;
350  $this->epoch = $params['epoch'] ?? 0;
351  $this->secret = $params['secret'] ?? (string)$this->epoch;
352  if ( ( $params['coalesceScheme'] ?? '' ) === 'hash_tag' ) {
353  // https://redis.io/topics/cluster-spec
354  // https://github.com/twitter/twemproxy/blob/v0.4.1/notes/recommendation.md#hash-tags
355  // https://github.com/Netflix/dynomite/blob/v0.7.0/notes/recommendation.md#hash-tags
356  $this->coalesceScheme = self::SCHEME_HASH_TAG;
357  } else {
358  // https://github.com/facebook/mcrouter/wiki/Key-syntax
359  $this->coalesceScheme = self::SCHEME_HASH_STOP;
360  }
361 
362  $this->keyHighQps = $params['keyHighQps'] ?? 100;
363  $this->keyHighByteSize = $params['keyHighByteSize'] ?? ( 128 * 1024 );
364  $this->keyHighUplinkBps = $params['keyHighUplinkBps'] ?? ( 1e9 / 8 / 100 );
365 
366  $this->setLogger( $params['logger'] ?? new NullLogger() );
367  $this->stats = $params['stats'] ?? new NullStatsdDataFactory();
368  $this->asyncHandler = $params['asyncHandler'] ?? null;
369 
370  $this->missLog = array_fill( 0, 10, [ '', 0.0 ] );
371 
372  $this->cache->registerWrapperInfoForStats(
373  'WANCache',
374  'wanobjectcache',
375  [ __CLASS__, 'getCollectionFromSisterKey' ]
376  );
377  }
378 
382  public function setLogger( LoggerInterface $logger ) {
383  $this->logger = $logger;
384  }
385 
391  public static function newEmpty() {
392  return new static( [ 'cache' => new EmptyBagOStuff() ] );
393  }
394 
450  final public function get( $key, &$curTTL = null, array $checkKeys = [], &$info = [] ) {
451  // Note that an undeclared variable passed as $info starts as null (not the default).
452  // Also, if no $info parameter is provided, then it doesn't matter how it changes here.
453  $legacyInfo = ( $info !== self::PASS_BY_REF );
454 
455  $res = $this->fetchKeys( [ $key ], $checkKeys )[$key];
456 
457  $curTTL = $res[self::RES_CUR_TTL];
458  $info = $legacyInfo
459  ? $res[self::RES_AS_OF]
460  : [
461  self::KEY_VERSION => $res[self::RES_VERSION],
462  self::KEY_AS_OF => $res[self::RES_AS_OF],
463  self::KEY_TTL => $res[self::RES_TTL],
464  self::KEY_CUR_TTL => $res[self::RES_CUR_TTL],
465  self::KEY_TOMB_AS_OF => $res[self::RES_TOMB_AS_OF],
466  self::KEY_CHECK_AS_OF => $res[self::RES_CHECK_AS_OF]
467  ];
468 
469  if ( $curTTL === null || $curTTL <= 0 ) {
470  // Log the timestamp in case a corresponding set() call does not provide "walltime"
471  unset( $this->missLog[array_key_first( $this->missLog )] );
472  $this->missLog[] = [ $key, $this->getCurrentTime() ];
473  }
474 
475  return $res[self::RES_VALUE];
476  }
477 
502  final public function getMulti(
503  array $keys,
504  &$curTTLs = [],
505  array $checkKeys = [],
506  &$info = []
507  ) {
508  // Note that an undeclared variable passed as $info starts as null (not the default).
509  // Also, if no $info parameter is provided, then it doesn't matter how it changes here.
510  $legacyInfo = ( $info !== self::PASS_BY_REF );
511 
512  $curTTLs = [];
513  $info = [];
514  $valuesByKey = [];
515 
516  $resByKey = $this->fetchKeys( $keys, $checkKeys );
517  foreach ( $resByKey as $key => $res ) {
518  if ( $res[self::RES_VALUE] !== false ) {
519  $valuesByKey[$key] = $res[self::RES_VALUE];
520  }
521 
522  if ( $res[self::RES_CUR_TTL] !== null ) {
523  $curTTLs[$key] = $res[self::RES_CUR_TTL];
524  }
525  $info[$key] = $legacyInfo
526  ? $res[self::RES_AS_OF]
527  : [
528  self::KEY_VERSION => $res[self::RES_VERSION],
529  self::KEY_AS_OF => $res[self::RES_AS_OF],
530  self::KEY_TTL => $res[self::RES_TTL],
531  self::KEY_CUR_TTL => $res[self::RES_CUR_TTL],
532  self::KEY_TOMB_AS_OF => $res[self::RES_TOMB_AS_OF],
533  self::KEY_CHECK_AS_OF => $res[self::RES_CHECK_AS_OF]
534  ];
535  }
536 
537  return $valuesByKey;
538  }
539 
554  protected function fetchKeys( array $keys, array $checkKeys, $touchedCb = null ) {
555  $resByKey = [];
556 
557  // List of all sister keys that need to be fetched from cache
558  $allSisterKeys = [];
559  // Order-corresponding value sister key list for the base key list ($keys)
560  $valueSisterKeys = [];
561  // List of "check" sister keys to compare all value sister keys against
562  $checkSisterKeysForAll = [];
563  // Map of (base key => additional "check" sister key(s) to compare against)
564  $checkSisterKeysByKey = [];
565 
566  foreach ( $keys as $key ) {
567  $sisterKey = $this->makeSisterKey( $key, self::TYPE_VALUE );
568  $allSisterKeys[] = $sisterKey;
569  $valueSisterKeys[] = $sisterKey;
570  }
571 
572  foreach ( $checkKeys as $i => $checkKeyOrKeyGroup ) {
573  // Note: avoid array_merge() inside loop in case there are many keys
574  if ( is_int( $i ) ) {
575  // Single "check" key that applies to all base keys
576  $sisterKey = $this->makeSisterKey( $checkKeyOrKeyGroup, self::TYPE_TIMESTAMP );
577  $allSisterKeys[] = $sisterKey;
578  $checkSisterKeysForAll[] = $sisterKey;
579  } else {
580  // List of "check" keys that apply to a specific base key
581  foreach ( (array)$checkKeyOrKeyGroup as $checkKey ) {
582  $sisterKey = $this->makeSisterKey( $checkKey, self::TYPE_TIMESTAMP );
583  $allSisterKeys[] = $sisterKey;
584  $checkSisterKeysByKey[$i][] = $sisterKey;
585  }
586  }
587  }
588 
589  if ( $this->warmupCache ) {
590  // Get the wrapped values of the sister keys from the warmup cache
591  $wrappedBySisterKey = $this->warmupCache;
592  $sisterKeysMissing = array_diff( $allSisterKeys, array_keys( $wrappedBySisterKey ) );
593  if ( $sisterKeysMissing ) {
594  $this->warmupKeyMisses += count( $sisterKeysMissing );
595  $wrappedBySisterKey += $this->cache->getMulti( $sisterKeysMissing );
596  }
597  } else {
598  // Fetch the wrapped values of the sister keys from the backend
599  $wrappedBySisterKey = $this->cache->getMulti( $allSisterKeys );
600  }
601 
602  // Pessimistically treat the "current time" as the time when any network I/O finished
603  $now = $this->getCurrentTime();
604 
605  // List of "check" sister key purge timestamps to compare all value sister keys against
606  $ckPurgesForAll = $this->processCheckKeys(
607  $checkSisterKeysForAll,
608  $wrappedBySisterKey,
609  $now
610  );
611  // Map of (base key => extra "check" sister key purge timestamp(s) to compare against)
612  $ckPurgesByKey = [];
613  foreach ( $checkSisterKeysByKey as $keyWithCheckKeys => $checkKeysForKey ) {
614  $ckPurgesByKey[$keyWithCheckKeys] = $this->processCheckKeys(
615  $checkKeysForKey,
616  $wrappedBySisterKey,
617  $now
618  );
619  }
620 
621  // Unwrap and validate any value found for each base key (under the value sister key)
622  reset( $keys );
623  foreach ( $valueSisterKeys as $valueSisterKey ) {
624  // Get the corresponding base key for this value sister key
625  $key = current( $keys );
626  next( $keys );
627 
628  if ( array_key_exists( $valueSisterKey, $wrappedBySisterKey ) ) {
629  // Key exists as either a live value or tombstone value
630  $wrapped = $wrappedBySisterKey[$valueSisterKey];
631  } else {
632  // Key does not exist
633  $wrapped = false;
634  }
635 
636  $res = $this->unwrap( $wrapped, $now );
637  $value = $res[self::RES_VALUE];
638 
639  foreach ( array_merge( $ckPurgesForAll, $ckPurgesByKey[$key] ?? [] ) as $ckPurge ) {
640  $res[self::RES_CHECK_AS_OF] = max(
641  $ckPurge[self::PURGE_TIME],
642  $res[self::RES_CHECK_AS_OF]
643  );
644  // Timestamp marking the end of the hold-off period for this purge
645  $holdoffDeadline = $ckPurge[self::PURGE_TIME] + $ckPurge[self::PURGE_HOLDOFF];
646  // Check if the value was generated during the hold-off period
647  if ( $value !== false && $holdoffDeadline >= $res[self::RES_AS_OF] ) {
648  // How long ago this value was purged by *this* "check" key
649  $ago = min( $ckPurge[self::PURGE_TIME] - $now, self::TINY_NEGATIVE );
650  // How long ago this value was purged by *any* known "check" key
651  $res[self::RES_CUR_TTL] = min( $res[self::RES_CUR_TTL], $ago );
652  }
653  }
654 
655  if ( $touchedCb !== null && $value !== false ) {
656  $touched = $touchedCb( $value );
657  if ( $touched !== null && $touched >= $res[self::RES_AS_OF] ) {
658  $res[self::RES_CUR_TTL] = min(
659  $res[self::RES_CUR_TTL],
660  $res[self::RES_AS_OF] - $touched,
661  self::TINY_NEGATIVE
662  );
663  }
664  } else {
665  $touched = null;
666  }
667 
668  $res[self::RES_TOUCH_AS_OF] = max( $res[self::RES_TOUCH_AS_OF], $touched );
669 
670  $resByKey[$key] = $res;
671  }
672 
673  return $resByKey;
674  }
675 
682  private function processCheckKeys(
683  array $checkSisterKeys,
684  array $wrappedBySisterKey,
685  float $now
686  ) {
687  $purges = [];
688 
689  foreach ( $checkSisterKeys as $timeKey ) {
690  $purge = isset( $wrappedBySisterKey[$timeKey] )
691  ? $this->parsePurgeValue( $wrappedBySisterKey[$timeKey] )
692  : null;
693 
694  if ( $purge === null ) {
695  $wrapped = $this->makeCheckPurgeValue( $now, self::HOLDOFF_TTL, $purge );
696  $this->cache->add(
697  $timeKey,
698  $wrapped,
699  self::CHECK_KEY_TTL,
700  $this->cache::WRITE_BACKGROUND
701  );
702  }
703 
704  $purges[] = $purge;
705  }
706 
707  return $purges;
708  }
709 
793  final public function set( $key, $value, $ttl = self::TTL_INDEFINITE, array $opts = [] ) {
794  $kClass = $this->determineKeyClassForStats( $key );
795 
796  $ok = $this->setMainValue(
797  $key,
798  $value,
799  $ttl,
800  $opts['version'] ?? null,
801  $opts['walltime'] ?? null,
802  $opts['lag'] ?? 0,
803  $opts['since'] ?? null,
804  $opts['pending'] ?? false,
805  $opts['lockTSE'] ?? self::TSE_NONE,
806  $opts['staleTTL'] ?? self::STALE_TTL_NONE,
807  $opts['segmentable'] ?? false,
808  $opts['creating'] ?? false
809  );
810 
811  $this->stats->increment( "wanobjectcache.$kClass.set." . ( $ok ? 'ok' : 'error' ) );
812 
813  return $ok;
814  }
815 
831  private function setMainValue(
832  $key,
833  $value,
834  $ttl,
835  ?int $version,
836  ?float $walltime,
837  $dataReplicaLag,
838  $dataReadSince,
839  bool $dataPendingCommit,
840  int $lockTSE,
841  int $staleTTL,
842  bool $segmentable,
843  bool $creating
844  ) {
845  if ( $ttl < 0 ) {
846  // not cacheable
847  return true;
848  }
849 
850  $now = $this->getCurrentTime();
851  $ttl = (int)$ttl;
852  $walltime ??= $this->timeSinceLoggedMiss( $key, $now );
853  $dataSnapshotLag = ( $dataReadSince !== null ) ? max( 0, $now - $dataReadSince ) : 0;
854  $dataCombinedLag = $dataReplicaLag + $dataSnapshotLag;
855 
856  // Forbid caching data that only exists within an uncommitted transaction. Also, lower
857  // the TTL when the data has a "since" time so far in the past that a delete() tombstone,
858  // made after that time, could have already expired (the key is no longer write-holed).
859  // The mitigation TTL depends on whether this data lag is assumed to systemically effect
860  // regeneration attempts in the near future. The TTL also reflects regeneration wall time.
861  if ( $dataPendingCommit ) {
862  // Case A: data comes from an uncommitted write transaction
863  $mitigated = 'pending writes';
864  // Data might never be committed; rely on a less problematic regeneration attempt
865  $mitigationTTL = self::TTL_UNCACHEABLE;
866  } elseif ( $dataSnapshotLag > self::MAX_READ_LAG ) {
867  // Case B: high snapshot lag
868  $pregenSnapshotLag = ( $walltime !== null ) ? ( $dataSnapshotLag - $walltime ) : 0;
869  if ( ( $pregenSnapshotLag + self::GENERATION_HIGH_SEC ) > self::MAX_READ_LAG ) {
870  // Case B1: generation started when transaction duration was already long
871  $mitigated = 'snapshot lag (late generation)';
872  // Probably non-systemic; rely on a less problematic regeneration attempt
873  $mitigationTTL = self::TTL_UNCACHEABLE;
874  } else {
875  // Case B2: slow generation made transaction duration long
876  $mitigated = 'snapshot lag (high generation time)';
877  // Probably systemic; use a low TTL to avoid stampedes/uncacheability
878  $mitigationTTL = self::TTL_LAGGED;
879  }
880  } elseif ( $dataReplicaLag === false || $dataReplicaLag > self::MAX_READ_LAG ) {
881  // Case C: low/medium snapshot lag with high replication lag
882  $mitigated = 'replication lag';
883  // Probably systemic; use a low TTL to avoid stampedes/uncacheability
884  $mitigationTTL = self::TTL_LAGGED;
885  } elseif ( $dataCombinedLag > self::MAX_READ_LAG ) {
886  $pregenCombinedLag = ( $walltime !== null ) ? ( $dataCombinedLag - $walltime ) : 0;
887  // Case D: medium snapshot lag with medium replication lag
888  if ( ( $pregenCombinedLag + self::GENERATION_HIGH_SEC ) > self::MAX_READ_LAG ) {
889  // Case D1: generation started when read lag was too high
890  $mitigated = 'read lag (late generation)';
891  // Probably non-systemic; rely on a less problematic regeneration attempt
892  $mitigationTTL = self::TTL_UNCACHEABLE;
893  } else {
894  // Case D2: slow generation made read lag too high
895  $mitigated = 'read lag (high generation time)';
896  // Probably systemic; use a low TTL to avoid stampedes/uncacheability
897  $mitigationTTL = self::TTL_LAGGED;
898  }
899  } else {
900  // Case E: new value generated with recent data
901  $mitigated = null;
902  // Nothing to mitigate
903  $mitigationTTL = null;
904  }
905 
906  if ( $mitigationTTL === self::TTL_UNCACHEABLE ) {
907  $this->logger->warning(
908  "Rejected set() for {cachekey} due to $mitigated.",
909  [
910  'cachekey' => $key,
911  'lag' => $dataReplicaLag,
912  'age' => $dataSnapshotLag,
913  'walltime' => $walltime
914  ]
915  );
916 
917  // no-op the write for being unsafe
918  return true;
919  }
920 
921  // TTL to use in staleness checks (does not effect persistence layer TTL)
922  $logicalTTL = null;
923 
924  if ( $mitigationTTL !== null ) {
925  // New value was generated from data that is old enough to be risky
926  if ( $lockTSE >= 0 ) {
927  // Persist the value as long as normal, but make it count as stale sooner
928  $logicalTTL = min( $ttl ?: INF, $mitigationTTL );
929  } else {
930  // Persist the value for a shorter duration
931  $ttl = min( $ttl ?: INF, $mitigationTTL );
932  }
933 
934  $this->logger->warning(
935  "Lowered set() TTL for {cachekey} due to $mitigated.",
936  [
937  'cachekey' => $key,
938  'lag' => $dataReplicaLag,
939  'age' => $dataSnapshotLag,
940  'walltime' => $walltime
941  ]
942  );
943  }
944 
945  // Wrap that value with time/TTL/version metadata
946  $wrapped = $this->wrap( $value, $logicalTTL ?: $ttl, $version, $now, $walltime );
947  $storeTTL = $ttl + $staleTTL;
948 
949  $flags = $this->cache::WRITE_BACKGROUND;
950  if ( $segmentable ) {
951  $flags |= $this->cache::WRITE_ALLOW_SEGMENTS;
952  }
953 
954  if ( $creating ) {
955  $ok = $this->cache->add(
956  $this->makeSisterKey( $key, self::TYPE_VALUE ),
957  $wrapped,
958  $storeTTL,
959  $flags
960  );
961  } else {
962  $ok = $this->cache->merge(
963  $this->makeSisterKey( $key, self::TYPE_VALUE ),
964  static function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
965  // A string value means that it is a tombstone; do nothing in that case
966  return ( is_string( $cWrapped ) ) ? false : $wrapped;
967  },
968  $storeTTL,
969  $this->cache::MAX_CONFLICTS_ONE,
970  $flags
971  );
972  }
973 
974  return $ok;
975  }
976 
1039  final public function delete( $key, $ttl = self::HOLDOFF_TTL ) {
1040  // Purge values must be stored under the value key so that WANObjectCache::set()
1041  // can atomically merge values without accidentally undoing a recent purge and thus
1042  // violating the holdoff TTL restriction.
1043  $valueSisterKey = $this->makeSisterKey( $key, self::TYPE_VALUE );
1044 
1045  if ( $ttl <= 0 ) {
1046  // A client or cache cleanup script is requesting a cache purge, so there is no
1047  // volatility period due to replica DB lag. Any recent change to an entity cached
1048  // in this key should have triggered an appropriate purge event.
1049  $ok = $this->relayNonVolatilePurge( $valueSisterKey );
1050  } else {
1051  // A cacheable entity recently changed, so there might be a volatility period due
1052  // to replica DB lag. Clients usually expect their actions to be reflected in any
1053  // of their subsequent web request. This is attainable if (a) purge relay lag is
1054  // lower than the time it takes for subsequent request by the client to arrive,
1055  // and, (b) DB replica queries have "read-your-writes" consistency due to DB lag
1056  // mitigation systems.
1057  $now = $this->getCurrentTime();
1058  // Set the key to the purge value in all datacenters
1059  $purge = $this->makeTombstonePurgeValue( $now );
1060  $ok = $this->relayVolatilePurge( $valueSisterKey, $purge, $ttl );
1061  }
1062 
1063  $kClass = $this->determineKeyClassForStats( $key );
1064  $this->stats->increment( "wanobjectcache.$kClass.delete." . ( $ok ? 'ok' : 'error' ) );
1065 
1066  return $ok;
1067  }
1068 
1088  final public function getCheckKeyTime( $key ) {
1089  return $this->getMultiCheckKeyTime( [ $key ] )[$key];
1090  }
1091 
1153  final public function getMultiCheckKeyTime( array $keys ) {
1154  $checkSisterKeysByKey = [];
1155  foreach ( $keys as $key ) {
1156  $checkSisterKeysByKey[$key] = $this->makeSisterKey( $key, self::TYPE_TIMESTAMP );
1157  }
1158 
1159  $wrappedBySisterKey = $this->cache->getMulti( $checkSisterKeysByKey );
1160  $wrappedBySisterKey += array_fill_keys( $checkSisterKeysByKey, false );
1161 
1162  $now = $this->getCurrentTime();
1163  $times = [];
1164  foreach ( $checkSisterKeysByKey as $key => $checkSisterKey ) {
1165  $purge = $this->parsePurgeValue( $wrappedBySisterKey[$checkSisterKey] );
1166  if ( $purge === null ) {
1167  $wrapped = $this->makeCheckPurgeValue( $now, self::HOLDOFF_TTL, $purge );
1168  $this->cache->add(
1169  $checkSisterKey,
1170  $wrapped,
1171  self::CHECK_KEY_TTL,
1172  $this->cache::WRITE_BACKGROUND
1173  );
1174  }
1175 
1176  $times[$key] = $purge[self::PURGE_TIME];
1177  }
1178 
1179  return $times;
1180  }
1181 
1215  final public function touchCheckKey( $key, $holdoff = self::HOLDOFF_TTL ) {
1216  $checkSisterKey = $this->makeSisterKey( $key, self::TYPE_TIMESTAMP );
1217 
1218  $now = $this->getCurrentTime();
1219  $purge = $this->makeCheckPurgeValue( $now, $holdoff );
1220  $ok = $this->relayVolatilePurge( $checkSisterKey, $purge, self::CHECK_KEY_TTL );
1221 
1222  $kClass = $this->determineKeyClassForStats( $key );
1223  $this->stats->increment( "wanobjectcache.$kClass.ck_touch." . ( $ok ? 'ok' : 'error' ) );
1224 
1225  return $ok;
1226  }
1227 
1255  final public function resetCheckKey( $key ) {
1256  $checkSisterKey = $this->makeSisterKey( $key, self::TYPE_TIMESTAMP );
1257  $ok = $this->relayNonVolatilePurge( $checkSisterKey );
1258 
1259  $kClass = $this->determineKeyClassForStats( $key );
1260  $this->stats->increment( "wanobjectcache.$kClass.ck_reset." . ( $ok ? 'ok' : 'error' ) );
1261 
1262  return $ok;
1263  }
1264 
1566  final public function getWithSetCallback(
1567  $key, $ttl, $callback, array $opts = [], array $cbParams = []
1568  ) {
1569  $version = $opts['version'] ?? null;
1570  $pcTTL = $opts['pcTTL'] ?? self::TTL_UNCACHEABLE;
1571  $pCache = ( $pcTTL >= 0 )
1572  ? $this->getProcessCache( $opts['pcGroup'] ?? self::PC_PRIMARY )
1573  : null;
1574 
1575  // Use the process cache if requested as long as no outer cache callback is running.
1576  // Nested callback process cache use is not lag-safe with regard to HOLDOFF_TTL since
1577  // process cached values are more lagged than persistent ones as they are not purged.
1578  if ( $pCache && $this->callbackDepth == 0 ) {
1579  $cached = $pCache->get( $key, $pcTTL, false );
1580  if ( $cached !== false ) {
1581  $this->logger->debug( "getWithSetCallback($key): process cache hit" );
1582  return $cached;
1583  }
1584  }
1585 
1586  [ $value, $valueVersion, $curAsOf ] = $this->fetchOrRegenerate( $key, $ttl, $callback, $opts, $cbParams );
1587  if ( $valueVersion !== $version ) {
1588  // Current value has a different version; use the variant key for this version.
1589  // Regenerate the variant value if it is not newer than the main value at $key
1590  // so that purges to the main key propagate to the variant value.
1591  $this->logger->debug( "getWithSetCallback($key): using variant key" );
1592  [ $value ] = $this->fetchOrRegenerate(
1593  $this->makeGlobalKey( 'WANCache-key-variant', md5( $key ), (string)$version ),
1594  $ttl,
1595  $callback,
1596  [ 'version' => null, 'minAsOf' => $curAsOf ] + $opts,
1597  $cbParams
1598  );
1599  }
1600 
1601  // Update the process cache if enabled
1602  if ( $pCache && $value !== false ) {
1603  $pCache->set( $key, $value );
1604  }
1605 
1606  return $value;
1607  }
1608 
1625  private function fetchOrRegenerate( $key, $ttl, $callback, array $opts, array $cbParams ) {
1626  $checkKeys = $opts['checkKeys'] ?? [];
1627  $graceTTL = $opts['graceTTL'] ?? self::GRACE_TTL_NONE;
1628  $minAsOf = $opts['minAsOf'] ?? self::MIN_TIMESTAMP_NONE;
1629  $hotTTR = $opts['hotTTR'] ?? self::HOT_TTR;
1630  $lowTTL = $opts['lowTTL'] ?? min( self::LOW_TTL, $ttl );
1631  $ageNew = $opts['ageNew'] ?? self::AGE_NEW;
1632  $touchedCb = $opts['touchedCallback'] ?? null;
1633  $startTime = $this->getCurrentTime();
1634 
1635  $kClass = $this->determineKeyClassForStats( $key );
1636 
1637  // Get the current key value and its metadata
1638  $curState = $this->fetchKeys( [ $key ], $checkKeys, $touchedCb )[$key];
1639  $curValue = $curState[self::RES_VALUE];
1640  // Use the cached value if it exists and is not due for synchronous regeneration
1641  if ( $this->isAcceptablyFreshValue( $curState, $graceTTL, $minAsOf ) ) {
1642  if ( !$this->isLotteryRefreshDue( $curState, $lowTTL, $ageNew, $hotTTR, $startTime ) ) {
1643  $this->stats->timing(
1644  "wanobjectcache.$kClass.hit.good",
1645  1e3 * ( $this->getCurrentTime() - $startTime )
1646  );
1647 
1648  return [ $curValue, $curState[self::RES_VERSION], $curState[self::RES_AS_OF] ];
1649  } elseif ( $this->scheduleAsyncRefresh( $key, $ttl, $callback, $opts, $cbParams ) ) {
1650  $this->logger->debug( "fetchOrRegenerate($key): hit with async refresh" );
1651  $this->stats->timing(
1652  "wanobjectcache.$kClass.hit.refresh",
1653  1e3 * ( $this->getCurrentTime() - $startTime )
1654  );
1655 
1656  return [ $curValue, $curState[self::RES_VERSION], $curState[self::RES_AS_OF] ];
1657  } else {
1658  $this->logger->debug( "fetchOrRegenerate($key): hit with sync refresh" );
1659  }
1660  }
1661 
1662  $isKeyTombstoned = ( $curState[self::RES_TOMB_AS_OF] !== null );
1663  // Use the interim key as a temporary alternative if the key is tombstoned
1664  if ( $isKeyTombstoned ) {
1665  $volState = $this->getInterimValue( $key, $minAsOf, $startTime, $touchedCb );
1666  $volValue = $volState[self::RES_VALUE];
1667  } else {
1668  $volState = $curState;
1669  $volValue = $curValue;
1670  }
1671 
1672  // During the volatile "hold-off" period that follows a purge of the key, the value
1673  // will be regenerated many times if frequently accessed. This is done to mitigate
1674  // the effects of backend replication lag as soon as possible. However, throttle the
1675  // overhead of locking and regeneration by reusing values recently written to cache
1676  // tens of milliseconds ago. Verify the "as of" time against the last purge event.
1677  $lastPurgeTime = max(
1678  // RES_TOUCH_AS_OF depends on the value (possibly from the interim key)
1679  $volState[self::RES_TOUCH_AS_OF],
1680  $curState[self::RES_TOMB_AS_OF],
1681  $curState[self::RES_CHECK_AS_OF]
1682  );
1683  $safeMinAsOf = max( $minAsOf, $lastPurgeTime + self::TINY_POSTIVE );
1684  if ( $this->isExtremelyNewValue( $volState, $safeMinAsOf, $startTime ) ) {
1685  $this->logger->debug( "fetchOrRegenerate($key): volatile hit" );
1686  $this->stats->timing(
1687  "wanobjectcache.$kClass.hit.volatile",
1688  1e3 * ( $this->getCurrentTime() - $startTime )
1689  );
1690 
1691  return [ $volValue, $volState[self::RES_VERSION], $curState[self::RES_AS_OF] ];
1692  }
1693 
1694  $lockTSE = $opts['lockTSE'] ?? self::TSE_NONE;
1695  $busyValue = $opts['busyValue'] ?? null;
1696  $staleTTL = $opts['staleTTL'] ?? self::STALE_TTL_NONE;
1697  $segmentable = $opts['segmentable'] ?? false;
1698  $version = $opts['version'] ?? null;
1699 
1700  // Determine whether one thread per datacenter should handle regeneration at a time
1701  $useRegenerationLock =
1702  // Note that since tombstones no-op set(), $lockTSE and $curTTL cannot be used to
1703  // deduce the key hotness because |$curTTL| will always keep increasing until the
1704  // tombstone expires or is overwritten by a new tombstone. Also, even if $lockTSE
1705  // is not set, constant regeneration of a key for the tombstone lifetime might be
1706  // very expensive. Assume tombstoned keys are possibly hot in order to reduce
1707  // the risk of high regeneration load after the delete() method is called.
1708  $isKeyTombstoned ||
1709  // Assume a key is hot if requested soon ($lockTSE seconds) after purge.
1710  // This avoids stampedes when timestamps from $checkKeys/$touchedCb bump.
1711  (
1712  $curState[self::RES_CUR_TTL] !== null &&
1713  $curState[self::RES_CUR_TTL] <= 0 &&
1714  abs( $curState[self::RES_CUR_TTL] ) <= $lockTSE
1715  ) ||
1716  // Assume a key is hot if there is no value and a busy fallback is given.
1717  // This avoids stampedes on eviction or preemptive regeneration taking too long.
1718  ( $busyValue !== null && $volValue === false );
1719 
1720  // If a regeneration lock is required, threads that do not get the lock will try to use
1721  // the stale value, the interim value, or the $busyValue placeholder, in that order. If
1722  // none of those are set then all threads will bypass the lock and regenerate the value.
1723  $hasLock = $useRegenerationLock && $this->claimStampedeLock( $key );
1724  if ( $useRegenerationLock && !$hasLock ) {
1725  // Determine if there is stale or volatile cached value that is still usable
1726  // @phan-suppress-next-line PhanTypeMismatchArgumentNullable False positive
1727  if ( $this->isValid( $volValue, $volState[self::RES_AS_OF], $minAsOf ) ) {
1728  $this->logger->debug( "fetchOrRegenerate($key): returning stale value" );
1729  $this->stats->timing(
1730  "wanobjectcache.$kClass.hit.stale",
1731  1e3 * ( $this->getCurrentTime() - $startTime )
1732  );
1733 
1734  return [ $volValue, $volState[self::RES_VERSION], $curState[self::RES_AS_OF] ];
1735  } elseif ( $busyValue !== null ) {
1736  $miss = is_infinite( $minAsOf ) ? 'renew' : 'miss';
1737  $this->logger->debug( "fetchOrRegenerate($key): busy $miss" );
1738  $this->stats->timing(
1739  "wanobjectcache.$kClass.$miss.busy",
1740  1e3 * ( $this->getCurrentTime() - $startTime )
1741  );
1742  $placeholderValue = $this->resolveBusyValue( $busyValue );
1743 
1744  return [ $placeholderValue, $version, $curState[self::RES_AS_OF] ];
1745  }
1746  }
1747 
1748  // Generate the new value given any prior value with a matching version
1749  $setOpts = [];
1750  $preCallbackTime = $this->getCurrentTime();
1751  ++$this->callbackDepth;
1752  // https://github.com/phan/phan/issues/4419
1753  $value = null;
1754  try {
1755  $value = $callback(
1756  ( $curState[self::RES_VERSION] === $version ) ? $curValue : false,
1757  $ttl,
1758  $setOpts,
1759  ( $curState[self::RES_VERSION] === $version ) ? $curState[self::RES_AS_OF] : null,
1760  $cbParams
1761  );
1762  } finally {
1763  --$this->callbackDepth;
1764  }
1765  $postCallbackTime = $this->getCurrentTime();
1766 
1767  // How long it took to fetch, validate, and generate the value
1768  $elapsed = max( $postCallbackTime - $startTime, 0.0 );
1769 
1770  // How long it took to generate the value
1771  $walltime = max( $postCallbackTime - $preCallbackTime, 0.0 );
1772  $this->stats->timing( "wanobjectcache.$kClass.regen_walltime", 1e3 * $walltime );
1773 
1774  // Attempt to save the newly generated value if applicable
1775  if (
1776  // Callback yielded a cacheable value
1777  ( $value !== false && $ttl >= 0 ) &&
1778  // Current thread was not raced out of a regeneration lock or key is tombstoned
1779  ( !$useRegenerationLock || $hasLock || $isKeyTombstoned ) &&
1780  // Key does not appear to be undergoing a set() stampede
1781  $this->checkAndSetCooloff( $key, $kClass, $value, $elapsed, $hasLock )
1782  ) {
1783  // If the key is write-holed then use the (volatile) interim key as an alternative
1784  if ( $isKeyTombstoned ) {
1785  $this->setInterimValue(
1786  $key,
1787  $value,
1788  $lockTSE,
1789  $version,
1790  $walltime,
1791  $segmentable
1792  );
1793  } else {
1794  $this->setMainValue(
1795  $key,
1796  $value,
1797  $ttl,
1798  $version,
1799  $walltime,
1800  // @phan-suppress-next-line PhanCoalescingAlwaysNull
1801  $setOpts['lag'] ?? 0,
1802  // @phan-suppress-next-line PhanCoalescingAlwaysNull
1803  $setOpts['since'] ?? $preCallbackTime,
1804  // @phan-suppress-next-line PhanCoalescingAlwaysNull
1805  $setOpts['pending'] ?? false,
1806  $lockTSE,
1807  $staleTTL,
1808  $segmentable,
1809  ( $curValue === false )
1810  );
1811  }
1812  }
1813 
1814  $this->yieldStampedeLock( $key, $hasLock );
1815 
1816  $miss = is_infinite( $minAsOf ) ? 'renew' : 'miss';
1817  $this->logger->debug( "fetchOrRegenerate($key): $miss, new value computed" );
1818  $this->stats->timing(
1819  "wanobjectcache.$kClass.$miss.compute",
1820  1e3 * ( $this->getCurrentTime() - $startTime )
1821  );
1822 
1823  return [ $value, $version, $curState[self::RES_AS_OF] ];
1824  }
1825 
1830  private function claimStampedeLock( $key ) {
1831  $checkSisterKey = $this->makeSisterKey( $key, self::TYPE_MUTEX );
1832  // Note that locking is not bypassed due to I/O errors; this avoids stampedes
1833  return $this->cache->add( $checkSisterKey, 1, self::LOCK_TTL );
1834  }
1835 
1840  private function yieldStampedeLock( $key, $hasLock ) {
1841  if ( $hasLock ) {
1842  $checkSisterKey = $this->makeSisterKey( $key, self::TYPE_MUTEX );
1843  $this->cache->delete( $checkSisterKey, $this->cache::WRITE_BACKGROUND );
1844  }
1845  }
1846 
1857  private function makeSisterKeys( array $baseKeys, string $type, string $route = null ) {
1858  $sisterKeys = [];
1859  foreach ( $baseKeys as $baseKey ) {
1860  $sisterKeys[] = $this->makeSisterKey( $baseKey, $type, $route );
1861  }
1862 
1863  return $sisterKeys;
1864  }
1865 
1876  private function makeSisterKey( string $baseKey, string $typeChar, string $route = null ) {
1877  if ( $this->coalesceScheme === self::SCHEME_HASH_STOP ) {
1878  // Key style: "WANCache:<base key>|#|<character>"
1879  $sisterKey = 'WANCache:' . $baseKey . '|#|' . $typeChar;
1880  } else {
1881  // Key style: "WANCache:{<base key>}:<character>"
1882  $sisterKey = 'WANCache:{' . $baseKey . '}:' . $typeChar;
1883  }
1884 
1885  if ( $route !== null ) {
1886  $sisterKey = $this->prependRoute( $sisterKey, $route );
1887  }
1888 
1889  return $sisterKey;
1890  }
1891 
1898  public static function getCollectionFromSisterKey( string $sisterKey ) {
1899  if ( substr( $sisterKey, -4 ) === '|#|v' ) {
1900  // Key style: "WANCache:<base key>|#|<character>"
1901  $collection = substr( $sisterKey, 9, strcspn( $sisterKey, ':|', 9 ) );
1902  } elseif ( substr( $sisterKey, -3 ) === '}:v' ) {
1903  // Key style: "WANCache:{<base key>}:<character>"
1904  $collection = substr( $sisterKey, 10, strcspn( $sisterKey, ':}', 10 ) );
1905  } else {
1906  $collection = 'internal';
1907  }
1908 
1909  return $collection;
1910  }
1911 
1924  private function isExtremelyNewValue( $res, $minAsOf, $now ) {
1925  if ( $res[self::RES_VALUE] === false || $res[self::RES_AS_OF] < $minAsOf ) {
1926  return false;
1927  }
1928 
1929  $age = $now - $res[self::RES_AS_OF];
1930 
1931  return ( $age < mt_rand( self::RECENT_SET_LOW_MS, self::RECENT_SET_HIGH_MS ) / 1e3 );
1932  }
1933 
1955  private function checkAndSetCooloff( $key, $kClass, $value, $elapsed, $hasLock ) {
1956  if ( is_scalar( $value ) ) {
1957  // Roughly estimate the size of the value once serialized
1958  $hypotheticalSize = strlen( (string)$value );
1959  } else {
1960  // Treat the value is a generic sizable object
1961  $hypotheticalSize = $this->keyHighByteSize;
1962  }
1963 
1964  if ( !$hasLock ) {
1965  // Suppose that this cache key is very popular (KEY_HIGH_QPS reads/second).
1966  // After eviction, there will be cache misses until it gets regenerated and saved.
1967  // If the time window when the key is missing lasts less than one second, then the
1968  // number of misses will not reach KEY_HIGH_QPS. This window largely corresponds to
1969  // the key regeneration time. Estimate the count/rate of cache misses, e.g.:
1970  // - 100 QPS, 20ms regeneration => ~2 misses (< 1s)
1971  // - 100 QPS, 100ms regeneration => ~10 misses (< 1s)
1972  // - 100 QPS, 3000ms regeneration => ~300 misses (100/s for 3s)
1973  $missesPerSecForHighQPS = ( min( $elapsed, 1 ) * $this->keyHighQps );
1974 
1975  // Determine whether there is enough I/O stampede risk to justify throttling set().
1976  // Estimate unthrottled set() overhead, as bps, from miss count/rate and value size,
1977  // comparing it to the per-key uplink bps limit (KEY_HIGH_UPLINK_BPS), e.g.:
1978  // - 2 misses (< 1s), 10KB value, 1250000 bps limit => 160000 bits (low risk)
1979  // - 2 misses (< 1s), 100KB value, 1250000 bps limit => 1600000 bits (high risk)
1980  // - 10 misses (< 1s), 10KB value, 1250000 bps limit => 800000 bits (low risk)
1981  // - 10 misses (< 1s), 100KB value, 1250000 bps limit => 8000000 bits (high risk)
1982  // - 300 misses (100/s), 1KB value, 1250000 bps limit => 800000 bps (low risk)
1983  // - 300 misses (100/s), 10KB value, 1250000 bps limit => 8000000 bps (high risk)
1984  // - 300 misses (100/s), 100KB value, 1250000 bps limit => 80000000 bps (high risk)
1985  if ( ( $missesPerSecForHighQPS * $hypotheticalSize ) >= $this->keyHighUplinkBps ) {
1986  $cooloffSisterKey = $this->makeSisterKey( $key, self::TYPE_COOLOFF );
1987  $watchPoint = $this->cache->watchErrors();
1988  if (
1989  !$this->cache->add( $cooloffSisterKey, 1, self::COOLOFF_TTL ) &&
1990  // Don't treat failures due to I/O errors as the key being in cool-off
1991  $this->cache->getLastError( $watchPoint ) === self::ERR_NONE
1992  ) {
1993  $this->logger->debug( "checkAndSetCooloff($key): bounced; {$elapsed}s" );
1994  $this->stats->increment( "wanobjectcache.$kClass.cooloff_bounce" );
1995 
1996  return false;
1997  }
1998  }
1999  }
2000 
2001  // Corresponding metrics for cache writes that actually get sent over the write
2002  $this->stats->timing( "wanobjectcache.$kClass.regen_set_delay", 1e3 * $elapsed );
2003  $this->stats->updateCount( "wanobjectcache.$kClass.regen_set_bytes", $hypotheticalSize );
2004 
2005  return true;
2006  }
2007 
2017  private function getInterimValue( $key, $minAsOf, $now, $touchedCb ) {
2018  if ( $this->useInterimHoldOffCaching ) {
2019  $interimSisterKey = $this->makeSisterKey( $key, self::TYPE_INTERIM );
2020  $wrapped = $this->cache->get( $interimSisterKey );
2021  $res = $this->unwrap( $wrapped, $now );
2022  if ( $res[self::RES_VALUE] !== false && $res[self::RES_AS_OF] >= $minAsOf ) {
2023  if ( $touchedCb !== null ) {
2024  // Update "last purge time" since the $touchedCb timestamp depends on $value
2025  // Get the new "touched timestamp", accounting for callback-checked dependencies
2026  $res[self::RES_TOUCH_AS_OF] = max(
2027  $touchedCb( $res[self::RES_VALUE] ),
2028  $res[self::RES_TOUCH_AS_OF]
2029  );
2030  }
2031 
2032  return $res;
2033  }
2034  }
2035 
2036  return $this->unwrap( false, $now );
2037  }
2038 
2048  private function setInterimValue(
2049  $key,
2050  $value,
2051  $ttl,
2052  ?int $version,
2053  float $walltime,
2054  bool $segmentable
2055  ) {
2056  $now = $this->getCurrentTime();
2057  $ttl = max( self::INTERIM_KEY_TTL, (int)$ttl );
2058 
2059  // Wrap that value with time/TTL/version metadata
2060  $wrapped = $this->wrap( $value, $ttl, $version, $now, $walltime );
2061 
2062  $flags = $this->cache::WRITE_BACKGROUND;
2063  if ( $segmentable ) {
2064  $flags |= $this->cache::WRITE_ALLOW_SEGMENTS;
2065  }
2066 
2067  return $this->cache->set(
2068  $this->makeSisterKey( $key, self::TYPE_INTERIM ),
2069  $wrapped,
2070  $ttl,
2071  $flags
2072  );
2073  }
2074 
2079  private function resolveBusyValue( $busyValue ) {
2080  return ( $busyValue instanceof Closure ) ? $busyValue() : $busyValue;
2081  }
2082 
2148  final public function getMultiWithSetCallback(
2149  ArrayIterator $keyedIds, $ttl, callable $callback, array $opts = []
2150  ) {
2151  // Batch load required keys into the in-process warmup cache
2152  $this->warmupCache = $this->fetchWrappedValuesForWarmupCache(
2153  $this->getNonProcessCachedMultiKeys( $keyedIds, $opts ),
2154  $opts['checkKeys'] ?? []
2155  );
2156  $this->warmupKeyMisses = 0;
2157 
2158  // The required callback signature includes $id as the first argument for convenience
2159  // to distinguish different items. To reuse the code in getWithSetCallback(), wrap the
2160  // callback with a proxy callback that has the standard getWithSetCallback() signature.
2161  // This is defined only once per batch to avoid closure creation overhead.
2162  $proxyCb = static function ( $oldValue, &$ttl, &$setOpts, $oldAsOf, $params )
2163  use ( $callback )
2164  {
2165  return $callback( $params['id'], $oldValue, $ttl, $setOpts, $oldAsOf );
2166  };
2167 
2168  // Get the order-preserved result map using the warm-up cache
2169  $values = [];
2170  foreach ( $keyedIds as $key => $id ) {
2171  $values[$key] = $this->getWithSetCallback(
2172  $key,
2173  $ttl,
2174  $proxyCb,
2175  $opts,
2176  [ 'id' => $id ]
2177  );
2178  }
2179 
2180  $this->warmupCache = [];
2181 
2182  return $values;
2183  }
2184 
2251  final public function getMultiWithUnionSetCallback(
2252  ArrayIterator $keyedIds, $ttl, callable $callback, array $opts = []
2253  ) {
2254  $checkKeys = $opts['checkKeys'] ?? [];
2255  $minAsOf = $opts['minAsOf'] ?? self::MIN_TIMESTAMP_NONE;
2256 
2257  // unset incompatible keys
2258  unset( $opts['lockTSE'] );
2259  unset( $opts['busyValue'] );
2260 
2261  // Batch load required keys into the in-process warmup cache
2262  $keysByIdGet = $this->getNonProcessCachedMultiKeys( $keyedIds, $opts );
2263  $this->warmupCache = $this->fetchWrappedValuesForWarmupCache( $keysByIdGet, $checkKeys );
2264  $this->warmupKeyMisses = 0;
2265 
2266  // IDs of entities known to be in need of generation
2267  $idsRegen = [];
2268 
2269  // Find out which keys are missing/deleted/stale
2270  $resByKey = $this->fetchKeys( $keysByIdGet, $checkKeys );
2271  foreach ( $keysByIdGet as $id => $key ) {
2272  $res = $resByKey[$key];
2273  if (
2274  $res[self::RES_VALUE] === false ||
2275  $res[self::RES_CUR_TTL] < 0 ||
2276  $res[self::RES_AS_OF] < $minAsOf
2277  ) {
2278  $idsRegen[] = $id;
2279  }
2280  }
2281 
2282  // Run the callback to populate the generation value map for all required IDs
2283  $newSetOpts = [];
2284  $newTTLsById = array_fill_keys( $idsRegen, $ttl );
2285  $newValsById = $idsRegen ? $callback( $idsRegen, $newTTLsById, $newSetOpts ) : [];
2286 
2287  $method = __METHOD__;
2288  // The required callback signature includes $id as the first argument for convenience
2289  // to distinguish different items. To reuse the code in getWithSetCallback(), wrap the
2290  // callback with a proxy callback that has the standard getWithSetCallback() signature.
2291  // This is defined only once per batch to avoid closure creation overhead.
2292  $proxyCb = function ( $oldValue, &$ttl, &$setOpts, $oldAsOf, $params )
2293  use ( $callback, $newValsById, $newTTLsById, $newSetOpts, $method )
2294  {
2295  $id = $params['id'];
2296 
2297  if ( array_key_exists( $id, $newValsById ) ) {
2298  // Value was already regenerated as expected, so use the value in $newValsById
2299  $newValue = $newValsById[$id];
2300  $ttl = $newTTLsById[$id];
2301  $setOpts = $newSetOpts;
2302  } else {
2303  // Pre-emptive/popularity refresh and version mismatch cases are not detected
2304  // above and thus $newValsById has no entry. Run $callback on this single entity.
2305  $ttls = [ $id => $ttl ];
2306  $result = $callback( [ $id ], $ttls, $setOpts );
2307  if ( !isset( $result[$id] ) ) {
2308  // T303092
2309  $this->logger->warning(
2310  $method . ' failed due to {id} not set in result {result}', [
2311  'id' => $id,
2312  'result' => json_encode( $result )
2313  ] );
2314  }
2315  $newValue = $result[$id];
2316  $ttl = $ttls[$id];
2317  }
2318 
2319  return $newValue;
2320  };
2321 
2322  // Get the order-preserved result map using the warm-up cache
2323  $values = [];
2324  foreach ( $keyedIds as $key => $id ) {
2325  $values[$key] = $this->getWithSetCallback(
2326  $key,
2327  $ttl,
2328  $proxyCb,
2329  $opts,
2330  [ 'id' => $id ]
2331  );
2332  }
2333 
2334  $this->warmupCache = [];
2335 
2336  return $values;
2337  }
2338 
2349  public function makeGlobalKey( $collection, ...$components ) {
2350  // @phan-suppress-next-line PhanParamTooFewUnpack Should infer non-emptiness
2351  return $this->cache->makeGlobalKey( ...func_get_args() );
2352  }
2353 
2364  public function makeKey( $collection, ...$components ) {
2365  // @phan-suppress-next-line PhanParamTooFewUnpack Should infer non-emptiness
2366  return $this->cache->makeKey( ...func_get_args() );
2367  }
2368 
2376  public function hash256( $component ) {
2377  return hash_hmac( 'sha256', $component, $this->secret );
2378  }
2379 
2431  final public function makeMultiKeys( array $ids, $keyCallback ) {
2432  $idByKey = [];
2433  foreach ( $ids as $id ) {
2434  // Discourage triggering of automatic makeKey() hashing in some backends
2435  if ( strlen( $id ) > 64 ) {
2436  $this->logger->warning( __METHOD__ . ": long ID '$id'; use hash256()" );
2437  }
2438  $key = $keyCallback( $id, $this );
2439  // Edge case: ignore key collisions due to duplicate $ids like "42" and 42
2440  if ( !isset( $idByKey[$key] ) ) {
2441  $idByKey[$key] = $id;
2442  } elseif ( (string)$id !== (string)$idByKey[$key] ) {
2443  throw new UnexpectedValueException(
2444  "Cache key collision; IDs ('$id','{$idByKey[$key]}') map to '$key'"
2445  );
2446  }
2447  }
2448 
2449  return new ArrayIterator( $idByKey );
2450  }
2451 
2487  final public function multiRemap( array $ids, array $res ) {
2488  if ( count( $ids ) !== count( $res ) ) {
2489  // If makeMultiKeys() is called on a list of non-unique IDs, then the resulting
2490  // ArrayIterator will have less entries due to "first appearance" de-duplication
2491  $ids = array_keys( array_fill_keys( $ids, true ) );
2492  if ( count( $ids ) !== count( $res ) ) {
2493  throw new UnexpectedValueException( "Multi-key result does not match ID list" );
2494  }
2495  }
2496 
2497  return array_combine( $ids, $res );
2498  }
2499 
2506  public function watchErrors() {
2507  return $this->cache->watchErrors();
2508  }
2509 
2527  final public function getLastError( $watchPoint = 0 ) {
2528  $code = $this->cache->getLastError( $watchPoint );
2529  switch ( $code ) {
2530  case self::ERR_NONE:
2531  return self::ERR_NONE;
2532  case self::ERR_NO_RESPONSE:
2533  return self::ERR_NO_RESPONSE;
2534  case self::ERR_UNREACHABLE:
2535  return self::ERR_UNREACHABLE;
2536  default:
2537  return self::ERR_UNEXPECTED;
2538  }
2539  }
2540 
2545  final public function clearLastError() {
2546  $this->cache->clearLastError();
2547  }
2548 
2554  public function clearProcessCache() {
2555  $this->processCaches = [];
2556  }
2557 
2578  final public function useInterimHoldOffCaching( $enabled ) {
2579  $this->useInterimHoldOffCaching = $enabled;
2580  }
2581 
2587  public function getQoS( $flag ) {
2588  return $this->cache->getQoS( $flag );
2589  }
2590 
2654  public function adaptiveTTL( $mtime, $maxTTL, $minTTL = 30, $factor = 0.2 ) {
2655  // handle fractional seconds and string integers
2656  $mtime = (int)$mtime;
2657  if ( $mtime <= 0 ) {
2658  // no last-modified time provided
2659  return $minTTL;
2660  }
2661 
2662  $age = (int)$this->getCurrentTime() - $mtime;
2663 
2664  return (int)min( $maxTTL, max( $minTTL, $factor * $age ) );
2665  }
2666 
2672  final public function getWarmupKeyMisses() {
2673  // Number of misses in $this->warmupCache during the last call to certain methods
2674  return $this->warmupKeyMisses;
2675  }
2676 
2691  protected function relayVolatilePurge( string $sisterKey, string $purgeValue, int $ttl ) {
2692  if ( $this->broadcastRoute !== null ) {
2693  $routeKey = $this->prependRoute( $sisterKey, $this->broadcastRoute );
2694  } else {
2695  $routeKey = $sisterKey;
2696  }
2697 
2698  return $this->cache->set(
2699  $routeKey,
2700  $purgeValue,
2701  $ttl,
2702  $this->cache::WRITE_BACKGROUND
2703  );
2704  }
2705 
2714  protected function relayNonVolatilePurge( string $sisterKey ) {
2715  if ( $this->broadcastRoute !== null ) {
2716  $routeKey = $this->prependRoute( $sisterKey, $this->broadcastRoute );
2717  } else {
2718  $routeKey = $sisterKey;
2719  }
2720 
2721  return $this->cache->delete( $routeKey, $this->cache::WRITE_BACKGROUND );
2722  }
2723 
2729  protected function prependRoute( string $sisterKey, string $route ) {
2730  if ( $sisterKey[0] === '/' ) {
2731  throw new RuntimeException( "Sister key '$sisterKey' already contains a route." );
2732  }
2733 
2734  return $route . $sisterKey;
2735  }
2736 
2748  private function scheduleAsyncRefresh( $key, $ttl, $callback, array $opts, array $cbParams ) {
2749  if ( !$this->asyncHandler ) {
2750  return false;
2751  }
2752  // Update the cache value later, such during post-send of an HTTP request. This forces
2753  // cache regeneration by setting "minAsOf" to infinity, meaning that no existing value
2754  // is considered valid. Furthermore, note that preemptive regeneration is not applicable
2755  // to invalid values, so there is no risk of infinite preemptive regeneration loops.
2756  $func = $this->asyncHandler;
2757  $func( function () use ( $key, $ttl, $callback, $opts, $cbParams ) {
2758  $opts['minAsOf'] = INF;
2759  try {
2760  $this->fetchOrRegenerate( $key, $ttl, $callback, $opts, $cbParams );
2761  } catch ( Exception $e ) {
2762  // Log some context for easier debugging
2763  $this->logger->error( 'Async refresh failed for {key}', [
2764  'key' => $key,
2765  'ttl' => $ttl,
2766  'exception' => $e
2767  ] );
2768  throw $e;
2769  }
2770  } );
2771 
2772  return true;
2773  }
2774 
2783  private function isAcceptablyFreshValue( $res, $graceTTL, $minAsOf ) {
2784  if ( !$this->isValid( $res[self::RES_VALUE], $res[self::RES_AS_OF], $minAsOf ) ) {
2785  // Value does not exists or is too old
2786  return false;
2787  }
2788 
2789  $curTTL = $res[self::RES_CUR_TTL];
2790  if ( $curTTL > 0 ) {
2791  // Value is definitely still fresh
2792  return true;
2793  }
2794 
2795  // Remaining seconds during which this stale value can be used
2796  $curGraceTTL = $graceTTL + $curTTL;
2797 
2798  return ( $curGraceTTL > 0 )
2799  // Chance of using the value decreases as $curTTL goes from 0 to -$graceTTL
2800  ? !$this->worthRefreshExpiring( $curGraceTTL, $graceTTL, $graceTTL )
2801  // Value is too stale to fall in the grace period
2802  : false;
2803  }
2804 
2815  protected function isLotteryRefreshDue( $res, $lowTTL, $ageNew, $hotTTR, $now ) {
2816  $curTTL = $res[self::RES_CUR_TTL];
2817  $logicalTTL = $res[self::RES_TTL];
2818  $asOf = $res[self::RES_AS_OF];
2819 
2820  return (
2821  $this->worthRefreshExpiring( $curTTL, $logicalTTL, $lowTTL ) ||
2822  $this->worthRefreshPopular( $asOf, $ageNew, $hotTTR, $now )
2823  );
2824  }
2825 
2841  protected function worthRefreshPopular( $asOf, $ageNew, $timeTillRefresh, $now ) {
2842  if ( $ageNew < 0 || $timeTillRefresh <= 0 ) {
2843  return false;
2844  }
2845 
2846  $age = $now - $asOf;
2847  $timeOld = $age - $ageNew;
2848  if ( $timeOld <= 0 ) {
2849  return false;
2850  }
2851 
2852  $popularHitsPerSec = 1;
2853  // Lifecycle is: new, ramp-up refresh chance, full refresh chance.
2854  // Note that the "expected # of refreshes" for the ramp-up time range is half
2855  // of what it would be if P(refresh) was at its full value during that time range.
2856  $refreshWindowSec = max( $timeTillRefresh - $ageNew - self::RAMPUP_TTL / 2, 1 );
2857  // P(refresh) * (# hits in $refreshWindowSec) = (expected # of refreshes)
2858  // P(refresh) * ($refreshWindowSec * $popularHitsPerSec) = 1 (by definition)
2859  // P(refresh) = 1/($refreshWindowSec * $popularHitsPerSec)
2860  $chance = 1 / ( $popularHitsPerSec * $refreshWindowSec );
2861  // Ramp up $chance from 0 to its nominal value over RAMPUP_TTL seconds to avoid stampedes
2862  $chance *= ( $timeOld <= self::RAMPUP_TTL ) ? $timeOld / self::RAMPUP_TTL : 1;
2863 
2864  return ( mt_rand( 1, 1000000000 ) <= 1000000000 * $chance );
2865  }
2866 
2885  protected function worthRefreshExpiring( $curTTL, $logicalTTL, $lowTTL ) {
2886  if ( $lowTTL <= 0 ) {
2887  return false;
2888  }
2889  // T264787: avoid having keys start off with a high chance of being refreshed;
2890  // the point where refreshing becomes possible cannot precede the key lifetime.
2891  $effectiveLowTTL = min( $lowTTL, $logicalTTL ?: INF );
2892 
2893  // How long the value was in the "low TTL" phase
2894  $timeOld = $effectiveLowTTL - $curTTL;
2895  if ( $timeOld <= 0 || $timeOld >= $effectiveLowTTL ) {
2896  return false;
2897  }
2898 
2899  // Ratio of the low TTL phase that has elapsed (r)
2900  $ttrRatio = $timeOld / $effectiveLowTTL;
2901  // Use p(r) as the monotonically increasing "chance of refresh" function,
2902  // having p(0)=0 and p(1)=1. The value expires at the nominal expiry.
2903  $chance = $ttrRatio ** 4;
2904 
2905  return ( mt_rand( 1, 1000000000 ) <= 1000000000 * $chance );
2906  }
2907 
2916  protected function isValid( $value, $asOf, $minAsOf ) {
2917  return ( $value !== false && $asOf >= $minAsOf );
2918  }
2919 
2928  private function wrap( $value, $ttl, $version, $now, $walltime ) {
2929  // Returns keys in ascending integer order for PHP7 array packing:
2930  // https://nikic.github.io/2014/12/22/PHPs-new-hashtable-implementation.html
2931  $wrapped = [
2932  self::FLD_FORMAT_VERSION => self::VERSION,
2933  self::FLD_VALUE => $value,
2934  self::FLD_TTL => $ttl,
2935  self::FLD_TIME => $now
2936  ];
2937  if ( $version !== null ) {
2938  $wrapped[self::FLD_VALUE_VERSION] = $version;
2939  }
2940 
2941  return $wrapped;
2942  }
2943 
2958  private function unwrap( $wrapped, $now ) {
2959  // https://nikic.github.io/2014/12/22/PHPs-new-hashtable-implementation.html
2960  $res = [
2961  // Attributes that only depend on the fetched key value
2962  self::RES_VALUE => false,
2963  self::RES_VERSION => null,
2964  self::RES_AS_OF => null,
2965  self::RES_TTL => null,
2966  self::RES_TOMB_AS_OF => null,
2967  // Attributes that depend on caller-specific "check" keys or "touched callbacks"
2968  self::RES_CHECK_AS_OF => null,
2969  self::RES_TOUCH_AS_OF => null,
2970  self::RES_CUR_TTL => null
2971  ];
2972 
2973  if ( is_array( $wrapped ) ) {
2974  // Entry expected to be a cached value; validate it
2975  if (
2976  ( $wrapped[self::FLD_FORMAT_VERSION] ?? null ) === self::VERSION &&
2977  $wrapped[self::FLD_TIME] >= $this->epoch
2978  ) {
2979  if ( $wrapped[self::FLD_TTL] > 0 ) {
2980  // Get the approximate time left on the key
2981  $age = $now - $wrapped[self::FLD_TIME];
2982  $curTTL = max( $wrapped[self::FLD_TTL] - $age, 0.0 );
2983  } else {
2984  // Key had no TTL, so the time left is unbounded
2985  $curTTL = INF;
2986  }
2987  $res[self::RES_VALUE] = $wrapped[self::FLD_VALUE];
2988  $res[self::RES_VERSION] = $wrapped[self::FLD_VALUE_VERSION] ?? null;
2989  $res[self::RES_AS_OF] = $wrapped[self::FLD_TIME];
2990  $res[self::RES_CUR_TTL] = $curTTL;
2991  $res[self::RES_TTL] = $wrapped[self::FLD_TTL];
2992  }
2993  } else {
2994  // Entry expected to be a tombstone; parse it
2995  $purge = $this->parsePurgeValue( $wrapped );
2996  if ( $purge !== null ) {
2997  // Tombstoned keys should always have a negative "current TTL"
2998  $curTTL = min( $purge[self::PURGE_TIME] - $now, self::TINY_NEGATIVE );
2999  $res[self::RES_CUR_TTL] = $curTTL;
3000  $res[self::RES_TOMB_AS_OF] = $purge[self::PURGE_TIME];
3001  }
3002  }
3003 
3004  return $res;
3005  }
3006 
3011  private function determineKeyClassForStats( $key ) {
3012  $parts = explode( ':', $key, 3 );
3013  // Fallback in case the key was not made by makeKey.
3014  // Replace dots because they are special in StatsD (T232907)
3015  return strtr( $parts[1] ?? $parts[0], '.', '_' );
3016  }
3017 
3026  private function parsePurgeValue( $value ) {
3027  if ( !is_string( $value ) ) {
3028  return null;
3029  }
3030 
3031  $segments = explode( ':', $value, 3 );
3032  $prefix = $segments[0];
3033  if ( $prefix !== self::PURGE_VAL_PREFIX ) {
3034  // Not a purge value
3035  return null;
3036  }
3037 
3038  $timestamp = (float)$segments[1];
3039  // makeTombstonePurgeValue() doesn't store hold-off TTLs
3040  $holdoff = isset( $segments[2] ) ? (int)$segments[2] : self::HOLDOFF_TTL;
3041 
3042  if ( $timestamp < $this->epoch ) {
3043  // Purge value is too old
3044  return null;
3045  }
3046 
3047  return [ self::PURGE_TIME => $timestamp, self::PURGE_HOLDOFF => $holdoff ];
3048  }
3049 
3054  private function makeTombstonePurgeValue( float $timestamp ) {
3055  return self::PURGE_VAL_PREFIX . ':' . (int)$timestamp;
3056  }
3057 
3064  private function makeCheckPurgeValue( float $timestamp, int $holdoff, array &$purge = null ) {
3065  $normalizedTime = (int)$timestamp;
3066  // Purge array that matches what parsePurgeValue() would have returned
3067  $purge = [ self::PURGE_TIME => (float)$normalizedTime, self::PURGE_HOLDOFF => $holdoff ];
3068 
3069  return self::PURGE_VAL_PREFIX . ":$normalizedTime:$holdoff";
3070  }
3071 
3076  private function getProcessCache( $group ) {
3077  if ( !isset( $this->processCaches[$group] ) ) {
3078  [ , $size ] = explode( ':', $group );
3079  $this->processCaches[$group] = new MapCacheLRU( (int)$size );
3080  if ( $this->wallClockOverride !== null ) {
3081  $this->processCaches[$group]->setMockTime( $this->wallClockOverride );
3082  }
3083  }
3084 
3085  return $this->processCaches[$group];
3086  }
3087 
3093  private function getNonProcessCachedMultiKeys( ArrayIterator $keys, array $opts ) {
3094  $pcTTL = $opts['pcTTL'] ?? self::TTL_UNCACHEABLE;
3095 
3096  $keysMissing = [];
3097  if ( $pcTTL > 0 && $this->callbackDepth == 0 ) {
3098  $pCache = $this->getProcessCache( $opts['pcGroup'] ?? self::PC_PRIMARY );
3099  foreach ( $keys as $key => $id ) {
3100  if ( !$pCache->has( $key, $pcTTL ) ) {
3101  $keysMissing[$id] = $key;
3102  }
3103  }
3104  }
3105 
3106  return $keysMissing;
3107  }
3108 
3115  private function fetchWrappedValuesForWarmupCache( array $keys, array $checkKeys ) {
3116  if ( !$keys ) {
3117  return [];
3118  }
3119 
3120  // Get all the value keys to fetch...
3121  $sisterKeys = $this->makeSisterKeys( $keys, self::TYPE_VALUE );
3122  // Get all the "check" keys to fetch...
3123  foreach ( $checkKeys as $i => $checkKeyOrKeyGroup ) {
3124  // Note: avoid array_merge() inside loop in case there are many keys
3125  if ( is_int( $i ) ) {
3126  // Single "check" key that applies to all value keys
3127  $sisterKeys[] = $this->makeSisterKey( $checkKeyOrKeyGroup, self::TYPE_TIMESTAMP );
3128  } else {
3129  // List of "check" keys that apply to a specific value key
3130  foreach ( (array)$checkKeyOrKeyGroup as $checkKey ) {
3131  $sisterKeys[] = $this->makeSisterKey( $checkKey, self::TYPE_TIMESTAMP );
3132  }
3133  }
3134  }
3135 
3136  $wrappedBySisterKey = $this->cache->getMulti( $sisterKeys );
3137  $wrappedBySisterKey += array_fill_keys( $sisterKeys, false );
3138 
3139  return $wrappedBySisterKey;
3140  }
3141 
3147  private function timeSinceLoggedMiss( $key, $now ) {
3148  for ( end( $this->missLog ); $miss = current( $this->missLog ); prev( $this->missLog ) ) {
3149  if ( $miss[0] === $key ) {
3150  return ( $now - $miss[1] );
3151  }
3152  }
3153 
3154  return null;
3155  }
3156 
3161  protected function getCurrentTime() {
3162  return $this->wallClockOverride ?: microtime( true );
3163  }
3164 
3169  public function setMockTime( &$time ) {
3170  $this->wallClockOverride =& $time;
3171  $this->cache->setMockTime( $time );
3172  foreach ( $this->processCaches as $pCache ) {
3173  $pCache->setMockTime( $time );
3174  }
3175  }
3176 }
A BagOStuff object with no objects in it.
Handles a simple LRU key/value map with a maximum number of entries.
Definition: MapCacheLRU.php:36
Multi-datacenter aware caching interface.
makeGlobalKey( $collection,... $components)
Make a cache key for the global keyspace and given components.
const HOLDOFF_TTL
Seconds to tombstone keys on delete() and to treat keys as volatile after purges.
const KEY_VERSION
Version number attribute for a key; keep value for b/c (< 1.36)
__construct(array $params)
isValid( $value, $asOf, $minAsOf)
Check that a wrapper value exists and has an acceptable age.
worthRefreshPopular( $asOf, $ageNew, $timeTillRefresh, $now)
Check if a key is due for randomized regeneration due to its popularity.
multiRemap(array $ids, array $res)
Get an (ID => value) map from (i) a non-unique list of entity IDs, and (ii) the list of corresponding...
relayVolatilePurge(string $sisterKey, string $purgeValue, int $ttl)
Set a sister key to a purge value in all datacenters.
prependRoute(string $sisterKey, string $route)
touchCheckKey( $key, $holdoff=self::HOLDOFF_TTL)
Increase the last-purge timestamp of a "check" key in all datacenters.
adaptiveTTL( $mtime, $maxTTL, $minTTL=30, $factor=0.2)
Get a TTL that is higher for objects that have not changed recently.
const GRACE_TTL_NONE
Idiom for set()/getWithSetCallback() meaning "no post-expiration grace period".
BagOStuff $cache
The local datacenter cache.
fetchKeys(array $keys, array $checkKeys, $touchedCb=null)
Fetch the value and key metadata of several keys from cache.
getWithSetCallback( $key, $ttl, $callback, array $opts=[], array $cbParams=[])
Method to fetch/regenerate a cache key.
getCheckKeyTime( $key)
Fetch the value of a timestamp "check" key.
getMulti(array $keys, &$curTTLs=[], array $checkKeys=[], &$info=[])
Fetch the value of several keys from cache.
getMultiWithUnionSetCallback(ArrayIterator $keyedIds, $ttl, callable $callback, array $opts=[])
Method to fetch/regenerate multiple cache keys at once.
LoggerInterface $logger
relayNonVolatilePurge(string $sisterKey)
Remove a sister key from all datacenters.
getMultiWithSetCallback(ArrayIterator $keyedIds, $ttl, callable $callback, array $opts=[])
Method to fetch multiple cache keys at once with regeneration.
makeMultiKeys(array $ids, $keyCallback)
Get an iterator of (cache key => entity ID) for a list of entity IDs.
static newEmpty()
Get an instance that wraps EmptyBagOStuff.
int $coalesceScheme
Scheme to use for key coalescing (Hash Tags or Hash Stops)
isLotteryRefreshDue( $res, $lowTTL, $ageNew, $hotTTR, $now)
Check if a key is due for randomized regeneration due to near-expiration/popularity.
watchErrors()
Get a "watch point" token that can be used to get the "last error" to occur after now.
bool $useInterimHoldOffCaching
Whether to use "interim" caching while keys are tombstoned.
worthRefreshExpiring( $curTTL, $logicalTTL, $lowTTL)
Check if a key is nearing expiration and thus due for randomized regeneration.
const HOLDOFF_TTL_NONE
Idiom for delete()/touchCheckKey() meaning "no hold-off period".
useInterimHoldOffCaching( $enabled)
Enable or disable the use of brief caching for tombstoned keys.
StatsdDataFactoryInterface $stats
clearProcessCache()
Clear the in-process caches; useful for testing.
const KEY_AS_OF
Generation completion timestamp attribute for a key; keep value for b/c (< 1.36)
getLastError( $watchPoint=0)
Get the "last error" registry.
makeKey( $collection,... $components)
Make a cache key using the "global" keyspace for the given components.
float $epoch
Unix timestamp of the oldest possible valid values.
callable null $asyncHandler
Function that takes a WAN cache callback and runs it later.
string null $broadcastRoute
Routing prefix for operations that should be broadcasted to all data centers.
setLogger(LoggerInterface $logger)
static getCollectionFromSisterKey(string $sisterKey)
const PASS_BY_REF
Idiom for get()/getMulti() to return extra information by reference.
const KEY_CHECK_AS_OF
Highest "check" key timestamp for a key; keep value for b/c (< 1.36)
clearLastError()
Clear the "last error" registry.
const STALE_TTL_NONE
Idiom for set()/getWithSetCallback() meaning "no post-expiration persistence".
MapCacheLRU[] $processCaches
Map of group PHP instance caches.
string $secret
Stable secret used for hashing long strings into key components.
resetCheckKey( $key)
Clear the last-purge timestamp of a "check" key in all datacenters.
const KEY_TOMB_AS_OF
Tomstone timestamp attribute for a key; keep value for b/c (< 1.36)
const KEY_CUR_TTL
Remaining TTL attribute for a key; keep value for b/c (< 1.36)
const TTL_LAGGED
Max TTL, in seconds, to store keys when a data source has high replication lag.
hash256( $component)
Hash a possibly long string into a suitable component for makeKey()/makeGlobalKey()
getMultiCheckKeyTime(array $keys)
Fetch the values of each timestamp "check" key.
const KEY_TTL
Logical TTL attribute for a key.
Generic interface for object stores with key encoding methods.
Generic interface providing Time-To-Live constants for expirable object storage.
Generic interface providing error code and quality-of-service constants for object stores.
const ERR_UNREACHABLE
Storage medium could not be reached to establish a connection.
const ERR_UNEXPECTED
Storage medium operation failed due to usage limitations or an I/O error.
const ERR_NO_RESPONSE
Storage medium failed to yield a complete response to an operation.