-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
289 lines (222 loc) · 5.75 KB
/
client.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
// Copyright 2022 Axel Etcheverry. All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.
package amplitude
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"sync"
"time"
"github.com/rs/zerolog/log"
)
const (
StandardEndpoint = "https://api2.amplitude.com/2/httpapi"
EUResidencyEndpoint = "https://api.eu.amplitude.com/2/httpapi"
)
var userAgent = "Amplitude Golang Client (https://github.com/euskadi31/go-amplitude)"
// Client Amplitude interface.
type Client interface {
Enqueue(event *Event) error
Close() error
}
type client struct {
endpoint string
key string
timeout time.Duration
interval time.Duration
batchSize int
bufferSize int
maxRetry int
retryInterval time.Duration
retrySize int
httpClient *http.Client
msgs chan *Event
events []*Event
retries chan *Payload
quitCh chan struct{}
shutdownCh chan struct{}
flushCh chan struct{}
mtx sync.Mutex
}
// New Amplitude client.
func New(key string, opts ...Option) Client {
c := &client{
endpoint: StandardEndpoint,
key: key,
timeout: time.Second * 1,
interval: time.Second * 10,
batchSize: 1000,
bufferSize: 2000,
maxRetry: 3,
retryInterval: time.Second * 1,
retrySize: 1000,
quitCh: make(chan struct{}, 1),
shutdownCh: make(chan struct{}, 1),
flushCh: make(chan struct{}, 1),
}
c.httpClient = &http.Client{
Timeout: c.timeout,
}
c.msgs = make(chan *Event, c.bufferSize)
c.events = []*Event{} /*make(, 0, c.bufferSize)*/
c.retries = make(chan *Payload, c.retrySize)
for _, opt := range opts {
opt(c)
}
go c.loop()
return c
}
func (c *client) addEvent(event *Event) {
c.mtx.Lock()
defer c.mtx.Unlock()
c.events = append(c.events, event)
if len(c.events) == c.bufferSize {
c.flushCh <- struct{}{}
}
}
func (c *client) loop() {
defer close(c.shutdownCh)
tick := time.NewTicker(c.interval)
defer tick.Stop()
for {
select {
case <-c.flushCh:
c.flush()
case payload := <-c.retries:
if err := c.sendBatch(payload); err != nil {
if payload.Attempts > c.maxRetry {
log.Warn().Msgf("%d messages dropped because they failed to be sent after %d attempts", payload.Size, c.maxRetry)
continue
}
c.retries <- payload
}
case event := <-c.msgs:
c.addEvent(event)
case <-tick.C:
c.flush()
case <-c.quitCh:
log.Debug().Msg("exit requested - draining messages")
// Drain the msg channel, we have to close it first so no more
// messages can be pushed and otherwise the loop would never end.
close(c.msgs)
for event := range c.msgs {
c.addEvent(event)
}
c.flush()
close(c.retries)
for payload := range c.retries {
if err := c.sendBatch(payload); err != nil {
log.Error().Msg("Amplitude send batch failed, events lost !")
}
}
log.Debug().Msg("exit")
return
}
}
}
func (c *client) Close() (err error) {
defer func() {
// Always recover, a panic could be raised if `c`.quitCh was closed which
// means the method was called more than once.
if recover() != nil {
err = ErrClosed
}
}()
close(c.quitCh)
<-c.shutdownCh
return
}
func (c *client) processErrorResponse(resp *http.Response) error {
var errorResponse *ErrorResponse
if err := json.NewDecoder(resp.Body).Decode(&errorResponse); err != nil {
return fmt.Errorf("json decode failed: %w", err)
}
return errorResponse
}
func (c *client) sendBatch(payload *Payload) error {
ctx := context.Background()
payload.Attempts++
r, err := http.NewRequestWithContext(ctx, http.MethodPost, c.endpoint, bytes.NewReader(payload.Body))
if err != nil {
return fmt.Errorf("http new request failed: %w", err)
}
r.Header.Set("Content-Type", "application/json")
r.Header.Set("Accept", "application/json")
r.Header.Set("User-Agent", userAgent)
// r.Header.Add("Content-Length", strconv.Itoa(len(data)))
resp, err := c.httpClient.Do(r)
if err != nil {
log.Error().Err(err).Msg("")
return fmt.Errorf("http client send request failed: %w", err)
}
defer func() {
if err := resp.Body.Close(); err != nil {
log.Error().Err(err).Msg("http client close response body failed")
}
}()
if resp.StatusCode != http.StatusOK {
err := c.processErrorResponse(resp)
log.Error().Err(err).Msgf("Amplitude send batch failed: status code %d", resp.StatusCode)
return ErrBatchFailed
}
log.Debug().Msg("Amplitude sent batch !")
return nil
}
func (c *client) getBatchEvents() []*Event {
c.mtx.Lock()
defer c.mtx.Unlock()
if len(c.events) == 0 {
return []*Event{}
}
end := c.batchSize
if length := len(c.events); length < end {
end = length
}
var events []*Event
events, c.events = c.events[0:end], c.events[end:]
return events
}
func (c *client) flush() error {
events := c.getBatchEvents()
if len(events) == 0 {
return nil
}
reqPayload := &RequestPayload{
APIKey: c.key,
Events: events,
}
b, err := json.Marshal(reqPayload)
if err != nil {
return fmt.Errorf("json marshal events failed: %w", err)
}
payload := &Payload{
Body: b,
Size: len(events),
}
if err := c.sendBatch(payload); err != nil {
c.retries <- payload
}
return nil
}
func (c *client) Enqueue(event *Event) (err error) {
if event.Timestamp == 0 {
event.Timestamp = time.Now().UTC().Unix()
}
defer func() {
// When the `msgs` channel is closed writing to it will trigger a panic.
// To avoid letting the panic propagate to the caller we recover from it
// and instead report that the client has been closed and shouldn't be
// used anymore.
if recover() != nil {
err = ErrClosed
}
}()
if len(c.msgs) == (cap(c.msgs) - 1) {
c.flushCh <- struct{}{}
}
c.msgs <- event
return
}