github.com/Jeffail/benthos/v3@v3.65.0/internal/bundle/metrics.go (about)

     1  package bundle
     2  
     3  import (
     4  	"sort"
     5  
     6  	"github.com/Jeffail/benthos/v3/internal/docs"
     7  	"github.com/Jeffail/benthos/v3/lib/metrics"
     8  )
     9  
    10  // AllMetrics is a set containing every single metrics that has been imported.
    11  var AllMetrics = &MetricsSet{
    12  	specs: map[string]metricsSpec{},
    13  }
    14  
    15  //------------------------------------------------------------------------------
    16  
    17  // MetricConstructor constructs an metrics component.
    18  type MetricConstructor metrics.ConstructorFunc
    19  
    20  type metricsSpec struct {
    21  	constructor MetricConstructor
    22  	spec        docs.ComponentSpec
    23  }
    24  
    25  // MetricsSet contains an explicit set of metrics available to a Benthos
    26  // service.
    27  type MetricsSet struct {
    28  	specs map[string]metricsSpec
    29  }
    30  
    31  // Add a new metrics to this set by providing a spec (name, documentation, and
    32  // constructor).
    33  func (s *MetricsSet) Add(constructor MetricConstructor, spec docs.ComponentSpec) error {
    34  	if s.specs == nil {
    35  		s.specs = map[string]metricsSpec{}
    36  	}
    37  	s.specs[spec.Name] = metricsSpec{
    38  		constructor: constructor,
    39  		spec:        spec,
    40  	}
    41  	docs.RegisterDocs(spec)
    42  	return nil
    43  }
    44  
    45  // Init attempts to initialise an metrics from a config.
    46  func (s *MetricsSet) Init(conf metrics.Config, opts ...func(metrics.Type)) (metrics.Type, error) {
    47  	spec, exists := s.specs[conf.Type]
    48  	if !exists {
    49  		return nil, metrics.ErrInvalidMetricOutputType
    50  	}
    51  	return spec.constructor(conf, opts...)
    52  }
    53  
    54  // Docs returns a slice of metrics specs, which document each method.
    55  func (s *MetricsSet) Docs() []docs.ComponentSpec {
    56  	var docs []docs.ComponentSpec
    57  	for _, v := range s.specs {
    58  		docs = append(docs, v.spec)
    59  	}
    60  	sort.Slice(docs, func(i, j int) bool {
    61  		return docs[i].Name < docs[j].Name
    62  	})
    63  	return docs
    64  }
    65  
    66  // DocsFor returns the documentation for a given component name, returns a
    67  // boolean indicating whether the component name exists.
    68  func (s *MetricsSet) DocsFor(name string) (docs.ComponentSpec, bool) {
    69  	c, ok := s.specs[name]
    70  	if !ok {
    71  		return docs.ComponentSpec{}, false
    72  	}
    73  	return c.spec, true
    74  }