Debian Codegraph @

includes/parser/ParserCache.php

raw symbols SCIP
1 <?php
2 /**
3 * Cache for outputs of the PHP parser
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Cache Parser
22 */
23
24 namespace MediaWiki\Parser;
25
26 use Exception;
27 use InvalidArgumentException;
28 use JsonException;
29 use MediaWiki\HookContainer\HookContainer;
30 use MediaWiki\HookContainer\HookRunner;
31 use MediaWiki\Json\JsonCodec;
32 use MediaWiki\Page\PageRecord;
33 use MediaWiki\Page\WikiPageFactory;
34 use MediaWiki\Title\TitleFactory;
35 use Psr\Log\LoggerInterface;
36 use Wikimedia\ObjectCache\BagOStuff;
37 use Wikimedia\ObjectCache\EmptyBagOStuff;
38 use Wikimedia\ObjectCache\HashBagOStuff;
39 use Wikimedia\Stats\StatsFactory;
40 use Wikimedia\UUID\GlobalIdGenerator;
41
42 /**
43 * Cache for ParserOutput objects corresponding to the latest page revisions.
44 *
45 * The ParserCache is a two-tiered cache backed by BagOStuff which supports
46 * varying the stored content on the values of ParserOptions used during
47 * a page parse.
48 *
49 * First tier is keyed by the page ID and stores ParserCacheMetadata, which
50 * contains information about cache expiration and the list of ParserOptions
51 * used during the parse of the page. For example, if only 'dateformat' and
52 * 'userlang' options were accessed by the parser when producing output for the
53 * page, array [ 'dateformat', 'userlang' ] will be stored in the metadata cache.
54 * This means none of the other existing options had any effect on the output.
55 *
56 * The second tier of the cache contains ParserOutput objects. The key for the
57 * second tier is constructed from the page ID and values of those ParserOptions
58 * used during a page parse which affected the output. Upon cache lookup, the list
59 * of used option names is retrieved from tier 1 cache, and only the values of
60 * those options are hashed together with the page ID to produce a key, while
61 * the rest of the options are ignored. Following the example above where
62 * only [ 'dateformat', 'userlang' ] options changed the parser output for a
63 * page, the key will look like 'page_id!dateformat=default:userlang=ru'.
64 * Thus any cache lookup with dateformat=default and userlang=ru will hit the
65 * same cache entry regardless of the values of the rest of the options, since they
66 * were not accessed during a parse and thus did not change the output.
67 *
68 * @see ParserOutput::recordOption()
69 * @see ParserOutput::getUsedOptions()
70 * @see ParserOptions::allCacheVaryingOptions()
71 * @ingroup Cache Parser
72 */
73 class ParserCache {
74 /**
75 * Constants for self::getKey()
76 * @since 1.30
77 * @since 1.36 the constants were made public
78 */
79
80 /** Use only current data */
81 public const USE_CURRENT_ONLY = 0;
82
83 /** Use expired data if current data is unavailable */
84 public const USE_EXPIRED = 1;
85
86 /** Use expired data or data from different revisions if current data is unavailable */
87 public const USE_OUTDATED = 2;
88
89 /**
90 * Use expired data and data from different revisions, and if all else
91 * fails vary on all variable options
92 */
93 private const USE_ANYTHING = 3;
94
95 /** @var string The name of this ParserCache. Used as a root of the cache key. */
96 private $name;
97
98 /** @var BagOStuff */
99 private $cache;
100
101 /**
102 * Anything cached prior to this is invalidated
103 *
104 * @var string
105 */
106 private $cacheEpoch;
107
108 /** @var HookRunner */
109 private $hookRunner;
110
111 /** @var JsonCodec */
112 private $jsonCodec;
113
114 /** @var StatsFactory */
115 private $stats;
116
117 /** @var LoggerInterface */
118 private $logger;
119
120 /** @var TitleFactory */
121 private $titleFactory;
122
123 /** @var WikiPageFactory */
124 private $wikiPageFactory;
125
126 private ?ParserCacheFilter $filter = null;
127
128 private GlobalIdGenerator $globalIdGenerator;
129
130 /**
131 * @var BagOStuff small in-process cache to store metadata.
132 * It's needed multiple times during the request, for example
133 * to build a PoolWorkArticleView key, and then to fetch the
134 * actual ParserCache entry.
135 */
136 private $metadataProcCache;
137
138 /**
139 * Setup a cache pathway with a given back-end storage mechanism.
140 *
141 * This class use an invalidation strategy that is compatible with
142 * MultiWriteBagOStuff in async replication mode.
143 *
144 * @param string $name
145 * @param BagOStuff $cache
146 * @param string $cacheEpoch Anything before this timestamp is invalidated
147 * @param HookContainer $hookContainer
148 * @param JsonCodec $jsonCodec
149 * @param StatsFactory $stats
150 * @param LoggerInterface $logger
151 * @param TitleFactory $titleFactory
152 * @param WikiPageFactory $wikiPageFactory
153 * @param GlobalIdGenerator $globalIdGenerator
154 */
155 public function __construct(
156 string $name,
157 BagOStuff $cache,
158 string $cacheEpoch,
159 HookContainer $hookContainer,
160 JsonCodec $jsonCodec,
161 StatsFactory $stats,
162 LoggerInterface $logger,
163 TitleFactory $titleFactory,
164 WikiPageFactory $wikiPageFactory,
165 GlobalIdGenerator $globalIdGenerator
166 ) {
167 $this->name = $name;
168 $this->cache = $cache;
169 $this->cacheEpoch = $cacheEpoch;
170 $this->hookRunner = new HookRunner( $hookContainer );
171 $this->jsonCodec = $jsonCodec;
172 $this->stats = $stats;
173 $this->logger = $logger;
174 $this->titleFactory = $titleFactory;
175 $this->wikiPageFactory = $wikiPageFactory;
176 $this->globalIdGenerator = $globalIdGenerator;
177 $this->metadataProcCache = new HashBagOStuff( [ 'maxKeys' => 2 ] );
178 }
179
180 /**
181 * @since 1.41
182 * @param ParserCacheFilter $filter
183 */
184 public function setFilter( ParserCacheFilter $filter ): void {
185 $this->filter = $filter;
186 }
187
188 /**
189 * @param PageRecord $page
190 * @since 1.28
191 */
192 public function deleteOptionsKey( PageRecord $page ) {
193 $page->assertWiki( PageRecord::LOCAL );
194 $key = $this->makeMetadataKey( $page );
195 $this->metadataProcCache->delete( $key );
196 $this->cache->delete( $key );
197 }
198
199 /**
200 * Retrieve the ParserOutput from ParserCache, even if it's outdated.
201 * @param PageRecord $page
202 * @param ParserOptions $popts
203 * @return ParserOutput|false
204 */
205 public function getDirty( PageRecord $page, $popts ) {
206 $page->assertWiki( PageRecord::LOCAL );
207 $value = $this->get( $page, $popts, true );
208 return is_object( $value ) ? $value : false;
209 }
210
211 /**
212 * @param PageRecord $page
213 * @return string
214 */
215 private function getContentModelFromPage( PageRecord $page ) {
216 $wikiPage = $this->wikiPageFactory->newFromTitle( $page );
217 return str_replace( '.', '_', $wikiPage->getContentModel() );
218 }
219
220 /**
221 * @param PageRecord $page
222 * @param string $status
223 * @param string|null $reason
224 */
225 private function incrementStats( PageRecord $page, $status, $reason = null ) {
226 $contentModel = $this->getContentModelFromPage( $page );
227 $metricSuffix = $reason ? "{$status}_{$reason}" : $status;
228
229 $this->stats->getCounter( 'ParserCache_operation_total' )
230 ->setLabel( 'name', $this->name )
231 ->setLabel( 'contentModel', $contentModel )
232 ->setLabel( 'status', $status )
233 ->setLabel( 'reason', $reason ?: 'n/a' )
234 ->copyToStatsdAt( "{$this->name}.{$contentModel}.{$metricSuffix}" )
235 ->increment();
236 }
237
238 /**
239 * @param PageRecord $page
240 * @param string $renderReason
241 */
242 private function incrementRenderReasonStats( PageRecord $page, $renderReason ) {
243 $contentModel = $this->getContentModelFromPage( $page );
244 $renderReason = preg_replace( '/\W+/', '_', $renderReason );
245
246 $this->stats->getCounter( 'ParserCache_render_total' )
247 ->setLabel( 'name', $this->name )
248 ->setLabel( 'contentModel', $contentModel )
249 ->setLabel( 'reason', $renderReason )
250 ->copyToStatsdAt( "{$this->name}.{$contentModel}.reason.{$renderReason}" )
251 ->increment();
252 }
253
254 /**
255 * Returns the ParserCache metadata about the given page
256 * considering the given options.
257 *
258 * @note Which parser options influence the cache key
259 * is controlled via ParserOutput::recordOption() or
260 * ParserOptions::addExtraKey().
261 *
262 * @param PageRecord $page
263 * @param int $staleConstraint one of the self::USE_ constants
264 * @return ParserCacheMetadata|null
265 * @since 1.36
266 */
267 public function getMetadata(
268 PageRecord $page,
269 int $staleConstraint = self::USE_ANYTHING
270 ): ?ParserCacheMetadata {
271 $page->assertWiki( PageRecord::LOCAL );
272
273 $pageKey = $this->makeMetadataKey( $page );
274 $metadata = $this->metadataProcCache->get( $pageKey );
275 if ( !$metadata ) {
276 $metadata = $this->cache->get(
277 $pageKey,
278 BagOStuff::READ_VERIFIED
279 );
280 }
281
282 if ( $metadata === false ) {
283 $this->incrementStats( $page, 'miss', 'absent_metadata' );
284 $this->logger->debug( 'ParserOutput metadata cache miss', [ 'name' => $this->name ] );
285 return null;
286 }
287
288 // NOTE: If the value wasn't serialized to JSON when being stored,
289 // we may already have a ParserOutput object here. This used
290 // to be the default behavior before 1.36. We need to retain
291 // support so we can handle cached objects after an update
292 // from an earlier revision.
293 // NOTE: Support for reading string values from the cache must be
294 // deployed a while before starting to write JSON to the cache,
295 // in case we have to revert either change.
296 if ( is_string( $metadata ) ) {
297 $metadata = $this->restoreFromJson( $metadata, $pageKey, CacheTime::class );
298 }
299
300 if ( !$metadata instanceof CacheTime ) {
301 $this->incrementStats( $page, 'miss', 'unserialize' );
302 return null;
303 }
304
305 if ( $this->checkExpired( $metadata, $page, $staleConstraint, 'metadata' ) ) {
306 return null;
307 }
308
309 if ( $this->checkOutdated( $metadata, $page, $staleConstraint, 'metadata' ) ) {
310 return null;
311 }
312
313 $this->logger->debug( 'Parser cache options found', [ 'name' => $this->name ] );
314 return $metadata;
315 }
316
317 /**
318 * @param PageRecord $page
319 * @return string
320 */
321 private function makeMetadataKey( PageRecord $page ): string {
322 return $this->cache->makeKey( $this->name, 'idoptions', $page->getId( PageRecord::LOCAL ) );
323 }
324
325 /**
326 * Get a key that will be used by the ParserCache to store the content
327 * for a given page considering the given options and the array of
328 * used options.
329 *
330 * @warning The exact format of the key is considered internal and is subject
331 * to change, thus should not be used as storage or long-term caching key.
332 * This is intended to be used for logging or keying something transient.
333 *
334 * @param PageRecord $page
335 * @param ParserOptions $options
336 * @param array|null $usedOptions Defaults to all cache varying options.
337 * @return string
338 * @internal
339 * @since 1.36
340 */
341 public function makeParserOutputKey(
342 PageRecord $page,
343 ParserOptions $options,
344 ?array $usedOptions = null
345 ): string {
346 $usedOptions ??= ParserOptions::allCacheVaryingOptions();
347 // idhash seem to mean 'page id' + 'rendering hash' (r3710)
348 $pageid = $page->getId( PageRecord::LOCAL );
349 $title = $this->titleFactory->newFromPageIdentity( $page );
350 $hash = $options->optionsHash( $usedOptions, $title );
351 // Before T263581 ParserCache was split between normal page views
352 // and action=parse. -0 is left in the key to avoid invalidating the entire
353 // cache when removing the cache split.
354 return $this->cache->makeKey( $this->name, 'idhash', "{$pageid}-0!{$hash}" );
355 }
356
357 /**
358 * Retrieve the ParserOutput from ParserCache.
359 * false if not found or outdated.
360 *
361 * @param PageRecord $page
362 * @param ParserOptions $popts
363 * @param bool $useOutdated (default false)
364 *
365 * @return ParserOutput|false
366 */
367 public function get( PageRecord $page, $popts, $useOutdated = false ) {
368 $page->assertWiki( PageRecord::LOCAL );
369
370 if ( !$page->exists() ) {
371 $this->incrementStats( $page, 'miss', 'nonexistent' );
372 return false;
373 }
374
375 if ( $page->isRedirect() ) {
376 // It's a redirect now
377 $this->incrementStats( $page, 'miss', 'redirect' );
378 return false;
379 }
380
381 $staleConstraint = $useOutdated ? self::USE_OUTDATED : self::USE_CURRENT_ONLY;
382 $parserOutputMetadata = $this->getMetadata( $page, $staleConstraint );
383 if ( !$parserOutputMetadata ) {
384 return false;
385 }
386
387 if ( !$popts->isSafeToCache( $parserOutputMetadata->getUsedOptions() ) ) {
388 $this->incrementStats( $page, 'miss', 'unsafe' );
389 return false;
390 }
391
392 $parserOutputKey = $this->makeParserOutputKey(
393 $page,
394 $popts,
395 $parserOutputMetadata->getUsedOptions()
396 );
397
398 $value = $this->cache->get( $parserOutputKey, BagOStuff::READ_VERIFIED );
399 if ( $value === false ) {
400 $this->incrementStats( $page, 'miss', 'absent' );
401 $this->logger->debug( 'ParserOutput cache miss', [ 'name' => $this->name ] );
402 return false;
403 }
404
405 // NOTE: If the value wasn't serialized to JSON when being stored,
406 // we may already have a ParserOutput object here. This used
407 // to be the default behavior before 1.36. We need to retain
408 // support so we can handle cached objects after an update
409 // from an earlier revision.
410 // NOTE: Support for reading string values from the cache must be
411 // deployed a while before starting to write JSON to the cache,
412 // in case we have to revert either change.
413 if ( is_string( $value ) ) {
414 $value = $this->restoreFromJson( $value, $parserOutputKey, ParserOutput::class );
415 }
416
417 if ( !$value instanceof ParserOutput ) {
418 $this->incrementStats( $page, 'miss', 'unserialize' );
419 return false;
420 }
421
422 if ( $this->checkExpired( $value, $page, $staleConstraint, 'output' ) ) {
423 return false;
424 }
425
426 if ( $this->checkOutdated( $value, $page, $staleConstraint, 'output' ) ) {
427 return false;
428 }
429
430 $wikiPage = $this->wikiPageFactory->newFromTitle( $page );
431 if ( $this->hookRunner->onRejectParserCacheValue( $value, $wikiPage, $popts ) === false ) {
432 $this->incrementStats( $page, 'miss', 'rejected' );
433 $this->logger->debug( 'key valid, but rejected by RejectParserCacheValue hook handler',
434 [ 'name' => $this->name ] );
435 return false;
436 }
437
438 $this->logger->debug( 'ParserOutput cache found', [ 'name' => $this->name ] );
439 $this->incrementStats( $page, 'hit' );
440 return $value;
441 }
442
443 /**
444 * @param ParserOutput $parserOutput
445 * @param PageRecord $page
446 * @param ParserOptions $popts
447 * @param string|null $cacheTime TS_MW timestamp when the cache was generated
448 * @param int|null $revId Revision ID that was parsed
449 */
450 public function save(
451 ParserOutput $parserOutput,
452 PageRecord $page,
453 $popts,
454 $cacheTime = null,
455 $revId = null
456 ) {
457 $page->assertWiki( PageRecord::LOCAL );
458 // T350538: Eventually we'll warn if the $cacheTime and $revId
459 // parameters are non-null here, since we *should* be getting
460 // them from the ParserOutput.
461 if ( $revId !== null && $revId !== $parserOutput->getCacheRevisionId() ) {
462 $this->logger->warning(
463 'Inconsistent revision ID',
464 [
465 'name' => $this->name,
466 'reason' => $popts->getRenderReason(),
467 'revid1' => $revId,
468 'revid2' => $parserOutput->getCacheRevisionId(),
469 ]
470 );
471 }
472
473 if ( !$parserOutput->hasText() ) {
474 throw new InvalidArgumentException( 'Attempt to cache a ParserOutput with no text set!' );
475 }
476
477 $expire = $parserOutput->getCacheExpiry();
478
479 if ( !$popts->isSafeToCache( $parserOutput->getUsedOptions() ) ) {
480 $this->logger->debug(
481 'Parser options are not safe to cache and has not been saved',
482 [ 'name' => $this->name ]
483 );
484 $this->incrementStats( $page, 'save', 'unsafe' );
485 return;
486 }
487
488 if ( $expire <= 0 ) {
489 $this->logger->debug(
490 'Parser output was marked as uncacheable and has not been saved',
491 [ 'name' => $this->name ]
492 );
493 $this->incrementStats( $page, 'save', 'uncacheable' );
494 return;
495 }
496
497 if ( $this->filter && !$this->filter->shouldCache( $parserOutput, $page, $popts ) ) {
498 $this->logger->debug(
499 'Parser output was filtered and has not been saved',
500 [ 'name' => $this->name ]
501 );
502 $this->incrementStats( $page, 'save', 'filtered' );
503
504 // TODO: In this case, we still want to cache in RevisionOutputCache (T350669).
505 return;
506 }
507
508 if ( $this->cache instanceof EmptyBagOStuff ) {
509 return;
510 }
511
512 // Ensure cache properties are set in the ParserOutput
513 // T350538: These should be turned into assertions that the
514 // properties are already present.
515 if ( $cacheTime ) {
516 $parserOutput->setCacheTime( $cacheTime );
517 } else {
518 if ( !$parserOutput->hasCacheTime() ) {
519 $this->logger->warning(
520 'No cache time set',
521 [
522 'name' => $this->name,
523 'reason' => $popts->getRenderReason(),
524 ]
525 );
526 }
527 $cacheTime = $parserOutput->getCacheTime();
528 }
529
530 if ( $revId ) {
531 $parserOutput->setCacheRevisionId( $revId );
532 } elseif ( $parserOutput->getCacheRevisionId() ) {
533 $revId = $parserOutput->getCacheRevisionId();
534 } else {
535 $revId = $page->getLatest( PageRecord::LOCAL );
536 $parserOutput->setCacheRevisionId( $revId );
537 }
538 if ( !$revId ) {
539 $this->logger->warning(
540 'Parser output cannot be saved if the revision ID is not known',
541 [ 'name' => $this->name ]
542 );
543 $this->incrementStats( $page, 'save', 'norevid' );
544 return;
545 }
546
547 if ( !$parserOutput->getRenderId() ) {
548 $this->logger->warning(
549 'Parser output missing render ID',
550 [
551 'name' => $this->name,
552 'reason' => $popts->getRenderReason(),
553 ]
554 );
555 $parserOutput->setRenderId( $this->globalIdGenerator->newUUIDv1() );
556 }
557
558 // Transfer cache properties to the cache metadata
559 $metadata = new CacheTime;
560 $metadata->recordOptions( $parserOutput->getUsedOptions() );
561 $metadata->updateCacheExpiry( $expire );
562 $metadata->setCacheTime( $cacheTime );
563 $metadata->setCacheRevisionId( $revId );
564
565 $parserOutputKey = $this->makeParserOutputKey(
566 $page,
567 $popts,
568 $metadata->getUsedOptions()
569 );
570
571 $msg = "Saved in parser cache with key $parserOutputKey" .
572 " and timestamp $cacheTime" .
573 " and revision id $revId.";
574
575 $reason = $popts->getRenderReason();
576 $msg .= " Rendering was triggered because: $reason";
577
578 $parserOutput->addCacheMessage( $msg );
579
580 $pageKey = $this->makeMetadataKey( $page );
581
582 $parserOutputData = $this->convertForCache( $parserOutput, $parserOutputKey );
583 $metadataData = $this->convertForCache( $metadata, $pageKey );
584
585 if ( !$parserOutputData || !$metadataData ) {
586 $this->logger->warning(
587 'Parser output failed to serialize and was not saved',
588 [ 'name' => $this->name ]
589 );
590 $this->incrementStats( $page, 'save', 'nonserializable' );
591 return;
592 }
593
594 // Save the parser output
595 $this->cache->set(
596 $parserOutputKey,
597 $parserOutputData,
598 $expire,
599 BagOStuff::WRITE_ALLOW_SEGMENTS
600 );
601
602 // ...and its pointer to the local cache.
603 $this->metadataProcCache->set( $pageKey, $metadataData, $expire );
604 // ...and to the global cache.
605 $this->cache->set( $pageKey, $metadataData, $expire );
606
607 $title = $this->titleFactory->newFromPageIdentity( $page );
608 $this->hookRunner->onParserCacheSaveComplete( $this, $parserOutput, $title, $popts, $revId );
609
610 $this->logger->debug( 'Saved in parser cache', [
611 'name' => $this->name,
612 'key' => $parserOutputKey,
613 'cache_time' => $cacheTime,
614 'rev_id' => $revId
615 ] );
616 $this->incrementStats( $page, 'save', 'success' );
617 $this->incrementRenderReasonStats( $page, $popts->getRenderReason() );
618 }
619
620 /**
621 * Get the backend BagOStuff instance that
622 * powers the parser cache
623 *
624 * @since 1.30
625 * @internal
626 * @return BagOStuff
627 */
628 public function getCacheStorage() {
629 return $this->cache;
630 }
631
632 /**
633 * Check if $entry expired for $page given the $staleConstraint
634 * when fetching from $cacheTier.
635 * @param CacheTime $entry
636 * @param PageRecord $page
637 * @param int $staleConstraint One of USE_* constants.
638 * @param string $cacheTier
639 * @return bool
640 */
641 private function checkExpired(
642 CacheTime $entry,
643 PageRecord $page,
644 int $staleConstraint,
645 string $cacheTier
646 ): bool {
647 if ( $staleConstraint < self::USE_EXPIRED && $entry->expired( $page->getTouched() ) ) {
648 $this->incrementStats( $page, 'miss', 'expired' );
649 $this->logger->debug( "{$cacheTier} key expired", [
650 'name' => $this->name,
651 'touched' => $page->getTouched(),
652 'epoch' => $this->cacheEpoch,
653 'cache_time' => $entry->getCacheTime()
654 ] );
655 return true;
656 }
657 return false;
658 }
659
660 /**
661 * Check if $entry belongs to the latest revision of $page
662 * given $staleConstraint when fetched from $cacheTier.
663 * @param CacheTime $entry
664 * @param PageRecord $page
665 * @param int $staleConstraint One of USE_* constants.
666 * @param string $cacheTier
667 * @return bool
668 */
669 private function checkOutdated(
670 CacheTime $entry,
671 PageRecord $page,
672 int $staleConstraint,
673 string $cacheTier
674 ): bool {
675 $latestRevId = $page->getLatest( PageRecord::LOCAL );
676 if ( $staleConstraint < self::USE_OUTDATED && $entry->isDifferentRevision( $latestRevId ) ) {
677 $this->incrementStats( $page, 'miss', 'revid' );
678 $this->logger->debug( "{$cacheTier} key is for an old revision", [
679 'name' => $this->name,
680 'rev_id' => $latestRevId,
681 'cached_rev_id' => $entry->getCacheRevisionId()
682 ] );
683 return true;
684 }
685 return false;
686 }
687
688 /**
689 * @param string $jsonData
690 * @param string $key
691 * @param string $expectedClass
692 * @return CacheTime|ParserOutput|null
693 */
694 private function restoreFromJson( string $jsonData, string $key, string $expectedClass ) {
695 try {
696 /** @var CacheTime $obj */
697 $obj = $this->jsonCodec->deserialize( $jsonData, $expectedClass );
698 return $obj;
699 } catch ( JsonException $e ) {
700 $this->logger->error( "Unable to deserialize JSON", [
701 'name' => $this->name,
702 'cache_key' => $key,
703 'ex_message' => $e->getMessage()
704 ] );
705 return null;
706 } catch ( Exception $e ) {
707 $this->logger->error( "Unexpected failure during cache load", [
708 'name' => $this->name,
709 'cache_key' => $key,
710 'ex_message' => $e->getMessage()
711 ] );
712 return null;
713 }
714 }
715
716 /**
717 * @param CacheTime $obj
718 * @param string $key
719 * @return string|null
720 */
721 protected function convertForCache( CacheTime $obj, string $key ) {
722 try {
723 return $this->jsonCodec->serialize( $obj );
724 } catch ( JsonException $e ) {
725 // Try to collect some additional debugging information, but
726 // wrap this in a try block to ensure we don't make the problem
727 // worse.
728 try {
729 $details = $this->jsonCodec->detectNonSerializableData( $obj, true );
730 } catch ( \Throwable $t ) {
731 $details = $t->getMessage();
732 }
733 $this->logger->error( "Unable to serialize JSON", [
734 'name' => $this->name,
735 'cache_key' => $key,
736 'ex_message' => $e->getMessage(),
737 'details' => $details,
738 'trace' => $e->getTraceAsString(),
739 ] );
740 return null;
741 }
742 }
743 }
744
745 /** @deprecated class alias since 1.43 */
746 class_alias( ParserCache::class, 'ParserCache' );