forked from nytlabs/streamtools
/
toNSQ.go
93 lines (80 loc) · 1.75 KB
/
toNSQ.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
package library
import (
"encoding/json"
"github.com/bitly/go-nsq"
"github.com/nytlabs/streamtools/st/blocks" // blocks
"github.com/nytlabs/streamtools/st/util"
)
// specify those channels we're going to use to communicate with streamtools
type ToNSQ struct {
blocks.Block
queryrule chan chan interface{}
inrule chan interface{}
in chan interface{}
out chan interface{}
quit chan interface{}
nsqdTCPAddrs string
topic string
}
// a bit of boilerplate for streamtools
func NewToNSQ() blocks.BlockInterface {
return &ToNSQ{}
}
func (b *ToNSQ) Setup() {
b.Kind = "ToNSQ"
b.in = b.InRoute("in")
b.inrule = b.InRoute("rule")
b.queryrule = b.QueryRoute("rule")
b.quit = b.Quit()
}
// connects to an NSQ topic and emits each message into streamtools.
func (b *ToNSQ) Run() {
var writer *nsq.Writer
for {
select {
case ruleI := <-b.inrule:
//rule := ruleI.(map[string]interface{})
topic, err := util.ParseString(ruleI, "Topic")
if err != nil {
b.Error(err)
break
}
nsqdTCPAddrs, err := util.ParseString(ruleI, "NsqdTCPAddrs")
if err != nil {
b.Error(err)
break
}
if writer != nil {
writer.Stop()
}
writer = nsq.NewWriter(nsqdTCPAddrs)
b.topic = topic
b.nsqdTCPAddrs = nsqdTCPAddrs
case msg := <-b.in:
if writer == nil {
continue
}
msgBytes, err := json.Marshal(msg)
if err != nil {
b.Error(err)
}
if len(msgBytes) == 0 {
continue
}
_, _, err = writer.Publish(b.topic, msgBytes)
if err != nil {
b.Error(err)
}
case <-b.quit:
if writer != nil {
writer.Stop()
}
return
case c := <-b.queryrule:
c <- map[string]interface{}{
"Topic": b.topic,
"NsqdTCPAddrs": b.nsqdTCPAddrs,
}
}
}
}