-
Notifications
You must be signed in to change notification settings - Fork 42
/
queries.go
194 lines (166 loc) · 3.44 KB
/
queries.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
package gobrake
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"sync"
"time"
)
type QueryInfo struct {
Method string
Route string
Query string
Func string
File string
Line int
StartTime time.Time
EndTime time.Time
}
type queryKey struct {
Method string `json:"method"`
Route string `json:"route"`
Query string `json:"query"`
Func string `json:"function"`
File string `json:"file"`
Line int `json:"line"`
Time time.Time `json:"time"`
}
type queryKeyStat struct {
queryKey
*tdigestStat
}
type queryStats struct {
opt *NotifierOptions
flushTimer *time.Timer
addWG *sync.WaitGroup
mu sync.Mutex
m map[queryKey]*tdigestStat
}
func newQueryStats(opt *NotifierOptions) *queryStats {
return &queryStats{
opt: opt,
}
}
func (s *queryStats) init() {
if s.flushTimer == nil {
s.flushTimer = time.AfterFunc(flushPeriod, s.flush)
s.addWG = new(sync.WaitGroup)
s.m = make(map[queryKey]*tdigestStat)
}
}
func (s *queryStats) flush() {
s.mu.Lock()
s.flushTimer = nil
addWG := s.addWG
s.addWG = nil
m := s.m
s.m = nil
s.mu.Unlock()
addWG.Wait()
err := s.send(m)
if err != nil {
logger.Printf("queryStats.send failed: %s", err)
}
}
type queriesOut struct {
Env string `json:"environment"`
Queries []queryKeyStat `json:"queries"`
}
func (s *queryStats) send(m map[queryKey]*tdigestStat) error {
var queries []queryKeyStat
for k, v := range m {
err := v.Pack()
if err != nil {
return err
}
queries = append(queries, queryKeyStat{
queryKey: k,
tdigestStat: v,
})
}
buf := buffers.Get().(*bytes.Buffer)
defer buffers.Put(buf)
buf.Reset()
out := queriesOut{
Env: s.opt.Environment,
Queries: queries,
}
err := json.NewEncoder(buf).Encode(&out)
if err != nil {
return err
}
req, err := http.NewRequest(
http.MethodPut,
fmt.Sprintf("%s/api/v5/projects/%d/queries-stats",
s.opt.APMHost, s.opt.ProjectId),
buf,
)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+s.opt.ProjectKey)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", userAgent)
resp, err := s.opt.HTTPClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
buf.Reset()
_, err = buf.ReadFrom(resp.Body)
if err != nil {
return err
}
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
return nil
}
switch resp.StatusCode {
case http.StatusUnauthorized:
return errUnauthorized
case http.StatusBadRequest, http.StatusTooManyRequests:
var sendResp sendResponse
err = json.NewDecoder(buf).Decode(&sendResp)
if err != nil {
return err
}
return errors.New(sendResp.Message)
case 404, 408, 409, 410, 500, 502, 504:
setQueryBacklog(out)
}
err = fmt.Errorf("got unexpected response status=%q", resp.Status)
return err
}
func (s *queryStats) Notify(c context.Context, q *QueryInfo) error {
if s.opt.DisableAPM {
return fmt.Errorf(
"APM is disabled, query is not sent: %s (%s:%d)",
q.Query, q.File, q.Line,
)
}
key := queryKey{
Method: q.Method,
Route: q.Route,
Query: q.Query,
Func: q.Func,
File: q.File,
Line: q.Line,
Time: q.StartTime.UTC().Truncate(time.Minute),
}
s.mu.Lock()
s.init()
stat, ok := s.m[key]
if !ok {
stat = newTDigestStat()
s.m[key] = stat
}
addWG := s.addWG
s.addWG.Add(1)
s.mu.Unlock()
dur := q.EndTime.Sub(q.StartTime)
err := stat.Add(dur)
addWG.Done()
return err
}