github.com/xmidt-org/webpa-common@v1.11.9/convey/conveymetric/metric.go (about)

     1  package conveymetric
     2  
     3  import (
     4  	"github.com/go-kit/kit/metrics"
     5  	"github.com/xmidt-org/webpa-common/convey"
     6  )
     7  
     8  // UnknownLabelValue is a constant for when key/tag can not be found in the C JSON.
     9  const UnknownLabelValue = "unknown"
    10  
    11  // Closure will be returned after Update(), this should be used to update the struct, aka decrement the count.
    12  type Closure func()
    13  
    14  // TagLabelPair is a convenient structure for inputs to create a new convey metric.
    15  type TagLabelPair struct {
    16  	Tag   string
    17  	Label string
    18  }
    19  
    20  // Interface provides a way of updating an internal resource.
    21  type Interface interface {
    22  	// Update takes the convey JSON to update internal struct, and return a closure to update the struct again, or an
    23  	// error
    24  	//
    25  	// Note: Closure should only be called once.
    26  	Update(data convey.C, labelPairs ...string) (Closure, error)
    27  }
    28  
    29  // NewConveyMetric produces an Interface where gauge is the internal structure to update, tag is the key in the C JSON
    30  // to update the gauge, and label is the `key` for the gauge cardinality.
    31  //
    32  // Note: The Gauge must have the label as one of the constant labels, (aka. the name of the gauge)
    33  func NewConveyMetric(gauge metrics.Gauge, pairs ...TagLabelPair) Interface {
    34  	return &cMetric{
    35  		pairs: pairs,
    36  		gauge: gauge,
    37  	}
    38  }
    39  
    40  // cMetric is the internal Interface implementation
    41  type cMetric struct {
    42  	pairs []TagLabelPair
    43  	gauge metrics.Gauge
    44  }
    45  
    46  func (m *cMetric) Update(data convey.C, baseLabelPairs ...string) (Closure, error) {
    47  	labelPairs := baseLabelPairs
    48  	for _, pair := range m.pairs {
    49  		labelValue := UnknownLabelValue
    50  		if item, ok := data[pair.Tag].(string); ok {
    51  			labelValue = item
    52  		}
    53  		labelPairs = append(labelPairs, pair.Label, labelValue)
    54  	}
    55  	m.gauge.With(labelPairs...).Add(1.0)
    56  	return func() { m.gauge.With(labelPairs...).Add(-1.0) }, nil
    57  }