-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstream.go
209 lines (174 loc) · 4.85 KB
/
stream.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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
amqp "github.com/rabbitmq/amqp091-go"
)
var (
streamConnectionsTotal = promauto.NewGauge(prometheus.GaugeOpts{
Namespace: metricNamespace,
Name: "stream_connections_total",
Help: "The total number of open stream connections.",
})
)
func extractFilterTopicsFromName(filter map[string]string) []string {
if name, ok := filter["name"]; ok {
delete(filter, "name")
return strings.Split(name, "|")
}
return []string{"#"}
}
func buildMatchers(filter map[string]string) (map[string]*regexp.Regexp, error) {
matchers := map[string]*regexp.Regexp{}
for k, v := range filter {
re, err := regexp.Compile(v)
if err != nil {
return nil, err
}
matchers[k] = re
}
return matchers, nil
}
type Message struct {
Name string `json:"name"`
Timestamp time.Time `json:"timestamp"`
Value interface{} `json:"value"`
Meta map[string]string `json:"meta"`
}
func unmarshalMessage(b []byte, msg *Message) error {
var obj struct {
Name string `json:"name"`
Timestamp int64 `json:"ts"`
Value interface{} `json:"val"`
Meta map[string]string `json:"meta"`
}
if err := json.Unmarshal(b, &obj); err != nil {
return err
}
msg.Name = obj.Name
msg.Timestamp = time.Unix(0, obj.Timestamp).UTC()
msg.Value = obj.Value
msg.Meta = obj.Meta
return nil
}
func matchMessage(matchers map[string]*regexp.Regexp, msg *Message) bool {
for key, matcher := range matchers {
if !matcher.MatchString(msg.Meta[key]) {
return false
}
}
return true
}
func getFilterForQueryValues(values url.Values) map[string]string {
filter := make(map[string]string)
for k := range values {
filter[k] = values.Get(k)
}
return filter
}
type StreamService struct {
RabbitMQURL string
HeartbeatDuration time.Duration
}
func (svc *StreamService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
return
}
if r.Method != http.MethodGet {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
streamConnectionsTotal.Add(1)
defer streamConnectionsTotal.Add(-1)
// TODO need to bound URL size here
filter := getFilterForQueryValues(r.URL.Query())
// special case: vsn is always uppercase
if s, ok := filter["vsn"]; ok {
filter["vsn"] = strings.ToUpper(s)
}
// special case: node is always lowercase
if s, ok := filter["node"]; ok {
filter["node"] = strings.ToLower(s)
}
// extract topics from name filter. deletes name field afterwards.
topics := extractFilterTopicsFromName(filter)
// create matcher
matchers, err := buildMatchers(filter)
if err != nil {
log.Printf("invalid request filter: %s", err)
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
conn, err := amqp.Dial(svc.RabbitMQURL)
if err != nil {
log.Printf("failed dial rabbitmq: %s", err)
http.Error(w, http.StatusText(http.StatusBadGateway), http.StatusBadGateway)
return
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
log.Printf("failed to open rabbitmq channel: %s", err)
http.Error(w, http.StatusText(http.StatusBadGateway), http.StatusBadGateway)
return
}
defer ch.Close()
queue, err := ch.QueueDeclare("", false, false, true, false, nil)
if err != nil {
log.Printf("failed to declare queue: %s", err)
http.Error(w, http.StatusText(http.StatusBadGateway), http.StatusBadGateway)
return
}
for _, topic := range topics {
if err := ch.QueueBind(queue.Name, topic, "waggle.msg", false, nil); err != nil {
log.Printf("failed to bind queue %s to exchange", queue.Name)
http.Error(w, http.StatusText(http.StatusBadGateway), http.StatusBadGateway)
return
}
}
messages, err := ch.Consume(queue.Name, "", true, false, false, false, nil)
if err != nil {
log.Printf("failed to consume queue %s", queue.Name)
http.Error(w, http.StatusText(http.StatusBadGateway), http.StatusBadGateway)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Access-Control-Allow-Origin", "*")
ticker := time.NewTicker(svc.HeartbeatDuration)
defer ticker.Stop()
for {
select {
case <-r.Context().Done():
return
case <-ticker.C:
fmt.Fprintf(w, ":keepalive\n\n")
flusher.Flush()
case amqpMsg := <-messages:
// reset heartbeat ticker
ticker.Reset(svc.HeartbeatDuration)
var msg Message
if err := unmarshalMessage(amqpMsg.Body, &msg); err != nil {
continue
}
if !matchMessage(matchers, &msg) {
continue
}
b, err := json.Marshal(msg)
if err != nil {
return
}
// write and flush event to client
fmt.Fprintf(w, "event: message\ndata: %s\n\n", b)
flusher.Flush()
}
}
}