From d20e5c455393bb6d929965ddee0efa082d9f4f6c Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Mon, 26 Dec 2022 13:31:50 +0100 Subject: [PATCH] feat: add counters --- collector.v | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++ counter_test.v | 8 +++++++ metrics.v | 26 +++++++++++++++++++++++ 3 files changed, 91 insertions(+) create mode 100644 collector.v create mode 100644 counter_test.v diff --git a/collector.v b/collector.v new file mode 100644 index 0000000..4c5df63 --- /dev/null +++ b/collector.v @@ -0,0 +1,57 @@ +module metrics + +import sync.stdatomic + +struct CounterEntry { + metric Metric + index int +} + +[heap] +struct DefaultMetricsCollector { +mut: + counters shared []u64 + counter_indexes shared map[string]CounterEntry +} + +pub fn new_default_metrics_collector() &DefaultMetricsCollector { + return &DefaultMetricsCollector{ + counters: []u64{} + counter_indexes: map[string]CounterEntry{} + } +} + +pub fn (mut c DefaultMetricsCollector) counter_register(value u64, metric Metric) { + new_index := lock c.counters { + c.counters << value + + c.counters.len - 1 + } + + lock c.counter_indexes { + c.counter_indexes[metric.str()] = CounterEntry{ + metric: metric + index: new_index + } + } +} + +pub fn (mut c DefaultMetricsCollector) counter_increment(metric Metric) { + entry := rlock c.counter_indexes { + c.counter_indexes[metric.str()] + } + + rlock c.counters { + stdatomic.add_u64(&c.counters[entry.index], 1) + } +} + +pub fn (mut c DefaultMetricsCollector) counter_decrement(metric Metric) { + entry := rlock c.counter_indexes { + c.counter_indexes[metric.str()] + } + + rlock c.counters { + stdatomic.sub_u64(&c.counters[entry.index], 1) + } +} diff --git a/counter_test.v b/counter_test.v new file mode 100644 index 0000000..f702d03 --- /dev/null +++ b/counter_test.v @@ -0,0 +1,8 @@ +import metrics + +fn test_counter_increment() { + mut m := new_default_metrics_collector() + m.counter_register(0, 'test') + + m.counter_increment('test') +} diff --git a/metrics.v b/metrics.v index e69de29..64702b3 100644 --- a/metrics.v +++ b/metrics.v @@ -0,0 +1,26 @@ +module metrics + +[params] +pub struct Metric { + name string [required] + labels [][2]string +} + +[inline] +fn join_two_array(arr [2]string) string { + return arr[0] + '=' + arr[1] +} + +pub fn (m &Metric) str() string { + if m.labels.len == 0 { + return m.name + } + + return '$m.name{${m.labels.map(join_two_array(it)).join(',')}}' +} + +interface MetricsCollector { + counter_register(value u64, metric Metric) + counter_increment(metric Metric) + counter_decrement(metric Metric) +}