storj/cmd/statreceiver/common.go

57 lines
1.2 KiB
Go
Raw Normal View History

2019-01-24 20:15:10 +00:00
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package main
import (
"io"
"log"
"sync/atomic"
"time"
)
type closerfunc func() error
func (f closerfunc) Close() error { return f() }
2019-01-01 09:41:27 +00:00
// Deliver kicks off a goroutine that reads packets from source and delivers them
// to dest. To stop delivery, call Close on the return value then close the source.
func Deliver(source Source, dest PacketDest) io.Closer {
done := new(uint32)
2019-01-01 09:41:27 +00:00
go func() {
2019-01-01 09:41:27 +00:00
for atomic.LoadUint32(done) == 0 {
data, ts, err := source.Next()
if err != nil {
log.Printf("failed getting packet: %v", err)
continue
}
2019-01-01 09:41:27 +00:00
err = dest.Packet(data, ts)
if err != nil {
log.Printf("failed delivering packet: %v", err)
continue
}
}
}()
2019-01-01 09:41:27 +00:00
return closerfunc(func() error {
atomic.StoreUint32(done, 1)
return nil
})
}
// Source reads incoming packets
type Source interface {
Next() (data []byte, ts time.Time, err error)
}
// PacketDest handles packets
type PacketDest interface {
Packet(data []byte, ts time.Time) error
}
// MetricDest handles metrics
type MetricDest interface {
2019-01-01 09:41:27 +00:00
Metric(application, instance string, key []byte, val float64, ts time.Time) error
}