forked from topfreegames/khan
-
Notifications
You must be signed in to change notification settings - Fork 1
/
dispatcher.go
241 lines (204 loc) · 6.16 KB
/
dispatcher.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
// khan
// https://github.com/topfreegames/khan
//
// Licensed under the MIT license:
// http://www.opensource.org/licenses/mit-license
// Copyright © 2016 Top Free Games <backend@tfgco.com>
package api
import (
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/url"
"strings"
"time"
workers "github.com/jrallison/go-workers"
"github.com/satori/go.uuid"
"github.com/topfreegames/khan/log"
"github.com/topfreegames/khan/queues"
"github.com/topfreegames/khan/util"
"github.com/uber-go/zap"
"github.com/valyala/fasthttp"
"github.com/valyala/fasttemplate"
)
const hookInternalFailures = "hook_internal_failures"
const requestingHookMilliseconds = "requesting_hook_milliseconds"
const requestingHookURLStatus = "requesting_hook_status"
//Dispatcher is responsible for sending web hooks to workers
type Dispatcher struct {
app *App
}
//NewDispatcher creates a new dispatcher available to our app
func NewDispatcher(app *App) (*Dispatcher, error) {
d := &Dispatcher{app: app}
return d, nil
}
//DispatchHook dispatches an event hook for eventType to gameID with the specified payload
func (d *Dispatcher) DispatchHook(gameID string, eventType int, payload map[string]interface{}) {
payload["type"] = eventType
payload["id"] = uuid.NewV4()
payload["timestamp"] = time.Now().Format(time.RFC3339)
// Push the work onto the queue.
log.I(d.app.Logger, "Pushing work into dispatch queue.", func(cm log.CM) {
cm.Write(
zap.String("source", "dispatcher"),
zap.String("operation", "DispatchHook"),
)
})
workers.Enqueue(queues.KhanQueue, "Add", map[string]interface{}{
"gameID": gameID,
"eventType": eventType,
"payload": payload,
})
}
func (d *Dispatcher) interpolateURL(sourceURL string, payload map[string]interface{}) (string, error) {
t, err := fasttemplate.NewTemplate(sourceURL, "{{", "}}")
if err != nil {
return sourceURL, err
}
s := t.ExecuteFuncString(func(w io.Writer, tag string) (int, error) {
pieces := strings.Split(tag, ".")
var item interface{}
item = payload
if len(pieces) > 1 {
for _, piece := range pieces {
switch item.(type) {
case map[string]interface{}:
item = item.(map[string]interface{})[piece]
default:
return 0, nil
}
}
valEncoded := url.QueryEscape(
fmt.Sprintf("%v", item),
)
return w.Write([]byte(valEncoded))
}
if val, ok := payload[tag]; ok {
valEncoded := url.QueryEscape(
fmt.Sprintf("%v", val),
)
return w.Write([]byte(valEncoded))
}
return 0, nil
})
return s, nil
}
func basicAuth(username, password string) string {
auth := username + ":" + password
return base64.StdEncoding.EncodeToString([]byte(auth))
}
// PerformDispatchHook dispatches web hooks for a specific game and event type
func (d *Dispatcher) PerformDispatchHook(m *workers.Msg) {
app := d.app
statsd := app.DDStatsD
item := m.Args()
data := item.MustMap()
gameID := data["gameID"].(string)
eventType, _ := data["eventType"].(json.Number).Int64()
payload := data["payload"].(map[string]interface{})
l := d.app.Logger.With(
zap.String("source", "dispatcher"),
zap.String("operation", "PerformDispatchHook"),
zap.String("gameID", gameID),
zap.Int64("eventType", eventType),
)
hooks := app.GetHooks()
if _, ok := hooks[gameID]; !ok {
log.D(l, "No hooks found for game.")
return
}
if _, ok := hooks[gameID][int(eventType)]; !ok {
log.D(l, "No hooks found for event in specified game.")
return
}
timeout := time.Duration(app.Config.GetInt("webhooks.timeout")) * time.Second
for _, hook := range hooks[gameID][int(eventType)] {
log.I(app.Logger, "Sending webhook...", func(cm log.CM) {
cm.Write(zap.String("url", hook.URL))
})
client := fasthttp.Client{
Name: fmt.Sprintf("khan-%s", util.VERSION),
}
requestURL, err := d.interpolateURL(hook.URL, payload)
if err != nil {
app.addError()
tags := []string{"error:interpolateurl"}
statsd.Increment(hookInternalFailures, tags...)
log.E(l, "Could not interpolate webhook.", func(cm log.CM) {
cm.Write(
zap.String("requestURL", hook.URL),
zap.Error(err),
)
})
continue
}
payloadJSON, _ := json.Marshal(payload)
log.D(l, "Requesting Hook URL...", func(cm log.CM) {
cm.Write(zap.String("requestURL", requestURL))
})
req := fasthttp.AcquireRequest()
req.Header.SetMethod("POST")
req.AppendBody(payloadJSON)
parsedURL, err := url.Parse(requestURL)
if err != nil {
app.addError()
tags := []string{"error:parserequesturl"}
statsd.Increment(hookInternalFailures, tags...)
log.E(l, "Could not parse request requestURL.", func(cm log.CM) {
cm.Write(
zap.String(requestURL, hook.URL),
zap.Error(err),
)
})
}
if parsedURL.User != nil {
username := parsedURL.User.Username()
password, setten := parsedURL.User.Password()
if setten == false {
password = ""
}
requestURL = fmt.Sprintf("%s://%s%s", parsedURL.Scheme, parsedURL.Host, parsedURL.RequestURI())
req.Header.Add("Authorization", "Basic "+basicAuth(username, password))
}
req.SetRequestURI(requestURL)
resp := fasthttp.AcquireResponse()
start := time.Now()
err = client.DoTimeout(req, resp, timeout)
if err != nil {
app.addError()
tags := []string{"error:timeout"}
statsd.Increment(hookInternalFailures, tags...)
log.E(l, "Could not request webhook.", func(cm log.CM) {
cm.Write(zap.String("requestURL", hook.URL), zap.Error(err))
})
continue
}
// elapsed must be set after checking the error
// in order avoid noising the avg time with timeouts
elapsed := time.Since(start)
statsd.Timing(requestingHookMilliseconds, elapsed)
tags := []string{fmt.Sprintf("status:%d", resp.StatusCode())}
statsd.Increment(requestingHookURLStatus, tags...)
if resp.StatusCode() > 399 {
app.addError()
log.E(l, "Could not request webhook.", func(cm log.CM) {
cm.Write(
zap.String("requestURL", hook.URL),
zap.Int("statusCode", resp.StatusCode()),
zap.String("body", string(resp.Body())),
)
})
continue
}
log.I(l, "Webhook requested successfully.", func(cm log.CM) {
cm.Write(
zap.Int("statusCode", resp.StatusCode()),
zap.String("requestURL", requestURL),
zap.String("body", string(resp.Body())),
)
})
}
return
}