Skip to content

Commit 5d27b6d

Browse files
Fix tracking of float counters in Redis (#42)
* Fix the check for new counters when using floats Signed-off-by: Justin Nuß <[email protected]> Co-authored-by: Lukas Kämmerling <[email protected]>
1 parent fd1aaac commit 5d27b6d

File tree

3 files changed

+30
-6
lines changed

3 files changed

+30
-6
lines changed

examples/some_counter.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,11 @@
1717
}
1818
$registry = new CollectorRegistry($adapter);
1919

20+
$count = preg_match('/^[0-9]+$/', $_GET['c'])
21+
? intval($_GET['c'])
22+
: floatval($_GET['c']);
23+
2024
$counter = $registry->registerCounter('test', 'some_counter', 'it increases', ['type']);
21-
$counter->incBy($_GET['c'], ['blue']);
25+
$counter->incBy($count, ['blue']);
2226

2327
echo "OK\n";

src/Prometheus/Storage/Redis.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -288,9 +288,9 @@ public function updateCounter(array $data): void
288288
$this->redis->eval(
289289
<<<LUA
290290
local result = redis.call(ARGV[1], KEYS[1], ARGV[3], ARGV[2])
291-
if result == tonumber(ARGV[2]) then
291+
local added = redis.call('sAdd', KEYS[2], KEYS[1])
292+
if added == 1 then
292293
redis.call('hMSet', KEYS[1], '__meta', ARGV[4])
293-
redis.call('sAdd', KEYS[2], KEYS[1])
294294
end
295295
return result
296296
LUA

tests/Test/BlackBoxTest.php

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,15 +64,24 @@ public function gaugesShouldBeOverwritten(): void
6464

6565
/**
6666
* @test
67+
* @dataProvider countersDataProvider
68+
* @param int|float $increment
6769
*/
68-
public function countersShouldIncrementAtomically(): void
70+
public function countersShouldIncrementAtomically($increment): void
6971
{
7072
$start = microtime(true);
7173
$promises = [];
7274
$sum = 0;
75+
$n = $increment;
7376
for ($i = 0; $i < 1100; $i++) {
74-
$promises[] = $this->client->getAsync('/examples/some_counter.php?c=' . $i . '&adapter=' . $this->adapter);
75-
$sum += $i;
77+
if (is_float($n)) {
78+
$url = '/examples/some_counter.php?c=' . number_format($n, 2) . '&adapter=' . $this->adapter;
79+
} else {
80+
$url = '/examples/some_counter.php?c=' . $n . '&adapter=' . $this->adapter;
81+
}
82+
$promises[] = $this->client->getAsync($url);
83+
$sum += $n;
84+
$n += $increment;
7685
}
7786

7887
Promise\settle($promises)->wait();
@@ -85,6 +94,17 @@ public function countersShouldIncrementAtomically(): void
8594
self::assertThat($body, self::stringContains('test_some_counter{type="blue"} ' . $sum));
8695
}
8796

97+
/**
98+
* @return array<int, array<float|int>>
99+
*/
100+
public function countersDataProvider(): array
101+
{
102+
return [
103+
[1],
104+
[0.5]
105+
];
106+
}
107+
88108
/**
89109
* @test
90110
*/

0 commit comments

Comments
 (0)