29use Psr\Log\LoggerAwareInterface;
30use Psr\Log\LoggerInterface;
31use Psr\Log\NullLogger;
32use Wikimedia\ScopedCallback;
33use Wikimedia\WaitConditionLoop;
111 if ( isset(
$params[
'keyspace'] ) ) {
112 $this->keyspace =
$params[
'keyspace'];
115 $this->asyncHandler =
$params[
'asyncHandler'] ??
null;
117 if ( !empty(
$params[
'reportDupes'] ) && is_callable( $this->asyncHandler ) ) {
118 $this->reportDupes =
true;
121 $this->syncTimeout =
$params[
'syncTimeout'] ?? 3;
129 $this->logger = $logger;
136 $this->debugMode = $bool;
152 $value = $this->
get( $key, $flags );
155 if ( !is_callable( $callback ) ) {
156 throw new InvalidArgumentException(
"Invalid cache miss callback provided." );
158 $value = call_user_func( $callback );
160 $this->
set( $key,
$value, $ttl, $flags );
180 public function get( $key, $flags = 0 ) {
183 return $this->
doGet( $key, $flags );
191 if ( !$this->reportDupes ) {
195 if ( !isset( $this->duplicateKeyLookups[$key] ) ) {
198 $this->duplicateKeyLookups[$key] = 0;
200 $this->duplicateKeyLookups[$key] += 1;
202 if ( $this->dupeTrackScheduled ===
false ) {
203 $this->dupeTrackScheduled =
true;
205 call_user_func( $this->asyncHandler,
function () {
206 $dups = array_filter( $this->duplicateKeyLookups );
207 foreach ( $dups
as $key => $count ) {
208 $this->logger->warning(
209 'Duplicate get(): "{key}" fetched {count} times',
211 [
'key' => $key,
'count' => $count + 1, ]
225 abstract protected function doGet( $key, $flags = 0, &$casToken =
null );
236 abstract public function set( $key,
$value, $exptime = 0, $flags = 0 );
245 abstract public function delete( $key, $flags = 0 );
256 abstract public function add( $key,
$value, $exptime = 0, $flags = 0 );
275 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
276 return $this->
mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
289 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
294 $currentValue = $this->
doGet( $key, self::READ_LATEST, $casToken );
296 $this->logger->warning(
297 __METHOD__ .
' failed due to I/O error on get() for {key}.',
305 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
306 $hadNoCurrentValue = ( $currentValue ===
false );
307 unset( $currentValue );
312 } elseif ( $hadNoCurrentValue ) {
320 $this->logger->warning(
321 __METHOD__ .
' failed due to I/O error for {key}.',
327 }
while ( !
$success && --$attempts );
343 protected function cas( $casToken, $key,
$value, $exptime = 0, $flags = 0 ) {
344 if ( !$this->
lock( $key, 0 ) ) {
349 $this->
doGet( $key, self::READ_LATEST, $curCasToken );
350 if ( $casToken === $curCasToken ) {
354 __METHOD__ .
' failed due to race condition for {key}.',
377 public function changeTTL( $key, $expiry = 0, $flags = 0 ) {
382 function (
$cache, $ttl, $currentValue )
use ( &$found ) {
383 $found = ( $currentValue !==
false );
385 return $currentValue;
392 return ( $ok && $found );
406 public function lock( $key, $timeout = 6, $expiry = 6, $rclass =
'' ) {
408 if ( isset( $this->locks[$key] ) ) {
409 if ( $rclass !=
'' && $this->locks[$key][
'class'] === $rclass ) {
410 ++$this->locks[$key][
'depth'];
418 $expiry = min( $expiry ?: INF, self::TTL_DAY );
419 $loop =
new WaitConditionLoop(
420 function ()
use ( $key, $expiry,
$fname ) {
422 if ( $this->
add(
"{$key}:lock", 1, $expiry ) ) {
423 return WaitConditionLoop::CONDITION_REACHED;
425 $this->logger->warning(
426 $fname .
' failed due to I/O error for {key}.',
430 return WaitConditionLoop::CONDITION_ABORTED;
433 return WaitConditionLoop::CONDITION_CONTINUE;
438 $code = $loop->invoke();
439 $locked = (
$code === $loop::CONDITION_REACHED );
441 $this->locks[$key] = [
'class' => $rclass,
'depth' => 1 ];
442 } elseif (
$code === $loop::CONDITION_TIMED_OUT ) {
443 $this->logger->warning(
444 "$fname failed due to timeout for {key}.",
445 [
'key' => $key,
'timeout' => $timeout ]
459 if ( isset( $this->locks[$key] ) && --$this->locks[$key][
'depth'] <= 0 ) {
460 unset( $this->locks[$key] );
462 $ok = $this->
delete(
"{$key}:lock" );
464 $this->logger->warning(
465 __METHOD__ .
' failed to release lock for {key}.',
492 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass =
'' ) {
493 $expiry = min( $expiry ?: INF, self::TTL_DAY );
495 if ( !$this->
lock( $key, $timeout, $expiry, $rclass ) ) {
501 return new ScopedCallback(
function ()
use ( $key, $lSince, $expiry ) {
504 if ( ( $age + $latency ) >= $expiry ) {
505 $this->logger->warning(
506 "Lock for {key} held too long ({age} sec).",
507 [
'key' => $key,
'age' => $age ]
538 $val = $this->
get( $key, $flags );
539 if ( $val !==
false ) {
558 if ( !$this->
set( $key,
$value, $exptime, $flags ) ) {
576 $res = $this->
delete( $key, $flags ) &&
$res;
617 $newValue = $this->
add( $key, (
int)$init, $ttl ) ? $init :
false;
633 return $this->lastError;
641 $this->lastError = self::ERR_NONE;
650 $this->lastError = $err;
674 $this->busyCallbacks[] = $workCallback;
681 if ( $this->debugMode ) {
682 $this->logger->debug(
"{class} debug: $text", [
683 'class' => static::class,
693 return ( $exptime != 0 && $exptime < ( 10 * self::TTL_YEAR ) );
717 if ( $exptime >= ( 10 * self::TTL_YEAR ) ) {
719 if ( $exptime <= 0 ) {
749 $key .=
':' . str_replace(
':',
'%3A', $arg );
751 return strtr( $key,
' ',
'_' );
774 public function makeKey( $class, $component =
null ) {
784 return $this->attrMap[$flag] ?? self::QOS_UNKNOWN;
795 foreach ( $bags
as $bag ) {
796 foreach ( $bag->attrMap
as $attr => $rank ) {
797 if ( isset( $map[$attr] ) ) {
798 $map[$attr] = min( $map[$attr], $rank );
813 return $this->wallClockOverride ?: microtime(
true );
821 $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.
deleteMulti(array $keys, $flags=0)
Batch deletion.
array $duplicateKeyLookups
add( $key, $value, $exptime=0, $flags=0)
Insert an item if it does not already exist.
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.
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.
convertToExpiry( $exptime)
Convert an optionally relative time to an absolute time.
mergeViaCas( $key, $callback, $exptime=0, $attempts=10, $flags=0)
expiryIsRelative( $exptime)
callable[] $busyCallbacks
convertToRelative( $exptime)
Convert an optionally absolute expiry time to a relative time.
setLogger(LoggerInterface $logger)
setMulti(array $data, $exptime=0, $flags=0)
Batch insertion/replace.
cas( $casToken, $key, $value, $exptime=0, $flags=0)
Check and set an item.
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.
changeTTL( $key, $expiry=0, $flags=0)
Change the expiration on a key if it exists.
setLastError( $err)
Set the "last error" registry.
clearLastError()
Clear the "last error" registry.
doGet( $key, $flags=0, &$casToken=null)
addBusyCallback(callable $workCallback)
Let a callback be run to avoid wasting time on special blocking calls.
makeKeyInternal( $keyspace, $args)
Construct a cache key.
int $lastError
ERR_* class constant.
array[] $locks
Lock tracking.
incr( $key, $value=1)
Increase stored value of $key by $value while preserving its TTL.
callable null $asyncHandler
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
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
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 When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password 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 interface for lightweight expiring object stores.
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))