forked from nytlabs/streamtools
/
count.go
103 lines (94 loc) · 2.14 KB
/
count.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
93
94
95
96
97
98
99
100
101
102
103
package library
import (
"container/heap"
"github.com/nytlabs/streamtools/st/blocks" // blocks
"github.com/nytlabs/streamtools/st/util"
"time"
)
type Count struct {
blocks.Block
queryrule chan chan interface{}
querycount chan chan interface{}
inrule chan interface{}
inpoll chan interface{}
clear chan interface{}
in chan interface{}
out chan interface{}
quit chan interface{}
}
// a bit of boilerplate for streamtools
func NewCount() blocks.BlockInterface {
return &Count{}
}
func (b *Count) Setup() {
b.Kind = "Count"
b.Desc = "counts the number of messages seen over a specified Window"
b.in = b.InRoute("in")
b.inrule = b.InRoute("rule")
b.inpoll = b.InRoute("poll")
b.clear = b.InRoute("clear")
b.queryrule = b.QueryRoute("rule")
b.querycount = b.QueryRoute("count")
b.quit = b.Quit()
b.out = b.Broadcast()
}
func (b *Count) Run() {
waitTimer := time.NewTimer(100 * time.Millisecond)
pq := &PriorityQueue{}
heap.Init(pq)
window := time.Duration(0)
for {
select {
case <-waitTimer.C:
case rule := <-b.inrule:
tmpDurStr, err := util.ParseString(rule, "Window")
if err != nil {
b.Error(err)
continue
}
tmpWindow, err := time.ParseDuration(tmpDurStr)
if err != nil {
b.Error(err)
continue
}
window = tmpWindow
case <-b.quit:
return
case <-b.in:
empty := make([]byte, 0)
queueMessage := &PQMessage{
val: &empty,
t: time.Now(),
}
heap.Push(pq, queueMessage)
case <-b.clear:
for len(*pq) > 0 {
heap.Pop(pq)
}
case <-b.inpoll:
b.out <- map[string]interface{}{
"Count": float64(len(*pq)),
}
case c := <-b.queryrule:
c <- map[string]interface{}{
"Window": window.String(),
}
case c := <-b.querycount:
c <- map[string]interface{}{
"Count": float64(len(*pq)),
}
}
for {
pqMsg, diff := pq.PeekAndShift(time.Now(), window)
if pqMsg == nil {
// either the queue is empty, or it"s not time to emit
if diff == 0 {
// then the queue is empty. Pause for 5 seconds before checking again
diff = time.Duration(500) * time.Millisecond
}
waitTimer.Reset(diff)
break
}
}
}
}