MediaWiki master
MessageBlobStore.php
Go to the documentation of this file.
1<?php
8
9namespace MediaWiki\ResourceLoader;
10
11use MediaWiki\Json\FormatJson;
12use MediaWiki\MediaWikiServices;
13use Psr\Log\LoggerAwareInterface;
14use Psr\Log\LoggerInterface;
15use Psr\Log\NullLogger;
16use Wikimedia\ObjectCache\WANObjectCache;
17
27class MessageBlobStore implements LoggerAwareInterface {
28
30 protected $logger;
31
33 protected $wanCache;
34
35 public function __construct(
36 private readonly ResourceLoader $resourceLoader,
37 ?LoggerInterface $logger,
38 ?WANObjectCache $wanObjectCache
39 ) {
40 $this->logger = $logger ?? new NullLogger();
41
42 // NOTE: when changing this assignment, make sure the code in the instantiator for
43 // LocalisationCache which calls MessageBlobStore::clearGlobalCacheEntry() uses the
44 // same cache object.
45 $this->wanCache = $wanObjectCache ?? MediaWikiServices::getInstance()
46 ->getMainWANObjectCache();
47 }
48
52 public function setLogger( LoggerInterface $logger ): void {
53 $this->logger = $logger;
54 }
55
64 public function getBlob( Module $module, $lang ) {
65 $blobs = $this->getBlobs( [ $module->getName() => $module ], $lang );
66 return $blobs[$module->getName()];
67 }
68
77 public function getBlobs( array $modules, $lang ) {
78 // Each cache key for a message blob by module name and language code also has a generic
79 // check key without language code. This is used to invalidate any and all language subkeys
80 // that exist for a module from the updateMessage() method.
81 $checkKeys = [
82 self::makeGlobalPurgeKey( $this->wanCache )
83 ];
84 $cacheKeys = [];
85 foreach ( $modules as $name => $module ) {
86 $cacheKey = $this->makeBlobCacheKey( $name, $lang, $module );
87 $cacheKeys[$name] = $cacheKey;
88 $checkKeys[$cacheKey][] = $this->makeModulePurgeKey( $name );
89 }
90 $curTTLs = [];
91 $result = $this->wanCache->getMulti( array_values( $cacheKeys ), $curTTLs, $checkKeys );
92
93 $blobs = [];
94 foreach ( $modules as $name => $module ) {
95 $key = $cacheKeys[$name];
96 if ( !isset( $result[$key] ) || $curTTLs[$key] === null || $curTTLs[$key] < 0 ) {
97 $blobs[$name] = $this->recacheMessageBlob( $key, $module, $lang );
98 } else {
99 // Use unexpired cache
100 $blobs[$name] = $result[$key];
101 }
102 }
103 return $blobs;
104 }
105
110 private static function makeGlobalPurgeKey( WANObjectCache $cache ) {
111 return $cache->makeGlobalKey( 'resourceloader-messageblob' );
112 }
113
120 private function makeModulePurgeKey( $name ) {
121 return $this->wanCache->makeKey( 'resourceloader-messageblob', $name );
122 }
123
130 private function makeBlobCacheKey( $name, $lang, Module $module ) {
131 $messages = array_values( array_unique( $module->getMessages() ) );
132 sort( $messages );
133 return $this->wanCache->makeKey( 'resourceloader-messageblob',
134 $name,
135 $lang,
136 md5( json_encode( $messages ) )
137 );
138 }
139
147 protected function recacheMessageBlob( $cacheKey, Module $module, $lang ) {
148 $blob = $this->generateMessageBlob( $module, $lang );
149 $cache = $this->wanCache;
150 $cache->set( $cacheKey, $blob,
151 // Add part of a day to TTL to avoid all modules expiring at once
152 $cache::TTL_WEEK + mt_rand( 0, $cache::TTL_DAY )
153 );
154 return $blob;
155 }
156
163 public function updateMessage( $key ): void {
164 $moduleNames = $this->resourceLoader->getModulesByMessage( $key );
165 foreach ( $moduleNames as $moduleName ) {
166 // Use the default holdoff TTL to account for database replica DB lag
167 // which can affect MessageCache.
168 $this->wanCache->touchCheckKey( $this->makeModulePurgeKey( $moduleName ) );
169 }
170 }
171
178 public static function clearGlobalCacheEntry( WANObjectCache $cache ): void {
179 // Disable holdoff TTL because:
180 // - LocalisationCache is populated by messages on-disk and don't have DB lag,
181 // thus there is no need for hold off. We only clear it after new localisation
182 // updates are known to be deployed to all servers.
183 // - This global check key invalidates message blobs for all modules for all wikis
184 // in cache contexts (e.g. languages, skins). Setting a hold-off on this key could
185 // cause a cache stampede since no values would be stored for several seconds.
186 $cache->touchCheckKey( self::makeGlobalPurgeKey( $cache ), $cache::HOLDOFF_TTL_NONE );
187 }
188
195 protected function fetchMessage( $key, $lang ) {
196 $message = wfMessage( $key )->inLanguage( $lang );
197 if ( !$message->exists() ) {
198 $this->logger->warning( 'Failed to find {messageKey} ({lang})', [
199 'messageKey' => $key,
200 'lang' => $lang,
201 ] );
202 $value = null;
203 } else {
204 $value = $message->plain();
205 }
206 return $value;
207 }
208
216 private function generateMessageBlob( Module $module, $lang ) {
217 $messages = [];
218 foreach ( $module->getMessages() as $key ) {
219 $value = $this->fetchMessage( $key, $lang );
220 // If the message does not exist, omit it from the blob so that
221 // client-side mw.message may do its own existence handling.
222 if ( $value !== null ) {
223 $messages[$key] = $value;
224 }
225 }
226
227 $json = FormatJson::encode( (object)$messages, false, FormatJson::UTF8_OK );
228 // @codeCoverageIgnoreStart
229 if ( $json === false ) {
230 $this->logger->warning( 'Failed to encode message blob for {module} ({lang})', [
231 'module' => $module->getName(),
232 'lang' => $lang,
233 ] );
234 $json = '{}';
235 }
236 // codeCoverageIgnoreEnd
237 return $json;
238 }
239}
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
static getInstance()
Returns the global default instance of the top level service locator.
This class generates message blobs for use by ResourceLoader.
static clearGlobalCacheEntry(WANObjectCache $cache)
Invalidate cache keys for all known modules.
__construct(private readonly ResourceLoader $resourceLoader, ?LoggerInterface $logger, ?WANObjectCache $wanObjectCache)
getBlob(Module $module, $lang)
Get the message blob for a module.
recacheMessageBlob( $cacheKey, Module $module, $lang)
getBlobs(array $modules, $lang)
Get the message blobs for a set of modules.
updateMessage( $key)
Invalidate cache keys for modules using this message key.
Abstraction for ResourceLoader modules, with name registration and maxage functionality.
Definition Module.php:34
getMessages()
Get the messages needed for this module.
Definition Module.php:360
getName()
Get this module's name.
Definition Module.php:119
ResourceLoader is a loading system for JavaScript and CSS resources.
Multi-datacenter aware caching interface.
makeGlobalKey( $keygroup,... $components)
set( $key, $value, $ttl=self::TTL_INDEFINITE, array $opts=[])
Set the value of a key in cache.