MediaWiki  1.33.0
MultiWriteBagOStuff.php
Go to the documentation of this file.
1 <?php
23 use Wikimedia\ObjectFactory;
24 
37  protected $caches;
39  protected $asyncWrites = false;
41  protected $cacheIndexes = [];
42 
43  const UPGRADE_TTL = 3600; // TTL when a key is copied to a higher cache tier
44 
65  public function __construct( $params ) {
66  parent::__construct( $params );
67 
68  if ( empty( $params['caches'] ) || !is_array( $params['caches'] ) ) {
69  throw new InvalidArgumentException(
70  __METHOD__ . ': "caches" parameter must be an array of caches'
71  );
72  }
73 
74  $this->caches = [];
75  foreach ( $params['caches'] as $cacheInfo ) {
76  if ( $cacheInfo instanceof BagOStuff ) {
77  $this->caches[] = $cacheInfo;
78  } else {
79  if ( !isset( $cacheInfo['args'] ) ) {
80  // B/C for when $cacheInfo was for ObjectCache::newFromParams().
81  // Callers intenting this to be for ObjectFactory::getObjectFromSpec
82  // should have set "args" per the docs above. Doings so avoids extra
83  // (likely harmless) params (factory/class/calls) ending up in "args".
84  $cacheInfo['args'] = [ $cacheInfo ];
85  }
86  $this->caches[] = ObjectFactory::getObjectFromSpec( $cacheInfo );
87  }
88  }
89  $this->mergeFlagMaps( $this->caches );
90 
91  $this->asyncWrites = (
92  isset( $params['replication'] ) &&
93  $params['replication'] === 'async' &&
94  is_callable( $this->asyncHandler )
95  );
96 
97  $this->cacheIndexes = array_keys( $this->caches );
98  }
99 
100  public function setDebug( $debug ) {
101  foreach ( $this->caches as $cache ) {
102  $cache->setDebug( $debug );
103  }
104  }
105 
106  public function get( $key, $flags = 0 ) {
107  if ( ( $flags & self::READ_LATEST ) == self::READ_LATEST ) {
108  // If the latest write was a delete(), we do NOT want to fallback
109  // to the other tiers and possibly see the old value. Also, this
110  // is used by merge(), which only needs to hit the primary.
111  return $this->caches[0]->get( $key, $flags );
112  }
113 
114  $value = false;
115  $missIndexes = []; // backends checked
116  foreach ( $this->caches as $i => $cache ) {
117  $value = $cache->get( $key, $flags );
118  if ( $value !== false ) {
119  break;
120  }
121  $missIndexes[] = $i;
122  }
123 
124  if ( $value !== false
125  && $missIndexes
126  && ( $flags & self::READ_VERIFIED ) == self::READ_VERIFIED
127  ) {
128  // Backfill the value to the higher (and often faster/smaller) cache tiers
129  $this->doWrite(
130  $missIndexes,
131  $this->asyncWrites,
132  'set',
133  [ $key, $value, self::UPGRADE_TTL ]
134  );
135  }
136 
137  return $value;
138  }
139  public function set( $key, $value, $exptime = 0, $flags = 0 ) {
140  return $this->doWrite(
141  $this->cacheIndexes,
142  $this->usesAsyncWritesGivenFlags( $flags ),
143  __FUNCTION__,
144  func_get_args()
145  );
146  }
147 
148  public function delete( $key, $flags = 0 ) {
149  return $this->doWrite(
150  $this->cacheIndexes,
151  $this->usesAsyncWritesGivenFlags( $flags ),
152  __FUNCTION__,
153  func_get_args()
154  );
155  }
156 
157  public function add( $key, $value, $exptime = 0, $flags = 0 ) {
158  // Try the write to the top-tier cache
159  $ok = $this->doWrite(
160  [ 0 ],
161  $this->usesAsyncWritesGivenFlags( $flags ),
162  __FUNCTION__,
163  func_get_args()
164  );
165 
166  if ( $ok ) {
167  // Relay the add() using set() if it succeeded. This is meant to handle certain
168  // migration scenarios where the same store might get written to twice for certain
169  // keys. In that case, it does not make sense to return false due to "self-conflicts".
170  return $this->doWrite(
171  array_slice( $this->cacheIndexes, 1 ),
172  $this->usesAsyncWritesGivenFlags( $flags ),
173  'set',
174  [ $key, $value, $exptime, $flags ]
175  );
176  }
177 
178  return false;
179  }
180 
181  public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
182  return $this->doWrite(
183  $this->cacheIndexes,
184  $this->usesAsyncWritesGivenFlags( $flags ),
185  __FUNCTION__,
186  func_get_args()
187  );
188  }
189 
190  public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
191  return $this->doWrite(
192  $this->cacheIndexes,
193  $this->usesAsyncWritesGivenFlags( $flags ),
194  __FUNCTION__,
195  func_get_args()
196  );
197  }
198 
199  public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
200  // Only need to lock the first cache; also avoids deadlocks
201  return $this->caches[0]->lock( $key, $timeout, $expiry, $rclass );
202  }
203 
204  public function unlock( $key ) {
205  // Only the first cache is locked
206  return $this->caches[0]->unlock( $key );
207  }
216  public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
217  $ret = false;
218  foreach ( $this->caches as $cache ) {
219  if ( $cache->deleteObjectsExpiringBefore( $date, $progressCallback ) ) {
220  $ret = true;
221  }
222  }
223 
224  return $ret;
225  }
226 
227  public function getMulti( array $keys, $flags = 0 ) {
228  // Just iterate over each key in order to handle all the backfill logic
229  $res = [];
230  foreach ( $keys as $key ) {
231  $val = $this->get( $key, $flags );
232  if ( $val !== false ) {
233  $res[$key] = $val;
234  }
235  }
236 
237  return $res;
238  }
239 
240  public function setMulti( array $data, $exptime = 0, $flags = 0 ) {
241  return $this->doWrite(
242  $this->cacheIndexes,
243  $this->usesAsyncWritesGivenFlags( $flags ),
244  __FUNCTION__,
245  func_get_args()
246  );
247  }
248 
249  public function deleteMulti( array $data, $flags = 0 ) {
250  return $this->doWrite(
251  $this->cacheIndexes,
252  $this->usesAsyncWritesGivenFlags( $flags ),
253  __FUNCTION__,
254  func_get_args()
255  );
256  }
257 
258  public function incr( $key, $value = 1 ) {
259  return $this->doWrite(
260  $this->cacheIndexes,
261  $this->asyncWrites,
262  __FUNCTION__,
263  func_get_args()
264  );
265  }
266 
267  public function decr( $key, $value = 1 ) {
268  return $this->doWrite(
269  $this->cacheIndexes,
270  $this->asyncWrites,
271  __FUNCTION__,
272  func_get_args()
273  );
274  }
275 
276  public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
277  return $this->doWrite(
278  $this->cacheIndexes,
279  $this->asyncWrites,
280  __FUNCTION__,
281  func_get_args()
282  );
283  }
284 
285  public function getLastError() {
286  return $this->caches[0]->getLastError();
287  }
288 
289  public function clearLastError() {
290  $this->caches[0]->clearLastError();
291  }
301  protected function doWrite( $indexes, $asyncWrites, $method, array $args ) {
302  $ret = true;
303 
304  if ( array_diff( $indexes, [ 0 ] ) && $asyncWrites && $method !== 'merge' ) {
305  // Deep-clone $args to prevent misbehavior when something writes an
306  // object to the BagOStuff then modifies it afterwards, e.g. T168040.
308  }
309 
310  foreach ( $indexes as $i ) {
311  $cache = $this->caches[$i];
312  if ( $i == 0 || !$asyncWrites ) {
313  // First store or in sync mode: write now and get result
314  if ( !$cache->$method( ...$args ) ) {
315  $ret = false;
316  }
317  } else {
318  // Secondary write in async mode: do not block this HTTP request
321  function () use ( $cache, $method, $args, $logger ) {
322  if ( !$cache->$method( ...$args ) ) {
323  $logger->warning( "Async $method op failed" );
324  }
325  }
326  );
327  }
328  }
329 
330  return $ret;
331  }
332 
337  protected function usesAsyncWritesGivenFlags( $flags ) {
338  return ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) ? false : $this->asyncWrites;
339  }
340 
341  public function makeKeyInternal( $keyspace, $args ) {
342  return $this->caches[0]->makeKeyInternal( ...func_get_args() );
343  }
344 
345  public function makeKey( $class, $component = null ) {
346  return $this->caches[0]->makeKey( ...func_get_args() );
347  }
348 
349  public function makeGlobalKey( $class, $component = null ) {
350  return $this->caches[0]->makeGlobalKey( ...func_get_args() );
351  }
352 
353  protected function doGet( $key, $flags = 0, &$casToken = null ) {
354  throw new LogicException( __METHOD__ . ': proxy class does not need this method.' );
355  }
356 }
MultiWriteBagOStuff\$cacheIndexes
int[] $cacheIndexes
List of all backing cache indexes.
Definition: MultiWriteBagOStuff.php:41
MultiWriteBagOStuff\lock
lock( $key, $timeout=6, $expiry=6, $rclass='')
Acquire an advisory lock on a key string.
Definition: MultiWriteBagOStuff.php:199
MultiWriteBagOStuff\doWrite
doWrite( $indexes, $asyncWrites, $method, array $args)
Apply a write method to the backing caches specified by $indexes (in order)
Definition: MultiWriteBagOStuff.php:301
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
MultiWriteBagOStuff\incrWithInit
incrWithInit( $key, $ttl, $value=1, $init=1)
Increase stored value of $key by $value while preserving its TTL.
Definition: MultiWriteBagOStuff.php:276
MultiWriteBagOStuff\setMulti
setMulti(array $data, $exptime=0, $flags=0)
Batch insertion/replace.
Definition: MultiWriteBagOStuff.php:240
MultiWriteBagOStuff\getLastError
getLastError()
Get the "last error" registered; clearLastError() should be called manually.
Definition: MultiWriteBagOStuff.php:285
MultiWriteBagOStuff\$asyncWrites
bool $asyncWrites
Use async secondary writes.
Definition: MultiWriteBagOStuff.php:39
MultiWriteBagOStuff\setDebug
setDebug( $debug)
Definition: MultiWriteBagOStuff.php:100
MultiWriteBagOStuff\clearLastError
clearLastError()
Clear the "last error" registry.
Definition: MultiWriteBagOStuff.php:289
MultiWriteBagOStuff\makeGlobalKey
makeGlobalKey( $class, $component=null)
Make a global cache key.
Definition: MultiWriteBagOStuff.php:349
MultiWriteBagOStuff\merge
merge( $key, callable $callback, $exptime=0, $attempts=10, $flags=0)
Merge changes into the existing cache value (possibly creating a new one)
Definition: MultiWriteBagOStuff.php:181
$params
$params
Definition: styleTest.css.php:44
BagOStuff
Class representing a cache/ephemeral data store.
Definition: BagOStuff.php:58
$res
$res
Definition: database.txt:21
MultiWriteBagOStuff\changeTTL
changeTTL( $key, $exptime=0, $flags=0)
Change the expiration on a key if it exists.
Definition: MultiWriteBagOStuff.php:190
serialize
serialize()
Definition: ApiMessageTrait.php:134
BagOStuff\$logger
LoggerInterface $logger
Definition: BagOStuff.php:66
php
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
Definition: injection.txt:35
$debug
$debug
Definition: mcc.php:31
MultiWriteBagOStuff\incr
incr( $key, $value=1)
Increase stored value of $key by $value while preserving its TTL.
Definition: MultiWriteBagOStuff.php:258
$data
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
Definition: generatePhpCharToUpperMappings.php:13
MultiWriteBagOStuff\deleteMulti
deleteMulti(array $data, $flags=0)
Batch deletion.
Definition: MultiWriteBagOStuff.php:249
MultiWriteBagOStuff\unlock
unlock( $key)
Release an advisory lock on a key string.
Definition: MultiWriteBagOStuff.php:204
BagOStuff\$asyncHandler
callable null $asyncHandler
Definition: BagOStuff.php:68
BagOStuff\READ_LATEST
const READ_LATEST
Bitfield constants for get()/getMulti()
Definition: BagOStuff.php:91
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
MultiWriteBagOStuff\makeKeyInternal
makeKeyInternal( $keyspace, $args)
Construct a cache key.
Definition: MultiWriteBagOStuff.php:341
MultiWriteBagOStuff\add
add( $key, $value, $exptime=0, $flags=0)
Insert an item if it does not already exist.
Definition: MultiWriteBagOStuff.php:157
array
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))
MultiWriteBagOStuff\deleteObjectsExpiringBefore
deleteObjectsExpiringBefore( $date, $progressCallback=false)
Delete objects expiring before a certain date.
Definition: MultiWriteBagOStuff.php:216
MultiWriteBagOStuff\decr
decr( $key, $value=1)
Decrease stored value of $key by $value while preserving its TTL.
Definition: MultiWriteBagOStuff.php:267
MultiWriteBagOStuff\__construct
__construct( $params)
$params include:
Definition: MultiWriteBagOStuff.php:65
BagOStuff\mergeFlagMaps
mergeFlagMaps(array $bags)
Merge the flag maps of one or more BagOStuff objects into a "lowest common denominator" map.
Definition: BagOStuff.php:793
$value
$value
Definition: styleTest.css.php:49
MultiWriteBagOStuff\makeKey
makeKey( $class, $component=null)
Make a cache key, scoped to this instance's keyspace.
Definition: MultiWriteBagOStuff.php:345
MultiWriteBagOStuff
A cache class that replicates all writes to multiple child caches.
Definition: MultiWriteBagOStuff.php:35
$ret
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1985
MultiWriteBagOStuff\$caches
BagOStuff[] $caches
Definition: MultiWriteBagOStuff.php:37
MultiWriteBagOStuff\doGet
doGet( $key, $flags=0, &$casToken=null)
Definition: MultiWriteBagOStuff.php:353
unserialize
unserialize( $serialized)
Definition: ApiMessageTrait.php:142
$args
if( $line===false) $args
Definition: cdb.php:64
$cache
$cache
Definition: mcc.php:33
MultiWriteBagOStuff\UPGRADE_TTL
const UPGRADE_TTL
Definition: MultiWriteBagOStuff.php:43
as
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
Definition: distributors.txt:9
$keys
$keys
Definition: testCompression.php:67
BagOStuff\$keyspace
string $keyspace
Definition: BagOStuff.php:64
MultiWriteBagOStuff\getMulti
getMulti(array $keys, $flags=0)
Get an associative array containing the item for each of the keys that have items.
Definition: MultiWriteBagOStuff.php:227
MultiWriteBagOStuff\usesAsyncWritesGivenFlags
usesAsyncWritesGivenFlags( $flags)
Definition: MultiWriteBagOStuff.php:337