29use Psr\Log\LoggerAwareInterface;
30use Psr\Log\LoggerInterface;
31use Psr\Log\NullLogger;
32use Wikimedia\ScopedCallback;
33use Wikimedia\WaitConditionLoop;
115 if ( isset(
$params[
'logger'] ) ) {
121 if ( isset(
$params[
'keyspace'] ) ) {
122 $this->keyspace =
$params[
'keyspace'];
125 $this->asyncHandler =
$params[
'asyncHandler'] ??
null;
127 if ( !empty(
$params[
'reportDupes'] ) && is_callable( $this->asyncHandler ) ) {
128 $this->reportDupes =
true;
131 $this->syncTimeout =
$params[
'syncTimeout'] ?? 3;
139 $this->logger = $logger;
146 $this->debugMode = $bool;
162 $value = $this->
get( $key, $flags );
165 if ( !is_callable( $callback ) ) {
166 throw new InvalidArgumentException(
"Invalid cache miss callback provided." );
168 $value = call_user_func( $callback );
170 $this->
set( $key,
$value, $ttl );
191 public function get( $key, $flags = 0, $oldFlags = null ) {
193 $flags = is_int( $oldFlags ) ? $oldFlags : $flags;
197 return $this->
doGet( $key, $flags );
205 if ( !$this->reportDupes ) {
209 if ( !isset( $this->duplicateKeyLookups[$key] ) ) {
212 $this->duplicateKeyLookups[$key] = 0;
214 $this->duplicateKeyLookups[$key] += 1;
216 if ( $this->dupeTrackScheduled ===
false ) {
217 $this->dupeTrackScheduled =
true;
219 call_user_func( $this->asyncHandler,
function () {
220 $dups = array_filter( $this->duplicateKeyLookups );
221 foreach ( $dups
as $key => $count ) {
222 $this->logger->warning(
223 'Duplicate get(): "{key}" fetched {count} times',
225 [
'key' => $key,
'count' => $count + 1, ]
238 abstract protected function doGet( $key, $flags = 0 );
250 throw new Exception( __METHOD__ .
' not implemented.' );
262 abstract public function set( $key,
$value, $exptime = 0, $flags = 0 );
270 abstract public function delete( $key );
288 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
289 return $this->
mergeViaLock( $key, $callback, $exptime, $attempts, $flags );
301 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
305 $this->reportDupes =
false;
307 $currentValue = $this->
getWithToken( $key, $casToken, self::READ_LATEST );
311 $this->logger->warning(
312 __METHOD__ .
' failed due to I/O error on get() for {key}.',
320 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
325 } elseif ( $currentValue ===
false ) {
333 $this->logger->warning(
334 __METHOD__ .
' failed due to I/O error for {key}.',
340 }
while ( !
$success && --$attempts );
355 protected function cas( $casToken, $key,
$value, $exptime = 0 ) {
356 if ( !$this->
lock( $key, 0 ) ) {
361 $this->
getWithToken( $key, $curCasToken, self::READ_LATEST );
362 if ( $casToken === $curCasToken ) {
366 __METHOD__ .
' failed due to race condition for {key}.',
388 protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
389 if ( $attempts <= 1 ) {
395 if ( !$this->
lock( $key, $timeout ) ) {
401 $this->reportDupes =
false;
402 $currentValue = $this->
get( $key, self::READ_LATEST );
406 $this->logger->warning(
407 __METHOD__ .
' failed due to I/O error on get() for {key}.',
414 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
422 if ( !$this->
unlock( $key ) ) {
424 trigger_error(
"Could not release lock for key '$key'." );
439 $value = $this->
get( $key );
455 public function lock( $key, $timeout = 6, $expiry = 6, $rclass =
'' ) {
457 if ( isset( $this->locks[$key] ) ) {
458 if ( $rclass !=
'' && $this->locks[$key][
'class'] === $rclass ) {
459 ++$this->locks[$key][
'depth'];
467 $expiry = min( $expiry ?: INF, self::TTL_DAY );
468 $loop =
new WaitConditionLoop(
469 function ()
use ( $key, $timeout, $expiry,
$fname ) {
471 if ( $this->
add(
"{$key}:lock", 1, $expiry ) ) {
474 $this->logger->warning(
475 $fname .
' failed due to I/O error for {key}.',
479 return WaitConditionLoop::CONDITION_ABORTED;
482 return WaitConditionLoop::CONDITION_CONTINUE;
487 $code = $loop->invoke();
488 $locked = (
$code === $loop::CONDITION_REACHED );
490 $this->locks[$key] = [
'class' => $rclass,
'depth' => 1 ];
491 } elseif (
$code === $loop::CONDITION_TIMED_OUT ) {
492 $this->logger->warning(
493 "$fname failed due to timeout for {key}.",
494 [
'key' => $key,
'timeout' => $timeout ]
508 if ( isset( $this->locks[$key] ) && --$this->locks[$key][
'depth'] <= 0 ) {
509 unset( $this->locks[$key] );
511 $ok = $this->
delete(
"{$key}:lock" );
513 $this->logger->warning(
514 __METHOD__ .
' failed to release lock for {key}.',
541 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass =
'' ) {
542 $expiry = min( $expiry ?: INF, self::TTL_DAY );
544 if ( !$this->
lock( $key, $timeout, $expiry, $rclass ) ) {
550 return new ScopedCallback(
function ()
use ( $key, $lSince, $expiry ) {
553 if ( ( $age + $latency ) >= $expiry ) {
554 $this->logger->warning(
555 "Lock for {key} held too long ({age} sec).",
556 [
'key' => $key,
'age' => $age ]
587 $val = $this->
get( $key );
588 if ( $val !==
false ) {
604 foreach ( $data
as $key =>
$value ) {
605 if ( !$this->
set( $key,
$value, $exptime ) ) {
620 if ( $this->
get( $key ) ===
false ) {
621 return $this->
set( $key,
$value, $exptime );
633 if ( !$this->
lock( $key, 1 ) ) {
636 $n = $this->
get( $key );
639 $this->
set( $key, max( 0, $n ) );
675 $newValue = $this->
add( $key, (
int)$init, $ttl ) ? $init :
false;
691 return $this->lastError;
699 $this->lastError = self::ERR_NONE;
708 $this->lastError = $err;
732 $this->busyCallbacks[] = $workCallback;
757 if ( $this->debugMode ) {
758 $this->logger->debug(
"{class} debug: $text", [
759 'class' => static::class,
770 if ( $exptime != 0 && $exptime < ( 10 * self::TTL_YEAR ) ) {
785 if ( $exptime >= ( 10 * self::TTL_YEAR ) ) {
787 if ( $exptime <= 0 ) {
817 $arg = str_replace(
':',
'%3A', $arg );
818 $key = $key .
':' . $arg;
820 return strtr( $key,
' ',
'_' );
843 public function makeKey( $class, $component =
null ) {
853 return $this->attrMap[$flag] ?? self::QOS_UNKNOWN;
864 foreach ( $bags
as $bag ) {
865 foreach ( $bag->attrMap
as $attr => $rank ) {
866 if ( isset( $map[$attr] ) ) {
867 $map[$attr] = min( $map[$attr], $rank );
882 return $this->wallClockOverride ?: microtime(
true );
890 $this->wallClockOverride =&
$time;
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Class representing a cache/ephemeral data store.
int[] $attrMap
Map of (ATTR_* class constant => QOS_* class constant)
getWithSetCallback( $key, $ttl, $callback, $flags=0)
Get an item with the given key, regenerating and setting it if not found.
__construct(array $params=[])
$params include:
getScopedLock( $key, $timeout=6, $expiry=30, $rclass='')
Get a lightweight exclusive self-unlocking lock.
unlock( $key)
Release an advisory lock on a key string.
incrWithInit( $key, $ttl, $value=1, $init=1)
Increase stored value of $key by $value while preserving its TTL.
isInteger( $value)
Check if a value is an integer.
lock( $key, $timeout=6, $expiry=6, $rclass='')
Acquire an advisory lock on a key string.
makeKey( $class, $component=null)
Make a cache key, scoped to this instance's keyspace.
array $duplicateKeyLookups
add( $key, $value, $exptime=0)
getMulti(array $keys, $flags=0)
Get an associative array containing the item for each of the keys that have items.
decr( $key, $value=1)
Decrease stored value of $key by $value while preserving its TTL.
modifySimpleRelayEvent(array $event)
Modify a cache update operation array for EventRelayer::notify()
float null $wallClockOverride
const READ_LATEST
Bitfield constants for get()/getMulti()
deleteObjectsExpiringBefore( $date, $progressCallback=false)
Delete all objects expiring before a certain date.
trackDuplicateKeys( $key)
Track the number of times that a given key has been used.
convertExpiry( $exptime)
Convert an optionally relative time to an absolute time.
callable[] $busyCallbacks
callback null $asyncHandler
getWithToken( $key, &$casToken, $flags=0)
setMulti(array $data, $exptime=0)
Batch insertion.
const ERR_NONE
Possible values for getLastError()
convertToRelative( $exptime)
Convert an optionally absolute expiry time to a relative time.
setLogger(LoggerInterface $logger)
const WRITE_SYNC
Bitfield constants for set()/merge()
mergeFlagMaps(array $bags)
Merge the flag maps of one or more BagOStuff objects into a "lowest common denominator" map.
getLastError()
Get the "last error" registered; clearLastError() should be called manually.
setLastError( $err)
Set the "last error" registry.
changeTTL( $key, $expiry=0)
Reset the TTL on a key if it exists.
mergeViaLock( $key, $callback, $exptime=0, $attempts=10, $flags=0)
clearLastError()
Clear the "last error" registry.
addBusyCallback(callable $workCallback)
Let a callback be run to avoid wasting time on special blocking calls.
cas( $casToken, $key, $value, $exptime=0)
Check and set an item.
makeKeyInternal( $keyspace, $args)
Construct a cache key.
int $lastError
ERR_* class constant.
array[] $locks
Lock tracking.
mergeViaCas( $key, $callback, $exptime=0, $attempts=10)
incr( $key, $value=1)
Increase stored value of $key by $value while preserving its TTL.
merge( $key, callable $callback, $exptime=0, $attempts=10, $flags=0)
Merge changes into the existing cache value (possibly creating a new one)
makeGlobalKey( $class, $component=null)
Make a global cache key.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
see documentation in includes Linker php for Linker::makeImageLink & $time
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
processing should stop and the error should be shown to the user * false
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Generic base class for storage interfaces.
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))