-
Notifications
You must be signed in to change notification settings - Fork 50
/
input_in_memory.go
91 lines (72 loc) · 1.67 KB
/
input_in_memory.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
package stream
import (
"context"
"sync"
)
var inMemoryInputsLock sync.Mutex
var inMemoryInputs = make(map[string]*InMemoryInput)
func ResetInMemoryInputs() {
inMemoryInputsLock.Lock()
defer inMemoryInputsLock.Unlock()
for _, inp := range inMemoryInputs {
inp.Reset()
}
}
type InMemorySettings struct {
Size int `cfg:"size" default:"1"`
}
type InMemoryInput struct {
lck sync.Mutex
channel chan *Message
stopped chan struct{}
closedStopped bool
settings *InMemorySettings
}
func ProvideInMemoryInput(name string, settings *InMemorySettings) *InMemoryInput {
inMemoryInputsLock.Lock()
defer inMemoryInputsLock.Unlock()
if input, ok := inMemoryInputs[name]; ok {
return input
}
inMemoryInputs[name] = NewInMemoryInput(settings)
return inMemoryInputs[name]
}
func NewInMemoryInput(settings *InMemorySettings) *InMemoryInput {
return &InMemoryInput{
channel: make(chan *Message, settings.Size),
stopped: make(chan struct{}),
closedStopped: false,
settings: settings,
}
}
func (i *InMemoryInput) Reset() {
i.lck.Lock()
defer i.lck.Unlock()
i.channel = make(chan *Message, i.settings.Size)
i.stopped = make(chan struct{})
i.closedStopped = false
}
func (i *InMemoryInput) Publish(messages ...*Message) {
for _, msg := range messages {
i.channel <- msg
}
}
func (i *InMemoryInput) Run(ctx context.Context) error {
select {
case <-ctx.Done():
case <-i.stopped:
}
close(i.channel)
return nil
}
func (i *InMemoryInput) Stop() {
i.lck.Lock()
defer i.lck.Unlock()
if !i.closedStopped {
close(i.stopped)
i.closedStopped = true
}
}
func (i *InMemoryInput) Data() <-chan *Message {
return i.channel
}