Repository navigation
Expand file tree
/
Copy pathnative_histogram.go
More file actions
234 lines (195 loc) · 7.72 KB
/
Copy pathnative_histogram.go
File metadata and controls
234 lines (195 loc) · 7.72 KB
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
// Copyright (c) 2026 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package tally
import (
"errors"
"sync"
"time"
)
// DefaultNativeHistogramMaxBuckets is the bucket budget used when a scope
// does not configure one. Matches the OpenTelemetry exponential histogram
// default max size.
const DefaultNativeHistogramMaxBuckets = 160
// ErrNativeHistogramBackendNotConfigured is returned by MarshalBinary when a
// scope has no ScopeOptions.NativeHistogramFactory. Values are still counted,
// but there is no encoder to serialize them with, so nothing is reported.
var ErrNativeHistogramBackendNotConfigured = errors.New(
"native histogram backend not configured: " +
"set ScopeOptions.NativeHistogramFactory",
)
// NativeHistogramData is a mergeable accumulator backing a NativeHistogram,
// supplied by the application through ScopeOptions.NativeHistogramFactory.
//
// Implementations need not be safe for concurrent use; the owning scope
// serializes every call. MarshalBinary is expected to produce a self-describing
// encoding of everything accumulated since the last Clear, in whatever format
// the configured reporter understands.
type NativeHistogramData interface {
// Update records a single observation.
Update(value float64)
// Count returns the number of observations accumulated since the last
// Clear.
Count() uint64
// Clear discards everything accumulated so far.
Clear()
// MarshalBinary serializes everything accumulated since the last Clear.
MarshalBinary() ([]byte, error)
}
// NativeValueHistogram is the interface for emitting native histogram metrics
// over unitless values: a distribution whose buckets are derived from the
// observed values rather than declared up front, reported as one serialized
// payload per interval instead of as a counter per bucket.
//
// Values and durations are separate types so that one distribution cannot mix
// the two. A native histogram has no declared buckets to signal which it
// holds, so unlike Histogram there is nothing to catch the mistake later: the
// samples are simply accumulated together and the percentiles come out wrong.
type NativeValueHistogram interface {
// RecordValue records a specific value directly.
RecordValue(value float64)
}
// NativeDurationHistogram is the NativeValueHistogram equivalent for
// durations, which it records as milliseconds.
type NativeDurationHistogram interface {
// RecordDuration records a specific duration directly, as milliseconds.
RecordDuration(value time.Duration)
// Start gives you a specific point in time to then record a duration.
Start() Stopwatch
}
// Asserted here rather than left to the scope: on its own this file has no
// call site that would catch a variant drifting out of its interface.
var (
_ NativeValueHistogram = nativeValueHistogram{}
_ NativeDurationHistogram = nativeDurationHistogram{}
_ StopwatchRecorder = nativeDurationHistogram{}
)
type nativeHistogram struct {
// mtx guards data, whose implementations are supplied by the application
// and are not required to be safe for concurrent use.
mtx sync.Mutex
data NativeHistogramData
cachedNativeHistogram CachedNativeHistogram
}
func newNativeHistogram(
data NativeHistogramData,
cachedNativeHistogram CachedNativeHistogram,
) *nativeHistogram {
return &nativeHistogram{
data: data,
cachedNativeHistogram: cachedNativeHistogram,
}
}
// record is the only way into the accumulator. It is deliberately unexported
// and unit-agnostic: both variants embed *nativeHistogram, so an exported
// Record method here would be promoted into each of them and hand a caller
// back the API the split exists to withhold.
func (h *nativeHistogram) record(value float64) {
h.mtx.Lock()
defer h.mtx.Unlock()
h.data.Update(value)
}
// drain marshals everything accumulated since the last drain and resets the
// accumulator, so each payload is a delta covering one reporting interval
// rather than the distribution's whole history.
//
// A marshal error clears the accumulator as well. Marshalling is
// deterministic, so re-presenting the same samples cannot succeed, and holding
// them would wedge the histogram for good: when it is the accumulated state
// that the encoder rejected, Clear is the only way back. Losing one interval
// beats never reporting again.
func (h *nativeHistogram) drain() ([]byte, uint64, bool) {
h.mtx.Lock()
defer h.mtx.Unlock()
samples := h.data.Count()
if samples == 0 {
return nil, 0, false
}
payload, err := h.data.MarshalBinary()
h.data.Clear()
if err != nil {
return nil, 0, false
}
return payload, samples, true
}
func (h *nativeHistogram) report(name string, tags map[string]string, r StatsReporter) {
payload, samples, ok := h.drain()
if !ok {
return
}
r.ReportNativeHistogram(name, tags, payload, samples)
}
func (h *nativeHistogram) cachedReport() {
payload, samples, ok := h.drain()
if !ok {
return
}
h.cachedNativeHistogram.ReportNativeHistogram(payload, samples)
}
func (h *nativeHistogram) snapshot() uint64 {
h.mtx.Lock()
defer h.mtx.Unlock()
return h.data.Count()
}
// nativeValueHistogram is the unitless view of an accumulator.
type nativeValueHistogram struct {
*nativeHistogram
}
func (h nativeValueHistogram) RecordValue(value float64) {
h.record(value)
}
// nativeDurationHistogram is the duration view of an accumulator.
type nativeDurationHistogram struct {
*nativeHistogram
}
// RecordDuration records value in MILLISECONDS. This deliberately differs from
// DurationBuckets.AsValues(), which is seconds: record() buckets the value on
// the way in, and 1000x is not a power-of-two shift, so no reporter downstream
// can rescale the sketch afterwards. The unit has to be right here.
func (h nativeDurationHistogram) RecordDuration(value time.Duration) {
h.record(float64(value) / float64(time.Millisecond))
}
func (h nativeDurationHistogram) Start() Stopwatch {
return NewStopwatch(globalNow(), h)
}
func (h nativeDurationHistogram) RecordStopwatch(stopwatchStart time.Time) {
d := globalNow().Sub(stopwatchStart)
h.RecordDuration(d)
}
// defaultNativeHistogramData counts observations but cannot serialize them.
// It is what a scope falls back to when no NativeHistogramFactory is set, so
// that the native histogram methods are safe to call but emit nothing.
type defaultNativeHistogramData struct {
count uint64
}
func defaultNativeHistogramFactory(maxBuckets int) NativeHistogramData {
return &defaultNativeHistogramData{}
}
func (d *defaultNativeHistogramData) Update(value float64) {
d.count++
}
func (d *defaultNativeHistogramData) Count() uint64 {
return d.count
}
func (d *defaultNativeHistogramData) Clear() {
d.count = 0
}
func (d *defaultNativeHistogramData) MarshalBinary() ([]byte, error) {
return nil, ErrNativeHistogramBackendNotConfigured
}