feat: add counters
parent
8f267b0ffc
commit
d20e5c4553
|
@ -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)
|
||||
}
|
||||
}
|
|
@ -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')
|
||||
}
|
26
metrics.v
26
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)
|
||||
}
|
Loading…
Reference in New Issue