-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathquasar.go
211 lines (176 loc) · 4.8 KB
/
quasar.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package quasar
import (
"encoding/json"
"log"
"os"
"os/signal"
"syscall"
"github.com/pkg/errors"
)
const (
// DefaultSend is the default tcp address for sending data to the server.
DefaultSend = "tcp://localhost:61124"
// DefaultRecv is the default tcp address for recieving data from the server.
DefaultRecv = "tcp://localhost:61123"
)
// Service is the state of the service.
// It holds the handlers and matchers and helps relay
// messages to the right handler when they come in from
// the Tenyks server.
type Service struct {
Name string
UUID string
Description string
HelpText string
Config *Config
defaultHandler MsgHandler
handlers []MsgHandler
conn *Connection
responseCh chan Message
ctrlCh chan struct{}
}
// Matcher is an interface that has a match method that receives a
// Message and tries to match it against a set of rules.
// If no match is found, then you should return nil.
type Matcher interface {
Match(Message) Result
}
// MatcherFunc registers the wrapped function as a Matcher.
type MatcherFunc func(Message) Result
func (fn MatcherFunc) Match(msg Message) Result {
return fn(msg)
}
// Handler is an interface that has a Handle method that takes a Result and Message as arguments.
// What you do with these is up to you. This is a function that will be triggered if it's
// matcher returns a valid match.
type Handler interface {
HandleMatch(Result, Message, Communication)
}
type HandlerFunc func(Result, Message, Communication)
func (fn HandlerFunc) HandleMatch(r Result, m Message, c Communication) {
fn(r, m, c)
}
type Result map[string]string
type MsgHandler struct {
MatcherFunc Matcher
DirectOnly bool
PrivateOnly bool
MatchHandler Handler
HelpText string
}
type Communication struct {
ch chan<- Message
}
func (c *Communication) Send(line string, message Message) {
message.Payload = line
c.ch <- message
}
func (s *Service) responseReceiver() {
for {
message := <-s.responseCh
j, err := json.Marshal(message)
if err != nil {
continue
}
s.publish(string(j))
}
}
func (s *Service) publish(msg string) {
s.conn.out <- msg
}
var NoopHandler = MsgHandler{MatchHandler: HandlerFunc(func(r Result, m Message, c Communication) {})}
func New(config *Config) *Service {
s := &Service{
Config: config,
responseCh: make(chan Message, 1000),
ctrlCh: make(chan struct{}),
}
// Add noop handler for default
s.DefaultHandle(NoopHandler)
return s
}
func (s *Service) Handle(handler MsgHandler) {
// Choose one, sucker
if handler.DirectOnly && handler.PrivateOnly {
// TODO: handle this with an error
log.Panicln("Cannot have both DirectOnly and PrivateOnly set to true")
}
s.handlers = append(s.handlers, handler)
}
func (s *Service) DefaultHandle(handler MsgHandler) {
s.defaultHandler = handler
}
func (s *Service) registerCommunicationAndCallHandler(handler Handler, result Result, msg Message) {
com := Communication{s.responseCh}
go handler.HandleMatch(result, msg, com)
}
func (s *Service) findMsgMatch(msg Message) {
for _, mh := range s.handlers {
res := mh.MatcherFunc.Match(msg)
if res == nil {
continue
} else {
s.registerCommunicationAndCallHandler(mh.MatchHandler, res, msg)
return
}
}
s.registerCommunicationAndCallHandler(s.defaultHandler.MatchHandler, nil, msg)
}
func (s *Service) deserializeAndDispatch(rawmsg string) {
msg := Message{}
if err := json.Unmarshal([]byte(rawmsg), &msg); err != nil {
// We don't care about malformed messages, so we discard and return.
return
}
s.findMsgMatch(msg)
}
func (s *Service) deligator() {
for {
select {
case msg := <-s.conn.in:
s.deserializeAndDispatch(msg)
case <-s.ctrlCh:
return
}
}
}
// Run runs forever or until a signal stops the program.
// This function blocks.
func (s *Service) Run() error {
if s.Config.Service.SendAddr == "" {
s.Config.Service.SendAddr = DefaultSend
}
if s.Config.Service.RecvAddr == "" {
s.Config.Service.RecvAddr = DefaultRecv
}
conn, err := NewConnection(s.Config)
if err != nil {
return errors.Wrap(err, "failed to create connection")
}
s.conn = conn
err = conn.start()
if err != nil {
return errors.Wrap(err, "failed to start connection")
}
go s.responseReceiver()
go s.deligator()
sigchn := make(chan os.Signal, 1)
signal.Notify(sigchn, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
// should consider removing this and just letting the person implementing
// the service be responsible for capturing signals and exiting. that would
// also enable this function to be safely ran in a goroutine.
Loop:
for {
select {
case <-sigchn:
break Loop
}
}
s.Cleanup()
return nil
}
// Cleanup will close open connections and clean up anything that shouldn't linger after shutdown.
func (s *Service) Cleanup() {
close(s.ctrlCh)
s.conn.close()
}