-
Notifications
You must be signed in to change notification settings - Fork 11
/
subscriber.go
86 lines (75 loc) · 1.75 KB
/
subscriber.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
package changelog
import (
"fmt"
"github.com/sei-protocol/sei-db/proto"
"github.com/sei-protocol/sei-db/stream/types"
)
var _ types.Subscriber[proto.ChangelogEntry] = (*Subscriber)(nil)
type Subscriber struct {
maxPendingSize int
chPendingEntries chan proto.ChangelogEntry
errSignal chan error
stopSignal chan struct{}
processFn func(entry proto.ChangelogEntry) error
}
func NewSubscriber(
maxPendingSize int,
processFn func(entry proto.ChangelogEntry) error,
) *Subscriber {
subscriber := &Subscriber{
maxPendingSize: maxPendingSize,
processFn: processFn,
}
return subscriber
}
func (s *Subscriber) Start() {
if s.maxPendingSize > 0 {
s.startAsyncProcessing()
}
}
func (s *Subscriber) ProcessEntry(entry proto.ChangelogEntry) error {
if s.maxPendingSize <= 0 {
return s.processFn(entry)
}
s.chPendingEntries <- entry
return s.CheckError()
}
func (s *Subscriber) startAsyncProcessing() {
if s.chPendingEntries == nil {
s.chPendingEntries = make(chan proto.ChangelogEntry, s.maxPendingSize)
s.errSignal = make(chan error)
go func() {
defer close(s.errSignal)
for {
select {
case entry := <-s.chPendingEntries:
if err := s.processFn(entry); err != nil {
s.errSignal <- err
}
case <-s.stopSignal:
return
}
}
}()
}
}
func (s *Subscriber) Close() error {
if s.chPendingEntries != nil {
return nil
}
s.stopSignal <- struct{}{}
close(s.chPendingEntries)
err := s.CheckError()
s.chPendingEntries = nil
s.errSignal = nil
return err
}
func (s *Subscriber) CheckError() error {
select {
case err := <-s.errSignal:
// async wal writing failed, we need to abort the state machine
return fmt.Errorf("subscriber failed unexpectedly: %w", err)
default:
}
return nil
}