Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
92.23% covered (success)
92.23%
95 / 103
50.00% covered (danger)
50.00%
5 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
RevisionOutputCache
92.23% covered (success)
92.23%
95 / 103
50.00% covered (danger)
50.00%
5 / 10
29.39
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 getContentModelFromRevision
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 incrementStats
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 incrementRenderReasonStats
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 makeParserOutputKey
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
2.02
 makeParserOutputKeyOptionalRevId
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 get
95.65% covered (success)
95.65%
22 / 23
0.00% covered (danger)
0.00%
0 / 1
6
 save
96.97% covered (success)
96.97%
32 / 33
0.00% covered (danger)
0.00%
0 / 1
10
 restoreFromJson
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 encodeAsJson
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2/**
3 * Cache for outputs of the PHP parser
4 *
5 * @license GPL-2.0-or-later
6 * @file
7 * @ingroup Cache Parser
8 */
9
10namespace MediaWiki\Parser;
11
12use InvalidArgumentException;
13use JsonException;
14use MediaWiki\Json\JsonCodec;
15use MediaWiki\Revision\RevisionRecord;
16use MediaWiki\Revision\SlotRecord;
17use MediaWiki\Utils\MWTimestamp;
18use Psr\Log\LoggerInterface;
19use Wikimedia\ObjectCache\WANObjectCache;
20use Wikimedia\Stats\StatsFactory;
21use Wikimedia\Timestamp\TimestampFormat as TS;
22use Wikimedia\UUID\GlobalIdGenerator;
23
24/**
25 * Cache for ParserOutput objects.
26 * The cache is split per ParserOptions.
27 *
28 * @since 1.36
29 * @ingroup Cache Parser
30 */
31class RevisionOutputCache {
32
33    /** @var string The name of this cache. Used as a root of the cache key. */
34    private $name;
35
36    /**
37     * Anything cached prior to this is invalidated
38     *
39     * @var string
40     */
41    private $cacheEpoch;
42
43    /**
44     * Expiry time for cache entries.
45     *
46     * @var int
47     */
48    private $cacheExpiry;
49
50    /**
51     * @param string $name
52     * @param WANObjectCache $cache
53     * @param int $cacheExpiry Expiry for ParserOutput in $cache.
54     * @param string $cacheEpoch Anything before this timestamp is invalidated
55     * @param JsonCodec $jsonCodec
56     * @param StatsFactory $stats
57     * @param LoggerInterface $logger
58     * @param GlobalIdGenerator $globalIdGenerator
59     */
60    public function __construct(
61        string $name,
62        private readonly WANObjectCache $cache,
63        int $cacheExpiry,
64        string $cacheEpoch,
65        private readonly JsonCodec $jsonCodec,
66        private readonly StatsFactory $stats,
67        private readonly LoggerInterface $logger,
68        private readonly GlobalIdGenerator $globalIdGenerator,
69    ) {
70        $this->name = $name;
71        $this->cacheExpiry = $cacheExpiry;
72        $this->cacheEpoch = $cacheEpoch;
73    }
74
75    /**
76     * @param RevisionRecord $revision
77     * @return string
78     */
79    private function getContentModelFromRevision( RevisionRecord $revision ) {
80        if ( !$revision->hasSlot( SlotRecord::MAIN ) ) {
81            return 'missing';
82        }
83        return str_replace( '.', '_', $revision->getMainContentModel() );
84    }
85
86    /**
87     * @param RevisionRecord $revision
88     * @param string $status e.g. hit, miss etc.
89     * @param string|null $reason
90     */
91    private function incrementStats( RevisionRecord $revision, string $status, ?string $reason = null ) {
92        $contentModel = $this->getContentModelFromRevision( $revision );
93
94        $this->stats->getCounter( 'RevisionOutputCache_operation_total' )
95            ->setLabel( 'name', $this->name )
96            ->setLabel( 'contentModel', $contentModel )
97            ->setLabel( 'status', $status )
98            ->setLabel( 'reason', $reason ?: 'n/a' )
99            ->increment();
100    }
101
102    /**
103     * @param RevisionRecord $revision
104     * @param string $renderReason
105     */
106    private function incrementRenderReasonStats( RevisionRecord $revision, $renderReason ) {
107        $contentModel = $this->getContentModelFromRevision( $revision );
108        $renderReason = preg_replace( '/\W+/', '_', $renderReason );
109
110        $this->stats->getCounter( 'RevisionOutputCache_render_total' )
111            ->setLabel( 'name', $this->name )
112            ->setLabel( 'contentModel', $contentModel )
113            ->setLabel( 'reason', $renderReason )
114            ->increment();
115    }
116
117    /**
118     * Get a key that will be used by this cache to store the content
119     * for a given page considering the given options and the array of
120     * used options.
121     *
122     * If there is a possibility the revision does not have a revision id, use
123     * makeParserOutputKeyOptionalRevId() instead.
124     *
125     * @warning The exact format of the key is considered internal and is subject
126     * to change, thus should not be used as storage or long-term caching key.
127     * This is intended to be used for logging or keying something transient.
128     *
129     * @param RevisionRecord $revision
130     * @param ParserOptions $options
131     * @param array|null $usedOptions currently ignored
132     * @return string
133     * @internal
134     */
135    public function makeParserOutputKey(
136        RevisionRecord $revision,
137        ParserOptions $options,
138        ?array $usedOptions = null
139    ): string {
140        $usedOptions = $options->allCacheVaryingOptionsWithPostproc();
141
142        $revId = $revision->getId();
143        if ( !$revId ) {
144            // If RevId is null, this would probably be unsafe to use as a cache key.
145            throw new InvalidArgumentException( "Revision must have an id number" );
146        }
147        $hash = $options->optionsHash( $usedOptions );
148        return $this->cache->makeKey( $this->name, $revId, $hash );
149    }
150
151    /**
152     * Get a key that will be used for locks or pool counter
153     *
154     * Similar to makeParserOutputKey except the revision id might be null,
155     * in which case it is unsafe to cache, but still needs a key for things like
156     * poolcounter.
157     *
158     * @warning The exact format of the key is considered internal and is subject
159     * to change, thus should not be used as storage or long-term caching key.
160     * This is intended to be used for logging or keying something transient.
161     *
162     * @param RevisionRecord $revision
163     * @param ParserOptions $options
164     * @param array|null $usedOptions currently ignored
165     * @return string
166     * @internal
167     */
168    public function makeParserOutputKeyOptionalRevId(
169        RevisionRecord $revision,
170        ParserOptions $options,
171        ?array $usedOptions = null
172    ): string {
173        $usedOptions = ParserOptions::allCacheVaryingOptions();
174
175        // revId may be null.
176        $revId = (string)$revision->getId();
177        $hash = $options->optionsHash( $usedOptions );
178        return $this->cache->makeKey( $this->name, $revId, $hash );
179    }
180
181    /**
182     * Retrieve the ParserOutput from cache.
183     * false if not found or outdated.
184     *
185     * @param RevisionRecord $revision
186     * @param ParserOptions $parserOptions
187     *
188     * @return ParserOutput|false False on failure
189     */
190    public function get( RevisionRecord $revision, ParserOptions $parserOptions ) {
191        if ( $this->cacheExpiry <= 0 ) {
192            // disabled
193            return false;
194        }
195
196        if ( !$parserOptions->isSafeToCache() ) {
197            $this->incrementStats( $revision, 'miss', 'unsafe' );
198            return false;
199        }
200
201        $cacheKey = $this->makeParserOutputKey( $revision, $parserOptions );
202        $json = $this->cache->get( $cacheKey );
203
204        if ( $json === false ) {
205            $this->incrementStats( $revision, 'miss', 'absent' );
206            return false;
207        }
208
209        $output = $this->restoreFromJson( $json, $cacheKey );
210        if ( $output === null ) {
211            $this->incrementStats( $revision, 'miss', 'unserialize' );
212            return false;
213        }
214
215        $cacheTime = (int)MWTimestamp::convert( TS::UNIX, $output->getCacheTime() );
216        $expiryTime = (int)MWTimestamp::convert( TS::UNIX, $this->cacheEpoch );
217        $expiryTime = max( $expiryTime, (int)MWTimestamp::now( TS::UNIX ) - $this->cacheExpiry );
218
219        if ( $cacheTime < $expiryTime ) {
220            $this->incrementStats( $revision, 'miss', 'expired' );
221            return false;
222        }
223
224        $this->logger->debug( 'old-revision cache hit' );
225        $this->incrementStats( $revision, 'hit' );
226        return $output;
227    }
228
229    /**
230     * @param ParserOutput $output
231     * @param RevisionRecord $revision
232     * @param ParserOptions $parserOptions
233     * @param string|null $cacheTime TS::MW timestamp when the output was generated
234     */
235    public function save(
236        ParserOutput $output,
237        RevisionRecord $revision,
238        ParserOptions $parserOptions,
239        ?string $cacheTime = null
240    ) {
241        if ( !$output->hasText() ) {
242            throw new InvalidArgumentException( 'Attempt to cache a ParserOutput with no text set!' );
243        }
244
245        if ( $this->cacheExpiry <= 0 ) {
246            // disabled
247            return;
248        }
249
250        $cacheKey = $this->makeParserOutputKey( $revision, $parserOptions );
251
252        // Ensure cache properties are set in the ParserOutput
253        // T350538: These should be turned into assertions that the
254        // properties are already present (and the $cacheTime argument
255        // removed).
256        if ( $cacheTime ) {
257            $output->setCacheTime( $cacheTime );
258        } else {
259            $cacheTime = $output->getCacheTime();
260        }
261        if ( !$output->getCacheRevisionId() ) {
262            $output->setCacheRevisionId( $revision->getId() );
263        }
264        if ( !$output->getRenderId() ) {
265            $output->setRenderId( $this->globalIdGenerator->newUUIDv1() );
266        }
267        if ( !$output->getRevisionTimestamp() ) {
268            $output->setRevisionTimestamp( $revision->getTimestamp() );
269        }
270
271        $msg = "Saved in RevisionOutputCache with key $cacheKey" .
272            " and timestamp $cacheTime" .
273            " and revision id {$revision->getId()}.";
274
275        $output->addCacheMessage( $msg );
276
277        // The ParserOutput might be dynamic and have been marked uncacheable by the parser.
278        $output->updateCacheExpiry( $this->cacheExpiry, '$wgOldRevisionParserCacheExpireTime' );
279
280        $expiry = $output->getCacheExpiry();
281        if ( $expiry <= 0 ) {
282            $this->incrementStats( $revision, 'save', 'uncacheable' );
283            return;
284        }
285
286        if ( !$parserOptions->isSafeToCache() ) {
287            $this->incrementStats( $revision, 'save', 'unsafe' );
288            return;
289        }
290
291        $json = $this->encodeAsJson( $output, $cacheKey );
292        if ( $json === null ) {
293            $this->incrementStats( $revision, 'save', 'nonserializable' );
294            return;
295        }
296
297        $this->cache->set( $cacheKey, $json, $expiry );
298        $this->incrementStats( $revision, 'save', 'success' );
299        $this->incrementRenderReasonStats( $revision, $parserOptions->getRenderReason() );
300    }
301
302    /**
303     * @param string $jsonData
304     * @param string $key
305     * @return CacheTime|ParserOutput|null
306     */
307    private function restoreFromJson( string $jsonData, string $key ) {
308        try {
309            /** @var CacheTime $obj */
310            $obj = $this->jsonCodec->deserialize( $jsonData, ParserOutput::class );
311            return $obj;
312        } catch ( JsonException $e ) {
313            $this->logger->error( 'Unable to deserialize JSON', [
314                'name' => $this->name,
315                'cache_key' => $key,
316                'message' => $e->getMessage()
317            ] );
318            return null;
319        }
320    }
321
322    /**
323     * @param CacheTime $obj
324     * @param string $key
325     * @return string|null
326     */
327    private function encodeAsJson( CacheTime $obj, string $key ) {
328        try {
329            return $this->jsonCodec->serialize( $obj );
330        } catch ( JsonException $e ) {
331            $this->logger->error( 'Unable to serialize JSON', [
332                'name' => $this->name,
333                'cache_key' => $key,
334                'message' => $e->getMessage(),
335            ] );
336            return null;
337        }
338    }
339}