o11y-8.x-1.x-dev/modules/o11y_metrics/modules/o11y_metrics_cache/src/Cache/CacheMetricsCacheTagsInvalidator.php
modules/o11y_metrics/modules/o11y_metrics_cache/src/Cache/CacheMetricsCacheTagsInvalidator.php
<?php
namespace Drupal\o11y_metrics_cache\Cache;
use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\o11y_metrics\Bridge\PrometheusBridgeInterface;
use Drupal\o11y_metrics\BaseMetricsSourceInterface;
/**
* Provides metrics about tag invalidations.
*/
class CacheMetricsCacheTagsInvalidator implements CacheTagsInvalidatorInterface, BaseMetricsSourceInterface {
/**
* The promphp bridge.
*
* @var \Drupal\o11y_metrics\Bridge\PrometheusBridgeInterface
*/
protected $promBridge;
/**
* Is this class enabled or not.
*
* @var bool
*/
protected $isEnabled;
/**
* The request_stack service.
*
* @var \Symfony\Component\HttpFoundation\RequestStack
*/
protected $requestStack;
/**
* A list of tags that have already been invalidated in this request.
*
* Used to prevent the recording of the same cache tag multiple times.
*
* @var string[]
*/
protected $invalidatedTags = [];
/**
* CacheMetricsCacheTagsInvalidator constructor.
*
* @param \Drupal\o11y_metrics\Bridge\PrometheusBridgeInterface $promBridge
* The promphp bridge.
* @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
* The request_stack service.
* @param bool $isEnabled
* Whether this class should do anything or not.
*/
public function __construct(
PrometheusBridgeInterface $promBridge,
RequestStack $requestStack,
bool $isEnabled
) {
$this->promBridge = $promBridge;
$this->requestStack = $requestStack;
$this->isEnabled = $isEnabled;
}
/**
* {@inheritdoc}
*/
public static function getMetricsSourceId(): string {
return 'cache_invalidations';
}
/**
* Log all Invalidations.
*
* @param string[] $tags
* The list of tags for which to invalidate cache items.
*/
public function invalidateTags(array $tags) {
if (!$this->isEnabled) {
return;
}
$request = $this->requestStack->getCurrentRequest();
foreach ($tags as $tag) {
// Only invalidate tags once per request unless they are written again.
if (isset($this->invalidatedTags[$tag])) {
continue;
}
$this->invalidatedTags[$tag] = TRUE;
$namespace_name_help = [
'drupal',
'cache_total_tag_invalidations',
'Total number of cache tag invalidations.',
];
$this->promBridge->getCounter(...$namespace_name_help, ...[[], $this])->inc();
$namespace_name_help[1] = 'cache_total_tag_invalidations_per_tag';
$this->promBridge->getCounter(
...$namespace_name_help,
...[['tag'], $this]
)->inc([$tag]);
$namespace_name_help[1] = 'cache_total_tag_invalidations_per_tag_and_request';
$this->promBridge->getCounter(
...$namespace_name_help,
...[['tag', 'request'], $this]
)->inc([
$tag,
$request->getBaseUrl() . $request->getPathInfo(),
]);
}
}
}
