package batchtraces
import (
)
var errAlreadyRunning = errors.New("batchtraces: already running")
type Stats struct {
Exported uint64
Dropped uint64
Failed uint64
}
var _ traces.Handler = (*Batcher)(nil)
type Batcher struct {
exp Exporter
clock *clock.Clock
onError func(context.Context, error)
flushInterval time.Duration
maxBatch int
maxExports int
state atomic.Pointer[runState]
exported atomic.Uint64
dropped atomic.Uint64
failed atomic.Uint64
}
type runState struct {
recsc chan traces.Record
stopc chan struct{}
}
func ( Exporter, Options) *Batcher {
.setDefaults()
return &Batcher{
exp: ,
clock: .Clock,
onError: .OnError,
flushInterval: .FlushInterval,
maxBatch: .MaxBatch,
maxExports: .MaxExports,
}
}
func ( *Batcher) ( context.Context, traces.Record) error {
:= .state.Load()
if == nil {
.dropped.Add(1)
return nil
}
select {
case <-.stopc:
.dropped.Add(1)
case .recsc <- :
}
return nil
}
func ( *Batcher) (
context.Context,
func( context.Context) error,
) error {
:= &runState{
recsc: make(chan traces.Record),
stopc: make(chan struct{}),
}
if !.state.CompareAndSwap(nil, ) {
return errAlreadyRunning
}
var sync.WaitGroup
.Go(func() {
.eventLoop(, )
})
defer func() {
.state.Store(nil)
close(.stopc)
.Wait()
}()
return ()
}
func ( *Batcher) ( context.Context, *runState) {
:= .clock.Timer(.flushInterval)
defer .Stop()
var sync.WaitGroup
defer .Wait()
:= make(chan struct{}, .maxExports)
:= make([]traces.Record, 0, .maxBatch)
:= func() {
if len() == 0 {
return
}
select {
case <- struct{}{}:
default:
.dropped.Add(uint64(len()))
clear()
= [:0]
return
}
:=
= make([]traces.Record, 0, .maxBatch)
.Go(func() {
defer func() { <- }()
.export(, )
})
}
for {
select {
case <-.stopc:
if len() > 0 {
.export(, )
}
return
case := <-.recsc:
= append(, )
if len() >= .maxBatch {
()
}
case <-.C():
()
.Reset(.flushInterval)
}
}
}
func ( *Batcher) ( context.Context, []traces.Record) {
if := .exp.Export(, ); != nil {
.failed.Add(uint64(len()))
if .onError != nil {
.onError(, )
}
return
}
.exported.Add(uint64(len()))
}
func ( *Batcher) () Stats {
return Stats{
Exported: .exported.Load(),
Dropped: .dropped.Load(),
Failed: .failed.Load(),
}
}