github.com/safing/portbase@v0.19.5/metrics/metric_counter_fetching.go (about)

     1  package metrics
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  
     7  	vm "github.com/VictoriaMetrics/metrics"
     8  )
     9  
    10  // FetchingCounter is a counter metric that fetches the values via a function call.
    11  type FetchingCounter struct {
    12  	*metricBase
    13  	counter  *vm.Counter
    14  	fetchCnt func() uint64
    15  }
    16  
    17  // NewFetchingCounter registers a new fetching counter metric.
    18  func NewFetchingCounter(id string, labels map[string]string, fn func() uint64, opts *Options) (*FetchingCounter, error) {
    19  	// Check if a fetch function is provided.
    20  	if fn == nil {
    21  		return nil, fmt.Errorf("%w: no fetch function provided", ErrInvalidOptions)
    22  	}
    23  
    24  	// Ensure that there are options.
    25  	if opts == nil {
    26  		opts = &Options{}
    27  	}
    28  
    29  	// Make base.
    30  	base, err := newMetricBase(id, labels, *opts)
    31  	if err != nil {
    32  		return nil, err
    33  	}
    34  
    35  	// Create metric struct.
    36  	m := &FetchingCounter{
    37  		metricBase: base,
    38  		fetchCnt:   fn,
    39  	}
    40  
    41  	// Create metric in set
    42  	m.counter = m.set.NewCounter(m.LabeledID())
    43  
    44  	// Register metric.
    45  	err = register(m)
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  
    50  	return m, nil
    51  }
    52  
    53  // CurrentValue returns the current counter value.
    54  func (fc *FetchingCounter) CurrentValue() uint64 {
    55  	return fc.fetchCnt()
    56  }
    57  
    58  // WritePrometheus writes the metric in the prometheus format to the given writer.
    59  func (fc *FetchingCounter) WritePrometheus(w io.Writer) {
    60  	fc.counter.Set(fc.fetchCnt())
    61  	fc.metricBase.set.WritePrometheus(w)
    62  }