zrok/controller/metrics/bridge.go

79 lines
1.4 KiB
Go
Raw Normal View History

2023-03-15 21:14:06 +01:00
package metrics
2023-03-15 18:49:17 +01:00
import (
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
type BridgeConfig struct {
Source interface{}
Sink interface{}
}
type Bridge struct {
src ZitiEventJsonSource
srcJoin chan struct{}
snk ZitiEventJsonSink
2023-05-01 20:45:45 +02:00
events chan ZitiEventMsg
2023-03-15 18:49:17 +01:00
close chan struct{}
join chan struct{}
}
func NewBridge(cfg *BridgeConfig) (*Bridge, error) {
b := &Bridge{
2023-05-01 20:45:45 +02:00
events: make(chan ZitiEventMsg),
2023-03-15 18:49:17 +01:00
join: make(chan struct{}),
close: make(chan struct{}),
}
if v, ok := cfg.Source.(ZitiEventJsonSource); ok {
b.src = v
} else {
return nil, errors.New("invalid source type")
}
if v, ok := cfg.Sink.(ZitiEventJsonSink); ok {
b.snk = v
} else {
return nil, errors.New("invalid sink type")
}
return b, nil
}
func (b *Bridge) Start() (join chan struct{}, err error) {
if b.srcJoin, err = b.src.Start(b.events); err != nil {
return nil, err
}
go func() {
logrus.Info("started")
defer logrus.Info("stopped")
defer close(b.join)
eventLoop:
for {
select {
case eventJson := <-b.events:
logrus.Info(eventJson)
2023-05-01 20:45:45 +02:00
if err := b.snk.Handle(eventJson.Data()); err == nil {
logrus.Infof("-> %v", eventJson.Data())
2023-03-15 18:49:17 +01:00
} else {
logrus.Error(err)
}
2023-05-01 20:45:45 +02:00
eventJson.Ack()
2023-03-15 18:49:17 +01:00
case <-b.close:
logrus.Info("received close signal")
break eventLoop
}
}
}()
return b.join, nil
}
func (b *Bridge) Stop() {
b.src.Stop()
close(b.close)
<-b.srcJoin
<-b.join
}