Skip to content

Commit 59f6ac5

Browse files
committed
On flush remove only prometheus specific keys from APCu
Signed-off-by: Matouš Michalík <i@matousmichalik.com>
1 parent d576d10 commit 59f6ac5

File tree

2 files changed

+55
-1
lines changed

2 files changed

+55
-1
lines changed

src/Prometheus/Storage/APC.php

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,11 +109,21 @@ public function updateCounter(array $data): void
109109
}
110110

111111
/**
112+
* Removes all previously stored data from apcu
113+
*
112114
* @return void
113115
*/
114116
public function flushAPC(): void
115117
{
116-
apcu_clear_cache();
118+
// / / | PCRE expresion boundary
119+
// ^ | match from first character only
120+
// %s: | common prefix substitute with colon suffix
121+
// .+ | at least one additional character
122+
$matchAll = sprintf('/^%s:.+/', self::PROMETHEUS_PREFIX);
123+
124+
foreach (new APCUIterator($matchAll) as $key => $value) {
125+
apcu_delete($key);
126+
}
117127
}
118128

119129
/**
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Prometheus\Storage;
6+
7+
use APCuIterator;
8+
use PHPUnit\Framework\TestCase;
9+
use Prometheus\CollectorRegistry;
10+
11+
/**
12+
* @requires extension apcu
13+
*/
14+
class APCTest extends TestCase
15+
{
16+
17+
/**
18+
* @test
19+
*/
20+
public function itShouldNotClearWholeAPCacheOnFlush(): void
21+
{
22+
apcu_clear_cache();
23+
apcu_add("not a prometheus metric key", "data");
24+
25+
$apc = new APC();
26+
$registry = new CollectorRegistry($apc);
27+
$registry->getOrRegisterCounter("namespace", "counter", "counter help")->inc();
28+
$registry->getOrRegisterGauge("namespace", "gauge", "gauge help")->inc();
29+
$registry->getOrRegisterHistogram("namespace", "histogram", "histogram help")->observe(1);
30+
$apc->flushAPC();
31+
32+
$cacheEntries = iterator_to_array(new APCuIterator(null), true);
33+
$cacheMap = array_map(function ($item) {
34+
return $item['value'];
35+
}, $cacheEntries);
36+
37+
self::assertThat(
38+
$cacheMap,
39+
self::equalTo([
40+
'not a prometheus metric key' => 'data',
41+
])
42+
);
43+
}
44+
}

0 commit comments

Comments
 (0)