Merge "FauxRequest: don’t override getValues()"
[lhc/web/wiklou.git] / includes / resourceloader / MessageBlobStore.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @author Roan Kattouw
20 * @author Trevor Parscal
21 */
22
23 use MediaWiki\MediaWikiServices;
24 use Psr\Log\LoggerAwareInterface;
25 use Psr\Log\LoggerInterface;
26 use Psr\Log\NullLogger;
27 use Wikimedia\Rdbms\Database;
28
29 /**
30 * This class generates message blobs for use by ResourceLoader.
31 *
32 * A message blob is a JSON object containing the interface messages for a
33 * certain module in a certain language.
34 *
35 * @ingroup ResourceLoader
36 * @since 1.17
37 */
38 class MessageBlobStore implements LoggerAwareInterface {
39
40 /* @var ResourceLoader */
41 private $resourceloader;
42
43 /**
44 * @var LoggerInterface
45 */
46 protected $logger;
47
48 /**
49 * @var WANObjectCache
50 */
51 protected $wanCache;
52
53 /**
54 * @param ResourceLoader $rl
55 * @param LoggerInterface|null $logger
56 */
57 public function __construct( ResourceLoader $rl, LoggerInterface $logger = null ) {
58 $this->resourceloader = $rl;
59 $this->logger = $logger ?: new NullLogger();
60 $this->wanCache = MediaWikiServices::getInstance()->getMainWANObjectCache();
61 }
62
63 /**
64 * @since 1.27
65 * @param LoggerInterface $logger
66 */
67 public function setLogger( LoggerInterface $logger ) {
68 $this->logger = $logger;
69 }
70
71 /**
72 * Get the message blob for a module
73 *
74 * @since 1.27
75 * @param ResourceLoaderModule $module
76 * @param string $lang Language code
77 * @return string JSON
78 */
79 public function getBlob( ResourceLoaderModule $module, $lang ) {
80 $blobs = $this->getBlobs( [ $module->getName() => $module ], $lang );
81 return $blobs[$module->getName()];
82 }
83
84 /**
85 * Get the message blobs for a set of modules
86 *
87 * @since 1.27
88 * @param ResourceLoaderModule[] $modules Array of module objects keyed by name
89 * @param string $lang Language code
90 * @return array An array mapping module names to message blobs
91 */
92 public function getBlobs( array $modules, $lang ) {
93 // Each cache key for a message blob by module name and language code also has a generic
94 // check key without language code. This is used to invalidate any and all language subkeys
95 // that exist for a module from the updateMessage() method.
96 $cache = $this->wanCache;
97 $checkKeys = [
98 // Global check key, see clear()
99 $cache->makeGlobalKey( __CLASS__ )
100 ];
101 $cacheKeys = [];
102 foreach ( $modules as $name => $module ) {
103 $cacheKey = $this->makeCacheKey( $module, $lang );
104 $cacheKeys[$name] = $cacheKey;
105 // Per-module check key, see updateMessage()
106 $checkKeys[$cacheKey][] = $cache->makeKey( __CLASS__, $name );
107 }
108 $curTTLs = [];
109 $result = $cache->getMulti( array_values( $cacheKeys ), $curTTLs, $checkKeys );
110
111 $blobs = [];
112 foreach ( $modules as $name => $module ) {
113 $key = $cacheKeys[$name];
114 if ( !isset( $result[$key] ) || $curTTLs[$key] === null || $curTTLs[$key] < 0 ) {
115 $blobs[$name] = $this->recacheMessageBlob( $key, $module, $lang );
116 } else {
117 // Use unexpired cache
118 $blobs[$name] = $result[$key];
119 }
120 }
121 return $blobs;
122 }
123
124 /**
125 * @since 1.27
126 * @param ResourceLoaderModule $module
127 * @param string $lang
128 * @return string Cache key
129 */
130 private function makeCacheKey( ResourceLoaderModule $module, $lang ) {
131 $messages = array_values( array_unique( $module->getMessages() ) );
132 sort( $messages );
133 return $this->wanCache->makeKey( __CLASS__, $module->getName(), $lang,
134 md5( json_encode( $messages ) )
135 );
136 }
137
138 /**
139 * @since 1.27
140 * @param string $cacheKey
141 * @param ResourceLoaderModule $module
142 * @param string $lang
143 * @return string JSON blob
144 */
145 protected function recacheMessageBlob( $cacheKey, ResourceLoaderModule $module, $lang ) {
146 $blob = $this->generateMessageBlob( $module, $lang );
147 $cache = $this->wanCache;
148 $cache->set( $cacheKey, $blob,
149 // Add part of a day to TTL to avoid all modules expiring at once
150 $cache::TTL_WEEK + mt_rand( 0, $cache::TTL_DAY ),
151 Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) )
152 );
153 return $blob;
154 }
155
156 /**
157 * Invalidate cache keys for modules using this message key.
158 * Called by MessageCache when a message has changed.
159 *
160 * @param string $key Message key
161 */
162 public function updateMessage( $key ) {
163 $moduleNames = $this->getResourceLoader()->getModulesByMessage( $key );
164 foreach ( $moduleNames as $moduleName ) {
165 // Uses a holdoff to account for database replica DB lag (for MessageCache)
166 $this->wanCache->touchCheckKey( $this->wanCache->makeKey( __CLASS__, $moduleName ) );
167 }
168 }
169
170 /**
171 * Invalidate cache keys for all known modules.
172 * Called by LocalisationCache after cache is regenerated.
173 */
174 public function clear() {
175 $cache = $this->wanCache;
176 // Disable hold-off because:
177 // - LocalisationCache is populated by messages on-disk and don't have DB lag,
178 // thus there is no need for hold off. We only clear it after new localisation
179 // updates are known to be deployed to all servers.
180 // - This global check key invalidates message blobs for all modules for all wikis
181 // in cache contexts (e.g. languages, skins). Setting a hold-off on this key could
182 // cause a cache stampede since no values would be stored for several seconds.
183 $cache->touchCheckKey( $cache->makeGlobalKey( __CLASS__ ), $cache::HOLDOFF_TTL_NONE );
184 }
185
186 /**
187 * @since 1.27
188 * @return ResourceLoader
189 */
190 protected function getResourceLoader() {
191 return $this->resourceloader;
192 }
193
194 /**
195 * @since 1.27
196 * @param string $key Message key
197 * @param string $lang Language code
198 * @return string|null
199 */
200 protected function fetchMessage( $key, $lang ) {
201 $message = wfMessage( $key )->inLanguage( $lang );
202 if ( !$message->exists() ) {
203 $this->logger->warning( 'Failed to find {messageKey} ({lang})', [
204 'messageKey' => $key,
205 'lang' => $lang,
206 ] );
207 $value = null;
208 } else {
209 $value = $message->plain();
210 }
211 return $value;
212 }
213
214 /**
215 * Generate the message blob for a given module in a given language.
216 *
217 * @param ResourceLoaderModule $module
218 * @param string $lang Language code
219 * @return string JSON blob
220 */
221 private function generateMessageBlob( ResourceLoaderModule $module, $lang ) {
222 $messages = [];
223 foreach ( $module->getMessages() as $key ) {
224 $value = $this->fetchMessage( $key, $lang );
225 if ( $value !== null ) {
226 $messages[$key] = $value;
227 }
228 }
229
230 $json = FormatJson::encode( (object)$messages, false, FormatJson::UTF8_OK );
231 // @codeCoverageIgnoreStart
232 if ( $json === false ) {
233 $this->logger->warning( 'Failed to encode message blob for {module} ({lang})', [
234 'module' => $module->getName(),
235 'lang' => $lang,
236 ] );
237 $json = '{}';
238 }
239 // codeCoverageIgnoreEnd
240 return $json;
241 }
242 }