-
Notifications
You must be signed in to change notification settings - Fork 14
/
emitter.go
431 lines (366 loc) · 11.8 KB
/
emitter.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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//
// Copyright (c) 2016-2023 Snowplow Analytics Ltd. All rights reserved.
//
// This program is licensed to you under the Apache License Version 2.0,
// and you may not use this file except in compliance with the Apache License Version 2.0.
// You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the Apache License Version 2.0 is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
//
package tracker
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"time"
"github.com/snowplow/snowplow-golang-tracker/v3/pkg/common"
"github.com/snowplow/snowplow-golang-tracker/v3/pkg/payload"
"github.com/snowplow/snowplow-golang-tracker/v3/pkg/storage/storageiface"
)
const (
DEFAULT_REQ_TYPE = "POST"
DEFAULT_PROTOCOL = "http"
DEFAULT_SEND_LIMIT = 500
DEFAULT_BYTE_LIMIT_GET = 40000
DEFAULT_BYTE_LIMIT_POST = 40000
DEFAULT_DB_NAME = "events.db"
POST_WRAPPER_BYTES = 88 // "schema":"iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-3","data":[]
POST_STM_BYTES = 22 // "stm":"1443452851000"
)
type SendResult struct {
ids []int
status int
}
type CallbackResult struct {
Count int
Status int
}
type Emitter struct {
CollectorUri string
CollectorUrl url.URL
RequestType string
Protocol string
SendLimit int
ByteLimitGet int
ByteLimitPost int
Storage storageiface.Storage
SendChannel chan bool
Callback func(successCount []CallbackResult, failureCount []CallbackResult)
HttpClient *http.Client
}
// InitEmitter creates a new Emitter object which handles
// storing and sending Snowplow Events.
func InitEmitter(options ...func(*Emitter)) *Emitter {
e := &Emitter{}
// Set Defaults
e.RequestType = DEFAULT_REQ_TYPE
e.Protocol = DEFAULT_PROTOCOL
e.SendLimit = DEFAULT_SEND_LIMIT
e.ByteLimitGet = DEFAULT_BYTE_LIMIT_GET
e.ByteLimitPost = DEFAULT_BYTE_LIMIT_POST
// Option parameters
for _, op := range options {
op(e)
}
// Check collector URI is not empty
if e.CollectorUri == "" {
panic("FATAL: CollectorUri cannot be empty.")
} else {
collectorUrl, err := returnCollectorUrl(e.RequestType, e.Protocol, e.CollectorUri)
if err != nil {
panic(err.Error())
} else {
e.CollectorUrl = *collectorUrl
}
}
// Setup default event storage
if e.Storage == nil {
panic("FATAL: Storage must be defined.")
}
// Setup HttpClient
if e.HttpClient == nil {
// Customize the Transport to have larger connection pool
defaultRoundTripper := http.DefaultTransport
defaultTransportPointer, ok := defaultRoundTripper.(*http.Transport)
if !ok {
panic(fmt.Sprintf("defaultRoundTripper not an *http.Transport"))
}
defaultTransport := *defaultTransportPointer
defaultTransport.MaxIdleConns = 100
defaultTransport.MaxIdleConnsPerHost = 100
timeout := time.Duration(5 * time.Second)
e.HttpClient = &http.Client{
Timeout: timeout,
Transport: &defaultTransport,
}
}
return e
}
// --- Require
// RequireCollectorUri sets the Emitters collector URI.
func RequireCollectorUri(collectorUri string) func(e *Emitter) {
return func(e *Emitter) { e.CollectorUri = collectorUri }
}
// RequireStorage sets a custom event Storage target which implements the Storage interface
func RequireStorage(storage storageiface.Storage) func(e *Emitter) {
return func(e *Emitter) { e.Storage = storage }
}
// --- Option
// OptionRequestType sets the request type to use (GET or POST).
func OptionRequestType(requestType string) func(e *Emitter) {
return func(e *Emitter) { e.RequestType = requestType }
}
// OptionProtocol sets the protocol type to use (http or https).
func OptionProtocol(protocol string) func(e *Emitter) {
return func(e *Emitter) { e.Protocol = protocol }
}
// OptionSendLimit sets the send limit for the emitter.
func OptionSendLimit(sendLimit int) func(e *Emitter) {
return func(e *Emitter) { e.SendLimit = sendLimit }
}
// OptionByteLimitGet sets the byte limit for GET requests.
func OptionByteLimitGet(byteLimitGet int) func(e *Emitter) {
return func(e *Emitter) { e.ByteLimitGet = byteLimitGet }
}
// OptionByteLimitPost sets the byte limit for POST requests.
func OptionByteLimitPost(byteLimitPost int) func(e *Emitter) {
return func(e *Emitter) { e.ByteLimitPost = byteLimitPost }
}
// OptionCallback sets a custom callback for the emitter loop.
func OptionCallback(callback func(successCount []CallbackResult, failureCount []CallbackResult)) func(e *Emitter) {
return func(e *Emitter) { e.Callback = callback }
}
// OptionHttpClient sets a custom client for HTTP connections.
func OptionHttpClient(client *http.Client) func(e *Emitter) {
return func(e *Emitter) { e.HttpClient = client }
}
// --- Event Handlers
// Add will push an event to the database and will then initiate a sending loop.
func (e *Emitter) Add(payload payload.Payload) {
e.Storage.AddEventRow(payload)
e.start()
}
// Flush will attempt to start the send loop regardless of an event coming in.
func (e *Emitter) Flush() {
e.start()
}
// Stop waits for the send channel to have a value and then resets it to nil.
func (e *Emitter) Stop() {
<-e.SendChannel
e.SendChannel = nil
}
// start will begin the sending loop.
func (e *Emitter) start() {
if e.SendChannel == nil || !e.IsSending() {
e.SendChannel = make(chan bool, 1)
go func() {
var done bool
defer func() {
e.SendChannel <- done
}()
for {
eventRows := e.Storage.GetEventRowsWithinRange(e.SendLimit)
// If there are no events in the database exit
if len(eventRows) == 0 {
break
}
results := e.doSend(eventRows)
// Process results
ids := []int{}
successes := []CallbackResult{}
failures := []CallbackResult{}
for _, res := range results {
count := len(res.ids)
status := res.status
if status >= 200 && status < 400 {
ids = append(ids, res.ids...)
successes = append(successes, CallbackResult{count, status})
} else {
failures = append(failures, CallbackResult{count, status})
}
}
if e.Callback != nil {
e.Callback(successes, failures)
}
// If all the events failed to be sent exit
if len(successes) == 0 && len(failures) > 0 {
break
}
e.Storage.DeleteEventRows(ids)
}
done = true
}()
}
}
// doSend will send all of the eventsRows it is given.
func (e *Emitter) doSend(eventRows []storageiface.EventRow) []SendResult {
futures := []<-chan SendResult{}
url := e.GetCollectorUrl()
if e.RequestType == "POST" {
ids := []int{}
payloads := []payload.Payload{}
totalByteSize := 0
for _, val := range eventRows {
byteSize := common.CountBytesInString(val.Event.String()) + POST_STM_BYTES
if byteSize+POST_WRAPPER_BYTES > e.ByteLimitPost {
// A single payload has exceeded the Byte Limit
futures = append(futures, e.sendPostRequest(url, []int{val.Id}, []payload.Payload{val.Event}, true))
} else if (totalByteSize + byteSize + POST_WRAPPER_BYTES + (len(payloads) - 1)) > e.ByteLimitPost {
// Byte limit reached
futures = append(futures, e.sendPostRequest(url, ids, payloads, false))
// Reset accumulators
ids = []int{val.Id}
payloads = []payload.Payload{val.Event}
totalByteSize = byteSize
} else {
ids = append(ids, val.Id)
payloads = append(payloads, val.Event)
totalByteSize += byteSize
}
}
if len(payloads) > 0 {
futures = append(futures, e.sendPostRequest(url, ids, payloads, false))
}
} else if e.RequestType == "GET" {
for _, val := range eventRows {
val.Event.Add(SENT_TIMESTAMP, common.NewString(common.GetTimestampString()))
queryString := common.MapToQueryParams(val.Event.Get()).Encode()
oversize := common.CountBytesInString(queryString) > e.ByteLimitGet
futures = append(futures, e.sendGetRequest(url+"?"+queryString, []int{val.Id}, oversize))
}
}
// Wait for all Futures to complete
results := []SendResult{}
for _, future := range futures {
results = append(results, <-future)
}
return results
}
// SendGetRequest sends a payload to the collector endpoint via GET.
func (e *Emitter) sendGetRequest(url string, ids []int, oversize bool) <-chan SendResult {
c := make(chan SendResult, 1)
go func() {
var result SendResult
defer func() {
c <- result
}()
status := -1
if oversize {
status = 200
}
req, _ := http.NewRequest("GET", url, nil)
resp, err := e.HttpClient.Do(req)
if err != nil {
log.Println(err.Error())
result = SendResult{ids: ids, status: status}
return
}
io.CopyN(ioutil.Discard, resp.Body, 512)
resp.Body.Close()
status = resp.StatusCode
if oversize {
status = 200
}
result = SendResult{ids: ids, status: status}
}()
return c
}
// SendPostRequest sends an array of Payloads together to the collector endpoint via POST.
func (e *Emitter) sendPostRequest(url string, ids []int, body []payload.Payload, oversize bool) <-chan SendResult {
c := make(chan SendResult, 1)
go func() {
var result SendResult
defer func() {
c <- result
}()
status := -1
if oversize {
status = 200
}
postEnvelope := map[string]interface{}{
SCHEMA: SCHEMA_PAYLOAD_DATA,
DATA: addSentTimeToEvents(body),
}
req, _ := http.NewRequest("POST", url, bytes.NewBufferString(common.MapToJson(postEnvelope)))
req.Header.Set("Content-Type", POST_CONTENT_TYPE)
resp, err := e.HttpClient.Do(req)
if err != nil {
log.Println(err.Error())
result = SendResult{ids: ids, status: status}
return
}
io.CopyN(ioutil.Discard, resp.Body, 512)
resp.Body.Close()
status = resp.StatusCode
if oversize {
status = 200
}
result = SendResult{ids: ids, status: status}
}()
return c
}
// --- Helpers
// IsSending checks whether the send channel has finished.
func (e Emitter) IsSending() bool {
return len(e.SendChannel) == 0
}
// returnCollectorUrl builds and returns the full collector URL to be used.
func returnCollectorUrl(requestType string, protocol string, collectorUri string) (*url.URL, error) {
var rawUrl string
switch requestType {
case "POST":
rawUrl = protocol + "://" + collectorUri + "/" + POST_PROTOCOL_VENDOR + "/" + POST_PROTOCOL_VERSION
case "GET":
rawUrl = protocol + "://" + collectorUri + "/" + GET_PROTOCOL_PATH
default:
return nil, errors.New("FATAL: RequestType did not match either POST or GET.")
}
return url.Parse(rawUrl)
}
// addSentTimeToEvents ranges over an array of events and appends the same timestamp to them all.
func addSentTimeToEvents(events []payload.Payload) []map[string]string {
eventMaps := []map[string]string{}
stm := common.NewString(common.GetTimestampString())
for _, p := range events {
p.Add(SENT_TIMESTAMP, stm)
eventMaps = append(eventMaps, p.Get())
}
return eventMaps
}
// --- Getters & Setters
// GetCollectorUrl returns the stringified collector URL.
func (e Emitter) GetCollectorUrl() string {
return e.CollectorUrl.String()
}
// SetCollectorUri sets a new Collector URI and updates the Collector URL.
func (e *Emitter) SetCollectorUri(collectorUri string) {
collectorUrl, err := returnCollectorUrl(e.RequestType, e.Protocol, collectorUri)
if err == nil {
e.CollectorUrl = *collectorUrl
e.CollectorUri = collectorUri
}
}
// SetRequestType sets a new Request Type and updates the Collector URL.
func (e *Emitter) SetRequestType(requestType string) {
collectorUrl, err := returnCollectorUrl(requestType, e.Protocol, e.CollectorUri)
if err == nil {
e.CollectorUrl = *collectorUrl
e.RequestType = requestType
}
}
// SetProtocol sets a new Protocol and updates the Collector URL.
func (e *Emitter) SetProtocol(protocol string) {
collectorUrl, err := returnCollectorUrl(e.RequestType, protocol, e.CollectorUri)
if err == nil {
e.CollectorUrl = *collectorUrl
e.Protocol = protocol
}
}