...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package trace
16
17 import (
18 "time"
19 )
20
21
22 const samplePeriod = time.Second
23
24
25
26 var defaultLatencies = [...]time.Duration{
27 10 * time.Microsecond,
28 100 * time.Microsecond,
29 time.Millisecond,
30 10 * time.Millisecond,
31 100 * time.Millisecond,
32 time.Second,
33 10 * time.Second,
34 time.Minute,
35 }
36
37
38 type bucket struct {
39 nextTime time.Time
40 buffer []*SpanData
41 nextIndex int
42 overflow bool
43 }
44
45 func makeBucket(bufferSize int) bucket {
46 return bucket{
47 buffer: make([]*SpanData, bufferSize),
48 }
49 }
50
51
52 func (b *bucket) add(s *SpanData) {
53 if s.EndTime.Before(b.nextTime) {
54 return
55 }
56 if len(b.buffer) == 0 {
57 return
58 }
59 b.nextTime = s.EndTime.Add(samplePeriod)
60 b.buffer[b.nextIndex] = s
61 b.nextIndex++
62 if b.nextIndex == len(b.buffer) {
63 b.nextIndex = 0
64 b.overflow = true
65 }
66 }
67
68
69 func (b *bucket) size() int {
70 if b.overflow {
71 return len(b.buffer)
72 }
73 return b.nextIndex
74 }
75
76
77 func (b *bucket) span(i int) *SpanData {
78 if !b.overflow {
79 return b.buffer[i]
80 }
81 if i < len(b.buffer)-b.nextIndex {
82 return b.buffer[b.nextIndex+i]
83 }
84 return b.buffer[b.nextIndex+i-len(b.buffer)]
85 }
86
87
88 func (b *bucket) resize(n int) {
89 cur := b.size()
90 newBuffer := make([]*SpanData, n)
91 if cur < n {
92 for i := 0; i < cur; i++ {
93 newBuffer[i] = b.span(i)
94 }
95 b.buffer = newBuffer
96 b.nextIndex = cur
97 b.overflow = false
98 return
99 }
100 for i := 0; i < n; i++ {
101 newBuffer[i] = b.span(i + cur - n)
102 }
103 b.buffer = newBuffer
104 b.nextIndex = 0
105 b.overflow = true
106 }
107
108
109 func latencyBucket(latency time.Duration) int {
110 i := 0
111 for i < len(defaultLatencies) && latency >= defaultLatencies[i] {
112 i++
113 }
114 return i
115 }
116
117
118
119
120
121
122 func latencyBucketBounds(index int) (lower time.Duration, upper time.Duration) {
123 if index == 0 {
124 return 0, defaultLatencies[index]
125 }
126 if index == len(defaultLatencies) {
127 return defaultLatencies[index-1], 1<<63 - 1
128 }
129 return defaultLatencies[index-1], defaultLatencies[index]
130 }
131
View as plain text