MediaWiki  master
MultiWriteBagOStuff.php
Go to the documentation of this file.
1 <?php
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  // @TODO: consider using self::WRITE_ALLOW_SEGMENTS here?
134  [ $key, $value, self::UPGRADE_TTL ]
135  );
136  }
137 
138  return $value;
139  }
140 
141  public function set( $key, $value, $exptime = 0, $flags = 0 ) {
142  return $this->doWrite(
143  $this->cacheIndexes,
144  $this->usesAsyncWritesGivenFlags( $flags ),
145  __FUNCTION__,
146  func_get_args()
147  );
148  }
149 
150  public function delete( $key, $flags = 0 ) {
151  return $this->doWrite(
152  $this->cacheIndexes,
153  $this->usesAsyncWritesGivenFlags( $flags ),
154  __FUNCTION__,
155  func_get_args()
156  );
157  }
158 
159  public function add( $key, $value, $exptime = 0, $flags = 0 ) {
160  // Try the write to the top-tier cache
161  $ok = $this->doWrite(
162  [ 0 ],
163  $this->usesAsyncWritesGivenFlags( $flags ),
164  __FUNCTION__,
165  func_get_args()
166  );
167 
168  if ( $ok ) {
169  // Relay the add() using set() if it succeeded. This is meant to handle certain
170  // migration scenarios where the same store might get written to twice for certain
171  // keys. In that case, it does not make sense to return false due to "self-conflicts".
172  return $this->doWrite(
173  array_slice( $this->cacheIndexes, 1 ),
174  $this->usesAsyncWritesGivenFlags( $flags ),
175  'set',
176  [ $key, $value, $exptime, $flags ]
177  );
178  }
179 
180  return false;
181  }
182 
183  public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
184  return $this->doWrite(
185  $this->cacheIndexes,
186  $this->usesAsyncWritesGivenFlags( $flags ),
187  __FUNCTION__,
188  func_get_args()
189  );
190  }
191 
192  public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
193  return $this->doWrite(
194  $this->cacheIndexes,
195  $this->usesAsyncWritesGivenFlags( $flags ),
196  __FUNCTION__,
197  func_get_args()
198  );
199  }
200 
201  public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
202  // Only need to lock the first cache; also avoids deadlocks
203  return $this->caches[0]->lock( $key, $timeout, $expiry, $rclass );
204  }
205 
206  public function unlock( $key ) {
207  // Only the first cache is locked
208  return $this->caches[0]->unlock( $key );
209  }
210 
219  public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
220  $ret = false;
221  foreach ( $this->caches as $cache ) {
222  if ( $cache->deleteObjectsExpiringBefore( $date, $progressCallback ) ) {
223  $ret = true;
224  }
225  }
226 
227  return $ret;
228  }
229 
230  public function getMulti( array $keys, $flags = 0 ) {
231  // Just iterate over each key in order to handle all the backfill logic
232  $res = [];
233  foreach ( $keys as $key ) {
234  $val = $this->get( $key, $flags );
235  if ( $val !== false ) {
236  $res[$key] = $val;
237  }
238  }
239 
240  return $res;
241  }
242 
243  public function setMulti( array $data, $exptime = 0, $flags = 0 ) {
244  return $this->doWrite(
245  $this->cacheIndexes,
246  $this->usesAsyncWritesGivenFlags( $flags ),
247  __FUNCTION__,
248  func_get_args()
249  );
250  }
251 
252  public function deleteMulti( array $data, $flags = 0 ) {
253  return $this->doWrite(
254  $this->cacheIndexes,
255  $this->usesAsyncWritesGivenFlags( $flags ),
256  __FUNCTION__,
257  func_get_args()
258  );
259  }
260 
261  public function incr( $key, $value = 1 ) {
262  return $this->doWrite(
263  $this->cacheIndexes,
264  $this->asyncWrites,
265  __FUNCTION__,
266  func_get_args()
267  );
268  }
269 
270  public function decr( $key, $value = 1 ) {
271  return $this->doWrite(
272  $this->cacheIndexes,
273  $this->asyncWrites,
274  __FUNCTION__,
275  func_get_args()
276  );
277  }
278 
279  public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
280  return $this->doWrite(
281  $this->cacheIndexes,
282  $this->asyncWrites,
283  __FUNCTION__,
284  func_get_args()
285  );
286  }
287 
288  public function getLastError() {
289  return $this->caches[0]->getLastError();
290  }
291 
292  public function clearLastError() {
293  $this->caches[0]->clearLastError();
294  }
295 
305  protected function doWrite( $indexes, $asyncWrites, $method, array $args ) {
306  $ret = true;
307 
308  if ( array_diff( $indexes, [ 0 ] ) && $asyncWrites && $method !== 'merge' ) {
309  // Deep-clone $args to prevent misbehavior when something writes an
310  // object to the BagOStuff then modifies it afterwards, e.g. T168040.
311  $args = unserialize( serialize( $args ) );
312  }
313 
314  foreach ( $indexes as $i ) {
315  $cache = $this->caches[$i];
316  if ( $i == 0 || !$asyncWrites ) {
317  // First store or in sync mode: write now and get result
318  if ( !$cache->$method( ...$args ) ) {
319  $ret = false;
320  }
321  } else {
322  // Secondary write in async mode: do not block this HTTP request
325  function () use ( $cache, $method, $args, $logger ) {
326  if ( !$cache->$method( ...$args ) ) {
327  $logger->warning( "Async $method op failed" );
328  }
329  }
330  );
331  }
332  }
333 
334  return $ret;
335  }
336 
341  protected function usesAsyncWritesGivenFlags( $flags ) {
342  return ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) ? false : $this->asyncWrites;
343  }
344 
345  public function makeKeyInternal( $keyspace, $args ) {
346  return $this->caches[0]->makeKeyInternal( ...func_get_args() );
347  }
348 
349  public function makeKey( $class, $component = null ) {
350  return $this->caches[0]->makeKey( ...func_get_args() );
351  }
352 
353  public function makeGlobalKey( $class, $component = null ) {
354  return $this->caches[0]->makeGlobalKey( ...func_get_args() );
355  }
356 
357  protected function doGet( $key, $flags = 0, &$casToken = null ) {
358  throw new LogicException( __METHOD__ . ': proxy class does not need this method.' );
359  }
360 
361  protected function doSet( $key, $value, $exptime = 0, $flags = 0 ) {
362  throw new LogicException( __METHOD__ . ': proxy class does not need this method.' );
363  }
364 
365  protected function doDelete( $key, $flags = 0 ) {
366  throw new LogicException( __METHOD__ . ': proxy class does not need this method.' );
367  }
368 
369  protected function doGetMulti( array $keys, $flags = 0 ) {
370  throw new LogicException( __METHOD__ . ': proxy class does not need this method.' );
371  }
372 
373  protected function serialize( $value ) {
374  throw new LogicException( __METHOD__ . ': proxy class does not need this method.' );
375  }
376 
377  protected function unserialize( $value ) {
378  throw new LogicException( __METHOD__ . ': proxy class does not need this method.' );
379  }
380 }
makeGlobalKey( $class, $component=null)
add( $key, $value, $exptime=0, $flags=0)
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
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:1982
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
doSet( $key, $value, $exptime=0, $flags=0)
$value
string $keyspace
Definition: BagOStuff.php:70
makeKeyInternal( $keyspace, $args)
incrWithInit( $key, $ttl, $value=1, $init=1)
if( $line===false) $args
Definition: cdb.php:64
lock( $key, $timeout=6, $expiry=6, $rclass='')
getMulti(array $keys, $flags=0)
doWrite( $indexes, $asyncWrites, $method, array $args)
Apply a write method to the backing caches specified by $indexes (in order)
deleteObjectsExpiringBefore( $date, $progressCallback=false)
Delete objects expiring before a certain date.
A cache class that replicates all writes to multiple child caches.
changeTTL( $key, $exptime=0, $flags=0)
bool $asyncWrites
Use async secondary writes.
$res
Definition: database.txt:21
__construct( $params)
$params include:
$cache
Definition: mcc.php:33
$params
mergeFlagMaps(array $bags)
Merge the flag maps of one or more BagOStuff objects into a "lowest common denominator" map...
Definition: BagOStuff.php:1012
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 null
Definition: hooks.txt:780
merge( $key, callable $callback, $exptime=0, $attempts=10, $flags=0)
doGet( $key, $flags=0, &$casToken=null)
setMulti(array $data, $exptime=0, $flags=0)
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
int [] $cacheIndexes
List of all backing cache indexes.
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
LoggerInterface $logger
Definition: BagOStuff.php:72
makeKey( $class, $component=null)
doGetMulti(array $keys, $flags=0)
doDelete( $key, $flags=0)
$debug
Definition: mcc.php:31
deleteMulti(array $data, $flags=0)
callable null $asyncHandler
Definition: BagOStuff.php:74