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