Expose $wgMaxArticleSize in siteinfo query api
[mediawiki.git] / includes / objectcache / ObjectCache.php
blobe1bb2db7c519a01f18b923f988f06b782817f2ce
1 <?php
2 /**
3 * Functions to get cache objects.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup Cache
24 use MediaWiki\Logger\LoggerFactory;
25 use MediaWiki\MediaWikiServices;
26 use MediaWiki\Services\ServiceDisabledException;
28 /**
29 * Functions to get cache objects
31 * The word "cache" has two main dictionary meanings, and both
32 * are used in this factory class. They are:
34 * - a) Cache (the computer science definition).
35 * A place to store copies or computations on existing data for
36 * higher access speeds.
37 * - b) Storage.
38 * A place to store lightweight data that is not canonically
39 * stored anywhere else (e.g. a "hoard" of objects).
41 * The former should always use strongly consistent stores, so callers don't
42 * have to deal with stale reads. The later may be eventually consistent, but
43 * callers can use BagOStuff:READ_LATEST to see the latest available data.
45 * Primary entry points:
47 * - ObjectCache::getMainWANInstance()
48 * Purpose: Memory cache.
49 * Stored in the local data-center's main cache (keyspace different from local-cluster cache).
50 * Delete events are broadcasted to other DCs main cache. See WANObjectCache for details.
52 * - ObjectCache::getLocalServerInstance( $fallbackType )
53 * Purpose: Memory cache for very hot keys.
54 * Stored only on the individual web server (typically APC for web requests,
55 * and EmptyBagOStuff in CLI mode).
56 * Not replicated to the other servers.
58 * - ObjectCache::getLocalClusterInstance()
59 * Purpose: Memory storage for per-cluster coordination and tracking.
60 * A typical use case would be a rate limit counter or cache regeneration mutex.
61 * Stored centrally within the local data-center. Not replicated to other DCs.
62 * Configured by $wgMainCacheType.
64 * - ObjectCache::getMainStashInstance()
65 * Purpose: Ephemeral global storage.
66 * Stored centrally within the primary data-center.
67 * Changes are applied there first and replicated to other DCs (best-effort).
68 * To retrieve the latest value (e.g. not from a slave), use BagOStuff::READ_LATEST.
69 * This store may be subject to LRU style evictions.
71 * - ObjectCache::getInstance( $cacheType )
72 * Purpose: Special cases (like tiered memory/disk caches).
73 * Get a specific cache type by key in $wgObjectCaches.
75 * All the above cache instances (BagOStuff and WANObjectCache) have their makeKey()
76 * method scoped to the *current* wiki ID. Use makeGlobalKey() to avoid this scoping
77 * when using keys that need to be shared amongst wikis.
79 * @ingroup Cache
81 class ObjectCache {
82 /** @var BagOStuff[] Map of (id => BagOStuff) */
83 public static $instances = [];
84 /** @var WANObjectCache[] Map of (id => WANObjectCache) */
85 public static $wanInstances = [];
87 /**
88 * Get a cached instance of the specified type of cache object.
90 * @param string $id A key in $wgObjectCaches.
91 * @return BagOStuff
93 public static function getInstance( $id ) {
94 if ( !isset( self::$instances[$id] ) ) {
95 self::$instances[$id] = self::newFromId( $id );
98 return self::$instances[$id];
102 * Get a cached instance of the specified type of WAN cache object.
104 * @since 1.26
105 * @param string $id A key in $wgWANObjectCaches.
106 * @return WANObjectCache
108 public static function getWANInstance( $id ) {
109 if ( !isset( self::$wanInstances[$id] ) ) {
110 self::$wanInstances[$id] = self::newWANCacheFromId( $id );
113 return self::$wanInstances[$id];
117 * Create a new cache object of the specified type.
119 * @param string $id A key in $wgObjectCaches.
120 * @return BagOStuff
121 * @throws MWException
123 public static function newFromId( $id ) {
124 global $wgObjectCaches;
126 if ( !isset( $wgObjectCaches[$id] ) ) {
127 throw new MWException( "Invalid object cache type \"$id\" requested. " .
128 "It is not present in \$wgObjectCaches." );
131 return self::newFromParams( $wgObjectCaches[$id] );
135 * Get the default keyspace for this wiki.
137 * This is either the value of the `CachePrefix` configuration variable,
138 * or (if the former is unset) the `DBname` configuration variable, with
139 * `DBprefix` (if defined).
141 * @return string
143 public static function getDefaultKeyspace() {
144 global $wgCachePrefix;
146 $keyspace = $wgCachePrefix;
147 if ( is_string( $keyspace ) && $keyspace !== '' ) {
148 return $keyspace;
151 return wfWikiID();
155 * Create a new cache object from parameters.
157 * @param array $params Must have 'factory' or 'class' property.
158 * - factory: Callback passed $params that returns BagOStuff.
159 * - class: BagOStuff subclass constructed with $params.
160 * - loggroup: Alias to set 'logger' key with LoggerFactory group.
161 * - .. Other parameters passed to factory or class.
162 * @return BagOStuff
163 * @throws MWException
165 public static function newFromParams( $params ) {
166 if ( isset( $params['loggroup'] ) ) {
167 $params['logger'] = LoggerFactory::getInstance( $params['loggroup'] );
168 } else {
169 $params['logger'] = LoggerFactory::getInstance( 'objectcache' );
171 if ( !isset( $params['keyspace'] ) ) {
172 $params['keyspace'] = self::getDefaultKeyspace();
174 if ( isset( $params['factory'] ) ) {
175 return call_user_func( $params['factory'], $params );
176 } elseif ( isset( $params['class'] ) ) {
177 $class = $params['class'];
178 // Automatically set the 'async' update handler
179 $params['asyncHandler'] = isset( $params['asyncHandler'] )
180 ? $params['asyncHandler']
181 : 'DeferredUpdates::addCallableUpdate';
182 // Enable reportDupes by default
183 $params['reportDupes'] = isset( $params['reportDupes'] )
184 ? $params['reportDupes']
185 : true;
186 // Do b/c logic for MemcachedBagOStuff
187 if ( is_subclass_of( $class, 'MemcachedBagOStuff' ) ) {
188 if ( !isset( $params['servers'] ) ) {
189 $params['servers'] = $GLOBALS['wgMemCachedServers'];
191 if ( !isset( $params['debug'] ) ) {
192 $params['debug'] = $GLOBALS['wgMemCachedDebug'];
194 if ( !isset( $params['persistent'] ) ) {
195 $params['persistent'] = $GLOBALS['wgMemCachedPersistent'];
197 if ( !isset( $params['timeout'] ) ) {
198 $params['timeout'] = $GLOBALS['wgMemCachedTimeout'];
201 return new $class( $params );
202 } else {
203 throw new MWException( "The definition of cache type \""
204 . print_r( $params, true ) . "\" lacks both "
205 . "factory and class parameters." );
210 * Factory function for CACHE_ANYTHING (referenced from DefaultSettings.php)
212 * CACHE_ANYTHING means that stuff has to be cached, not caching is not an option.
213 * If a caching method is configured for any of the main caches ($wgMainCacheType,
214 * $wgMessageCacheType, $wgParserCacheType), then CACHE_ANYTHING will effectively
215 * be an alias to the configured cache choice for that.
216 * If no cache choice is configured (by default $wgMainCacheType is CACHE_NONE),
217 * then CACHE_ANYTHING will forward to CACHE_DB.
219 * @param array $params
220 * @return BagOStuff
222 public static function newAnything( $params ) {
223 global $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType;
224 $candidates = [ $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType ];
225 foreach ( $candidates as $candidate ) {
226 if ( $candidate !== CACHE_NONE && $candidate !== CACHE_ANYTHING ) {
227 return self::getInstance( $candidate );
231 try {
232 // Make sure we actually have a DB backend before falling back to CACHE_DB
233 MediaWikiServices::getInstance()->getDBLoadBalancer();
234 $candidate = CACHE_DB;
235 } catch ( ServiceDisabledException $e ) {
236 // The LoadBalancer is disabled, probably because
237 // MediaWikiServices::disableStorageBackend was called.
238 $candidate = CACHE_NONE;
241 return self::getInstance( $candidate );
245 * Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
247 * This will look for any APC style server-local cache.
248 * A fallback cache can be specified if none is found.
250 * // Direct calls
251 * ObjectCache::getLocalServerInstance( $fallbackType );
253 * // From $wgObjectCaches via newFromParams()
254 * ObjectCache::getLocalServerInstance( array( 'fallback' => $fallbackType ) );
256 * @param int|string|array $fallback Fallback cache or parameter map with 'fallback'
257 * @return BagOStuff
258 * @throws MWException
259 * @since 1.27
261 public static function getLocalServerInstance( $fallback = CACHE_NONE ) {
262 if ( function_exists( 'apc_fetch' ) ) {
263 $id = 'apc';
264 } elseif ( function_exists( 'xcache_get' ) && wfIniGetBool( 'xcache.var_size' ) ) {
265 $id = 'xcache';
266 } elseif ( function_exists( 'wincache_ucache_get' ) ) {
267 $id = 'wincache';
268 } else {
269 if ( is_array( $fallback ) ) {
270 $id = isset( $fallback['fallback'] ) ? $fallback['fallback'] : CACHE_NONE;
271 } else {
272 $id = $fallback;
276 return self::getInstance( $id );
280 * @param array $params [optional] Array key 'fallback' for $fallback.
281 * @param int|string $fallback Fallback cache, e.g. (CACHE_NONE, "hash") (since 1.24)
282 * @return BagOStuff
283 * @deprecated 1.27
285 public static function newAccelerator( $params = [], $fallback = null ) {
286 if ( $fallback === null ) {
287 if ( is_array( $params ) && isset( $params['fallback'] ) ) {
288 $fallback = $params['fallback'];
289 } elseif ( !is_array( $params ) ) {
290 $fallback = $params;
294 return self::getLocalServerInstance( $fallback );
298 * Create a new cache object of the specified type.
300 * @since 1.26
301 * @param string $id A key in $wgWANObjectCaches.
302 * @return WANObjectCache
303 * @throws MWException
305 public static function newWANCacheFromId( $id ) {
306 global $wgWANObjectCaches;
308 if ( !isset( $wgWANObjectCaches[$id] ) ) {
309 throw new MWException( "Invalid object cache type \"$id\" requested. " .
310 "It is not present in \$wgWANObjectCaches." );
313 $params = $wgWANObjectCaches[$id];
314 foreach ( $params['channels'] as $action => $channel ) {
315 $params['relayers'][$action] = MediaWikiServices::getInstance()->getEventRelayerGroup()
316 ->getRelayer( $channel );
317 $params['channels'][$action] = $channel;
319 $params['cache'] = self::newFromId( $params['cacheId'] );
320 if ( isset( $params['loggroup'] ) ) {
321 $params['logger'] = LoggerFactory::getInstance( $params['loggroup'] );
322 } else {
323 $params['logger'] = LoggerFactory::getInstance( 'objectcache' );
325 $class = $params['class'];
327 return new $class( $params );
331 * Get the main cluster-local cache object.
333 * @since 1.27
334 * @return BagOStuff
336 public static function getLocalClusterInstance() {
337 global $wgMainCacheType;
339 return self::getInstance( $wgMainCacheType );
343 * Get the main WAN cache object.
345 * @since 1.26
346 * @return WANObjectCache
348 public static function getMainWANInstance() {
349 global $wgMainWANCache;
351 return self::getWANInstance( $wgMainWANCache );
355 * Get the cache object for the main stash.
357 * Stash objects are BagOStuff instances suitable for storing light
358 * weight data that is not canonically stored elsewhere (such as RDBMS).
359 * Stashes should be configured to propagate changes to all data-centers.
361 * Callers should be prepared for:
362 * - a) Writes to be slower in non-"primary" (e.g. HTTP GET/HEAD only) DCs
363 * - b) Reads to be eventually consistent, e.g. for get()/getMulti()
364 * In general, this means avoiding updates on idempotent HTTP requests and
365 * avoiding an assumption of perfect serializability (or accepting anomalies).
366 * Reads may be eventually consistent or data might rollback as nodes flap.
367 * Callers can use BagOStuff:READ_LATEST to see the latest available data.
369 * @return BagOStuff
370 * @since 1.26
372 public static function getMainStashInstance() {
373 global $wgMainStash;
375 return self::getInstance( $wgMainStash );
379 * Clear all the cached instances.
381 public static function clear() {
382 self::$instances = [];
383 self::$wanInstances = [];