Skip to content

Commit 50b70a6

Browse files
Ensure that label values are strings in APCNg adapter (#159)
* Ensure that label values are strings in APCNg adapter APCNg is crashing if the label value provided wasn't a string, but something that can be coerced to string (such as int). The problem occurs in two different places: - when a metric is emitted, the `storeLabelKeys()` calls into `addItemToKey()` which has its second parameter type hinted as a `string` and throws a type error if anything else is passed. This results in partially stored state; - when trying to scrape metrics with partially stored state, the `APCng::collect()` will try to build all the permutations and expect all the key-value pairs for labels to exist, but numeric label values aren't persisted and so it will cause the `Undefined array key` error as reported in #154; This change ensures that label values are cast to the string type before encoding them and using as APC keys. Signed-off-by: Garry Filakhtov <garry.filakhtov@bigcommerce.com> * Fix PHPStan issues Signed-off-by: Garry Filakhtov <garry.filakhtov@bigcommerce.com> --------- Signed-off-by: Garry Filakhtov <garry.filakhtov@bigcommerce.com>
1 parent 600f6df commit 50b70a6

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

src/Prometheus/Storage/APCng.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,7 @@ private function storeLabelKeys(array $data): void
254254
$data['name'],
255255
$label,
256256
'label'
257-
]), isset($data['labelValues']) ? $data['labelValues'][$seq] : ''); // may not need the isset check
257+
]), isset($data['labelValues']) ? (string)$data['labelValues'][$seq] : ''); // may not need the isset check
258258
}
259259
}
260260

@@ -860,7 +860,7 @@ private function sortSamples(array &$samples): void
860860
*/
861861
private function encodeLabelValues(array $values): string
862862
{
863-
$json = json_encode($values);
863+
$json = json_encode(array_map("strval", $values));
864864
if (false === $json) {
865865
throw new RuntimeException(json_last_error_msg());
866866
}

tests/Test/Prometheus/Storage/APCngTest.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,26 @@ public function itShouldNotClearWholeAPCacheOnFlush(): void
4242
);
4343
}
4444

45+
/**
46+
* @test
47+
*/
48+
public function nonStringLabelValuesAreCastToStrings(): void
49+
{
50+
apcu_clear_cache();
51+
52+
$adapter = new APCng();
53+
$registry = new CollectorRegistry($adapter);
54+
$registry->getOrRegisterCounter(
55+
'ns',
56+
'int_label_values',
57+
'test int label values',
58+
['int_label'],
59+
)->incBy(3, [3]);
60+
61+
$counter = apcu_fetch("prom:counter:ns_int_label_values:WyIzIl0=:value");
62+
self::assertSame(3000, $counter);
63+
}
64+
4565
/**
4666
* @test
4767
*/

0 commit comments

Comments
 (0)