-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathpending_events.go
66 lines (58 loc) · 1.11 KB
/
pending_events.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
package sbac // import "chainspace.io/chainspace-go/sbac"
import (
"sync"
"context"
)
type pendingEvents struct {
cancel func()
cond *sync.Cond
ctx context.Context
events []Event
mu sync.Mutex
cb func(Event) bool
}
func (pe *pendingEvents) Close() {
pe.cancel()
// just sending a nil event, this will get canceled directly
pe.OnEvent(nil)
}
func (pe *pendingEvents) Len() int {
pe.mu.Lock()
defer pe.mu.Unlock()
return len(pe.events)
}
func (pe *pendingEvents) OnEvent(e Event) {
pe.mu.Lock()
pe.events = append(pe.events, e)
pe.mu.Unlock()
pe.cond.Signal()
}
func (pe *pendingEvents) Run() {
for {
pe.mu.Lock()
for len(pe.events) == 0 {
pe.cond.Wait()
}
// check if context exited
if pe.ctx.Err() != nil {
return
}
e := pe.events[0]
pe.events = pe.events[1:]
pe.mu.Unlock()
if !pe.cb(e) {
pe.OnEvent(e)
}
}
}
func NewPendingEvents(cb func(Event) bool) *pendingEvents {
ctx, cancel := context.WithCancel(context.Background())
pe := &pendingEvents{
cancel: cancel,
cb: cb,
ctx: ctx,
events: []Event{},
}
pe.cond = sync.NewCond(&pe.mu)
return pe
}