-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
types.go
92 lines (76 loc) · 2.28 KB
/
types.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package api
import (
"sync"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/model"
"github.com/grafana/loki/pkg/logproto"
)
// Entry is a log entry with labels.
type Entry struct {
Labels model.LabelSet
logproto.Entry
}
type InstrumentedEntryHandler interface {
EntryHandler
UnregisterLatencyMetric(prometheus.Labels)
}
// EntryHandler is something that can "handle" entries via a channel.
// Stop must be called to gracefully shutdown the EntryHandler
type EntryHandler interface {
Chan() chan<- Entry
Stop()
}
// EntryMiddleware takes an EntryHandler and returns another one that will intercept and forward entries.
// The newly created EntryHandler should be Stopped independently from the original one.
type EntryMiddleware interface {
Wrap(EntryHandler) EntryHandler
}
// EntryMiddlewareFunc allows to create EntryMiddleware via a function.
type EntryMiddlewareFunc func(EntryHandler) EntryHandler
func (e EntryMiddlewareFunc) Wrap(next EntryHandler) EntryHandler {
return e(next)
}
// EntryMutatorFunc is a function that can mutate an entry
type EntryMutatorFunc func(Entry) Entry
type entryHandler struct {
stop func()
entries chan<- Entry
}
func (e entryHandler) Chan() chan<- Entry {
return e.entries
}
func (e entryHandler) Stop() {
e.stop()
}
// NewEntryHandler creates a new EntryHandler using a input channel and a stop function.
func NewEntryHandler(entries chan<- Entry, stop func()) EntryHandler {
return entryHandler{
stop: stop,
entries: entries,
}
}
// NewEntryMutatorHandler creates a EntryHandler that mutates incoming entries from another EntryHandler.
func NewEntryMutatorHandler(next EntryHandler, f EntryMutatorFunc) EntryHandler {
in, wg, once := make(chan Entry), sync.WaitGroup{}, sync.Once{}
nextChan := next.Chan()
wg.Add(1)
go func() {
defer wg.Done()
for e := range in {
nextChan <- f(e)
}
}()
return NewEntryHandler(in, func() {
once.Do(func() { close(in) })
wg.Wait()
})
}
// AddLabelsMiddleware is an EntryMiddleware that adds some labels.
func AddLabelsMiddleware(additionalLabels model.LabelSet) EntryMiddleware {
return EntryMiddlewareFunc(func(eh EntryHandler) EntryHandler {
return NewEntryMutatorHandler(eh, func(e Entry) Entry {
e.Labels = additionalLabels.Merge(e.Labels)
return e
})
})
}