grafana/pkg/bus/bus.go

87 lines
2.1 KiB
Go
Raw Normal View History

2014-11-28 15:16:49 -06:00
package bus
import (
"context"
"errors"
"fmt"
2014-11-28 15:16:49 -06:00
"reflect"
"go.opentelemetry.io/otel/attribute"
"github.com/grafana/grafana/pkg/infra/tracing"
2014-11-28 15:16:49 -06:00
)
// HandlerFunc defines a handler function interface.
2014-12-16 09:45:07 -06:00
type HandlerFunc interface{}
// Msg defines a message interface.
2014-12-16 09:45:07 -06:00
type Msg interface{}
2014-11-28 15:16:49 -06:00
// ErrHandlerNotFound defines an error if a handler is not found.
var ErrHandlerNotFound = errors.New("handler not found")
// Bus type defines the bus interface structure.
2014-12-01 10:56:03 -06:00
type Bus interface {
Publish(ctx context.Context, msg Msg) error
AddEventListener(handler HandlerFunc)
}
// InProcBus defines the bus structure.
2014-12-01 10:56:03 -06:00
type InProcBus struct {
listeners map[string][]HandlerFunc
tracer tracing.Tracer
2014-12-01 10:56:03 -06:00
}
2014-11-28 15:16:49 -06:00
func ProvideBus(tracer tracing.Tracer) *InProcBus {
return &InProcBus{
listeners: make(map[string][]HandlerFunc),
tracer: tracer,
}
2014-11-28 15:16:49 -06:00
}
// Publish function publish a message to the bus listener.
func (b *InProcBus) Publish(ctx context.Context, msg Msg) error {
var msgName = reflect.TypeOf(msg).Elem().Name()
var params = []reflect.Value{}
if listeners, exists := b.listeners[msgName]; exists {
params = append(params, reflect.ValueOf(ctx))
params = append(params, reflect.ValueOf(msg))
if err := callListeners(listeners, params); err != nil {
return err
}
}
_, span := b.tracer.Start(ctx, "bus - "+msgName)
defer span.End()
span.SetAttributes("msg", msgName, attribute.Key("msg").String(msgName))
return nil
}
func callListeners(listeners []HandlerFunc, params []reflect.Value) error {
for _, listenerHandler := range listeners {
2015-01-09 09:36:23 -06:00
ret := reflect.ValueOf(listenerHandler).Call(params)
e := ret[0].Interface()
if e != nil {
err, ok := e.(error)
if ok {
return err
}
return fmt.Errorf("expected listener to return an error, got '%T'", e)
2015-01-09 09:36:23 -06:00
}
}
return nil
}
func (b *InProcBus) AddEventListener(handler HandlerFunc) {
handlerType := reflect.TypeOf(handler)
eventName := handlerType.In(1).Elem().Name()
_, exists := b.listeners[eventName]
if !exists {
b.listeners[eventName] = make([]HandlerFunc, 0)
}
b.listeners[eventName] = append(b.listeners[eventName], handler)
}