nextcloud/lib/private/OpenMetrics/Exporters/Cached.php
Benjamin Gaussorgues 509784cff2
chore(metrics): harden Cached exporter
Signed-off-by: Benjamin Gaussorgues <benjamin.gaussorgues@nextcloud.com>
2026-03-11 13:01:21 +01:00

65 lines
1.2 KiB
PHP

<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OC\OpenMetrics\Exporters;
use Generator;
use OCP\ICache;
use OCP\ICacheFactory;
use OCP\OpenMetrics\IMetricFamily;
use OCP\OpenMetrics\Metric;
use OCP\OpenMetrics\MetricValue;
use Override;
/**
* Cached metrics
*/
abstract class Cached implements IMetricFamily {
private readonly ICache $cache;
public function __construct(
ICacheFactory $cacheFactory,
) {
$this->cache = $cacheFactory->createDistributed('openmetrics');
}
/**
* Number of seconds to keep the results
*/
abstract public function getTTL(): int;
/**
* Actually gather the metrics
*
* @see metrics
*/
abstract public function gatherMetrics(): Generator;
#[Override]
public function metrics(): Generator {
$cacheKey = static::class;
if ($data = $this->cache->get($cacheKey)) {
yield from unserialize(
$data,
[
'allowed_classes' => [Metric::class, MetricValue::class],
],
);
return;
}
$data = [];
foreach ($this->gatherMetrics() as $metric) {
yield $metric;
$data[] = $metric;
}
$this->cache->set($cacheKey, serialize($data), $this->getTTL());
}
}