forked from maddyblue/goread
-
Notifications
You must be signed in to change notification settings - Fork 0
/
types.go
302 lines (263 loc) · 6.97 KB
/
types.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
/*
* Copyright (c) 2013 Matt Jibson <matt.jibson@gmail.com>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package miniprofiler
import (
"encoding/json"
"fmt"
"html/template"
"math/rand"
"net/http"
"runtime/debug"
"strings"
"sync"
"time"
)
var rnd = rand.New(&lockedSource{src: rand.NewSource(time.Now().UnixNano())})
type lockedSource struct {
lk sync.Mutex
src rand.Source
}
func (r *lockedSource) Int63() (n int64) {
r.lk.Lock()
n = r.src.Int63()
r.lk.Unlock()
return
}
func (r *lockedSource) Seed(seed int64) {
r.lk.Lock()
r.src.Seed(seed)
r.lk.Unlock()
}
func newGuid() string {
return fmt.Sprintf("%016x", rnd.Int63())
}
type Profile struct {
Id string
Name string
start time.Time
Started int64
MachineName string
Root *Timing
ClientTimings *ClientTimings
DurationMilliseconds float64
CustomLinks map[string]string
w http.ResponseWriter
r *http.Request
}
type Timing struct {
Id string
Name string
DurationMilliseconds float64
StartMilliseconds float64
Children []*Timing
CustomTimings map[string][]*CustomTiming
profile *Profile
sync.Mutex
}
// NewProfile creates a new Profile with given name.
// For use only by miniprofiler extensions.
func NewProfile(w http.ResponseWriter, r *http.Request, name string) *Profile {
p := &Profile{
w: w,
r: r,
}
if Enable(r) {
p.Id = newGuid()
p.Name = name
p.CustomLinks = make(map[string]string)
p.start = time.Now()
p.MachineName = MachineName()
p.Root = &Timing{
Id: newGuid(),
profile: p,
}
w.Header().Add("X-MiniProfiler-Ids", "[\""+p.Id+"\"]")
}
return p
}
// Finalize finalizes a Profile and Store()s it.
// For use only by miniprofiler extensions.
func (p *Profile) Finalize() {
if p.Root == nil {
return
}
u := p.r.URL
if !u.IsAbs() {
u.Host = p.r.Host
if p.r.TLS == nil {
u.Scheme = "http"
} else {
u.Scheme = "https"
}
}
p.Root.Name = p.r.Method + " " + u.String()
p.Started = p.start.Unix() * 1000
p.DurationMilliseconds = Since(p.start)
p.Root.DurationMilliseconds = p.DurationMilliseconds
Store(p.r, p)
}
// ProfileFromJson returns a Profile from JSON data.
func ProfileFromJson(b []byte) *Profile {
p := Profile{}
json.Unmarshal(b, &p)
return &p
}
// Json converts a profile to JSON.
func (p *Profile) Json() []byte {
b, _ := json.Marshal(p)
return b
}
type Timer interface {
AddCustomTiming(callType, executeType string, start, end time.Time, command string)
Step(name string, f func(t Timer))
StepCustomTiming(callType, executeType, command string, f func())
AddCustomLink(name, URL string)
SetName(string)
Includes() template.HTML
}
func (p *Profile) SetName(name string) {
if p.Root != nil {
p.Name = name
}
}
func (T *Timing) SetName(name string) {
if T != nil {
T.profile.SetName(name)
}
}
func (p *Profile) AddCustomLink(name, URL string) {
if p.CustomLinks != nil {
p.CustomLinks[name] = URL
}
}
func (T *Timing) AddCustomLink(name, URL string) {
if T != nil {
T.profile.AddCustomLink(name, URL)
}
}
func (p *Profile) AddCustomTiming(callType, executeType string, start, end time.Time, command string) {
if p.Root != nil {
p.Root.AddCustomTiming(callType, executeType, start, end, command)
}
}
func (p *Profile) StepCustomTiming(callType, executeType, command string, f func()) {
if p.Root != nil {
p.Root.StepCustomTiming(callType, executeType, command, f)
} else {
f()
}
}
func (p *Profile) Step(name string, f func(t Timer)) {
if p.Root != nil {
p.Root.Step(name, f)
} else {
f(p)
}
}
func (T *Timing) Includes() template.HTML {
if T != nil {
return T.profile.Includes()
}
return ""
}
func (T *Timing) Step(name string, f func(t Timer)) {
t := &Timing{
Id: newGuid(),
Name: name,
StartMilliseconds: Since(T.profile.start),
profile: T.profile,
}
T.addChild(t)
f(t)
t.DurationMilliseconds = Since(t.profile.start) - t.StartMilliseconds
}
func (T *Timing) addChild(t *Timing) {
T.Lock()
T.Children = append(T.Children, t)
T.Unlock()
}
func (t *Timing) AddCustomTiming(callType, executeType string, start, end time.Time, command string) {
if t == nil {
return
}
t.Lock()
if t.CustomTimings == nil {
t.CustomTimings = make(map[string][]*CustomTiming)
}
s := &CustomTiming{
Id: newGuid(),
StartMilliseconds: start.Sub(t.profile.start).Seconds() * 1000,
DurationMilliseconds: end.Sub(start).Seconds() * 1000,
CommandString: command,
StackTraceSnippet: getStackSnippet(),
ExecuteType: executeType,
}
t.CustomTimings[callType] = append(t.CustomTimings[callType], s)
t.Unlock()
}
func (t *Timing) StepCustomTiming(callType, executeType, command string, f func()) {
start := time.Now()
f()
end := time.Now()
t.AddCustomTiming(callType, executeType, start, end, command)
}
func getStackSnippet() string {
stack := debug.Stack()
lines := strings.Split(string(stack), "\n")
var snippet []string
for i := 0; i < len(lines); i++ {
idx := strings.LastIndex(lines[i], " ")
if idx == -1 {
break
}
if i+1 < len(lines) && strings.HasPrefix(lines[i+1], "\t") {
i++
snip := strings.TrimSpace(lines[i])
snip = strings.Split(snip, ":")[0]
sp := strings.Split(snip, ".")
snip = sp[len(sp)-1]
if strings.Contains(snip, "miniprofiler") || strings.HasPrefix(snip, "_func_") || snip == "ServeHTTP" || snip == "ProfileRequest" {
continue
}
snippet = append(snippet, snip)
}
}
if len(snippet) > 2 {
snippet = snippet[2:]
}
return strings.Join(snippet, " ")
}
type CustomTiming struct {
Id string
ExecuteType string
CommandString string
StackTraceSnippet string
StartMilliseconds float64
DurationMilliseconds float64
FirstFetchDurationMilliseconds float64
}
type ClientTimings struct {
RedirectCount int64
Timings []*ClientTiming
}
func (c *ClientTimings) Len() int { return len(c.Timings) }
func (c *ClientTimings) Less(i, j int) bool { return c.Timings[i].Start < c.Timings[j].Start }
func (c *ClientTimings) Swap(i, j int) { c.Timings[i], c.Timings[j] = c.Timings[j], c.Timings[i] }
type ClientTiming struct {
Name string
Start int64
Duration int64
}