File: client.go

package info (click to toggle)
golang-github-cactus-go-statsd-client 5.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 204 kB
  • sloc: makefile: 5
file content (315 lines) | stat: -rw-r--r-- 8,242 bytes parent folder | download
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
303
304
305
306
307
308
309
310
311
312
313
314
315
// Copyright (c) 2012-2016 Eli Janssen
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.

package statsd

import (
	"fmt"
	"math/rand"
	"strconv"
	"strings"
	"time"
)

var bufPool = newBufferPool()

// The StatSender interface wraps all the statsd metric methods
type StatSender interface {
	Inc(string, int64, float32, ...Tag) error
	Dec(string, int64, float32, ...Tag) error
	Gauge(string, int64, float32, ...Tag) error
	GaugeDelta(string, int64, float32, ...Tag) error
	Timing(string, int64, float32, ...Tag) error
	TimingDuration(string, time.Duration, float32, ...Tag) error
	Set(string, string, float32, ...Tag) error
	SetInt(string, int64, float32, ...Tag) error
	Raw(string, string, float32, ...Tag) error
}

// The Statter interface defines the behavior of a stat client
type Statter interface {
	StatSender
	NewSubStatter(string) SubStatter
	SetPrefix(string)
	Close() error
}

// The SubStatter interface defines the behavior of a stat child/subclient
type SubStatter interface {
	StatSender
	SetSamplerFunc(SamplerFunc)
	NewSubStatter(string) SubStatter
}

// The SamplerFunc type defines a function that can serve
// as a Client sampler function.
type SamplerFunc func(float32) bool

// DefaultSampler is the default rate sampler function
func DefaultSampler(rate float32) bool {
	if rate < 1 {
		return rand.Float32() < rate
	}
	return true
}

// A Client is a statsd client.
type Client struct {
	// prefix for statsd name
	prefix string
	// packet sender
	sender Sender
	// sampler method
	sampler SamplerFunc
	// tag handler
	tagFormat TagFormat
}

// Close closes the connection and cleans up.
func (s *Client) Close() error {
	if s == nil {
		return nil
	}

	err := s.sender.Close()
	return err
}

// Inc increments a statsd count type.
// stat is a string name for the metric.
// value is the integer value
// rate is the sample rate (0.0 to 1.0)
// tags is a []Tag
func (s *Client) Inc(stat string, value int64, rate float32, tags ...Tag) error {
	if !s.includeStat(rate) {
		return nil
	}

	return s.submit(stat, "", value, "|c", rate, tags)
}

// Dec decrements a statsd count type.
// stat is a string name for the metric.
// value is the integer value.
// rate is the sample rate (0.0 to 1.0).
func (s *Client) Dec(stat string, value int64, rate float32, tags ...Tag) error {
	if !s.includeStat(rate) {
		return nil
	}

	return s.submit(stat, "", -value, "|c", rate, tags)
}

// Gauge submits/updates a statsd gauge type.
// stat is a string name for the metric.
// value is the integer value.
// rate is the sample rate (0.0 to 1.0).
func (s *Client) Gauge(stat string, value int64, rate float32, tags ...Tag) error {
	if !s.includeStat(rate) {
		return nil
	}

	return s.submit(stat, "", value, "|g", rate, tags)
}

// GaugeDelta submits a delta to a statsd gauge.
// stat is the string name for the metric.
// value is the (positive or negative) change.
// rate is the sample rate (0.0 to 1.0).
func (s *Client) GaugeDelta(stat string, value int64, rate float32, tags ...Tag) error {
	if !s.includeStat(rate) {
		return nil
	}

	// if negative, the submit formatter will prefix with a - already
	// so only special case the positive value.
	// don't pull out the prefix here, avoids some tiny amount of stack space by
	// inlining like this. performance
	if value >= 0 {
		return s.submit(stat, "+", value, "|g", rate, tags)
	}
	return s.submit(stat, "", value, "|g", rate, tags)
}

// Timing submits a statsd timing type.
// stat is a string name for the metric.
// delta is the time duration value in milliseconds
// rate is the sample rate (0.0 to 1.0).
func (s *Client) Timing(stat string, delta int64, rate float32, tags ...Tag) error {
	if !s.includeStat(rate) {
		return nil
	}

	return s.submit(stat, "", delta, "|ms", rate, tags)
}

// TimingDuration submits a statsd timing type.
// stat is a string name for the metric.
// delta is the timing value as time.Duration
// rate is the sample rate (0.0 to 1.0).
func (s *Client) TimingDuration(stat string, delta time.Duration, rate float32, tags ...Tag) error {
	if !s.includeStat(rate) {
		return nil
	}

	ms := float64(delta) / float64(time.Millisecond)
	return s.submit(stat, "", ms, "|ms", rate, tags)
}

// Set submits a stats set type
// stat is a string name for the metric.
// value is the string value
// rate is the sample rate (0.0 to 1.0).
func (s *Client) Set(stat string, value string, rate float32, tags ...Tag) error {
	if !s.includeStat(rate) {
		return nil
	}

	return s.submit(stat, "", value, "|s", rate, tags)
}

// SetInt submits a number as a stats set type.
// stat is a string name for the metric.
// value is the integer value
// rate is the sample rate (0.0 to 1.0).
func (s *Client) SetInt(stat string, value int64, rate float32, tags ...Tag) error {
	if !s.includeStat(rate) {
		return nil
	}

	return s.submit(stat, "", value, "|s", rate, tags)
}

// Raw submits a preformatted value.
// stat is the string name for the metric.
// value is a preformatted "raw" value string.
// rate is the sample rate (0.0 to 1.0).
func (s *Client) Raw(stat string, value string, rate float32, tags ...Tag) error {
	if !s.includeStat(rate) {
		return nil
	}

	return s.submit(stat, "", value, "", rate, tags)
}

// SetSamplerFunc sets a sampler function to something other than the default
// sampler is a function that determines whether the metric is
// to be accepted, or discarded.
// An example use case is for submitted pre-sampled metrics.
func (s *Client) SetSamplerFunc(sampler SamplerFunc) {
	s.sampler = sampler
}

// submit an already sampled raw stat
func (s *Client) submit(stat, vprefix string, value interface{}, suffix string, rate float32, tags []Tag) error {
	skiptags := false
	if len(tags) == 0 {
		skiptags = true
	}

	buf := bufPool.Get()
	defer bufPool.Put(buf)
	// sadly, no way to jam this back into the bytes.Buffer without
	// doing a few allocations... avoiding those is the whole point here...
	// so from here on out just use it as a raw []byte
	data := buf.Bytes()

	if s.prefix != "" {
		data = append(data, s.prefix...)
		data = append(data, '.')
	}

	data = append(data, stat...)

	// infix tags, if present
	if !skiptags && s.tagFormat&AllInfix != 0 {
		data = s.tagFormat.WriteInfix(data, tags)
		// if we did infix already, no suffix also.
		skiptags = true
	}

	data = append(data, ':')

	if vprefix != "" {
		data = append(data, vprefix...)
	}

	switch v := value.(type) {
	case string:
		data = append(data, v...)
	case int64:
		data = strconv.AppendInt(data, v, 10)
	case float64:
		data = strconv.AppendFloat(data, v, 'f', -1, 64)
	default:
		return fmt.Errorf("No matching type format")
	}

	if suffix != "" {
		data = append(data, suffix...)
	}

	if rate < 1 {
		data = append(data, "|@"...)
		data = strconv.AppendFloat(data, float64(rate), 'f', 6, 32)
	}

	// suffix tags if present
	if !skiptags && s.tagFormat&AllSuffix != 0 {
		data = s.tagFormat.WriteSuffix(data, tags)
	}

	_, err := s.sender.Send(data)
	return err
}

// check for nil client, and perform sampling calculation
func (s *Client) includeStat(rate float32) bool {
	if s == nil {
		return false
	}

	// test for nil in case someone builds their own
	// client without calling new (result is nil sampler)
	if s.sampler != nil {
		return s.sampler(rate)
	}
	return DefaultSampler(rate)
}

// SetPrefix sets/updates the statsd client prefix.
// Note: Does not change the prefix of any SubStatters.
func (s *Client) SetPrefix(prefix string) {
	if s == nil {
		return
	}

	s.prefix = prefix
}

// NewSubStatter returns a SubStatter with appended prefix
func (s *Client) NewSubStatter(prefix string) SubStatter {
	var c *Client
	if s != nil {
		c = &Client{
			prefix:  joinPathComp(s.prefix, prefix),
			sender:  s.sender,
			sampler: s.sampler,
		}
	}
	return c
}

// joinPathComp is a helper that ensures we combine path components with a dot
// when it's appropriate to do so; prefix is the existing prefix and suffix is
// the new component being added.
//
// It returns the joined prefix.
func joinPathComp(prefix, suffix string) string {
	suffix = strings.TrimLeft(suffix, ".")
	if prefix != "" && suffix != "" {
		return prefix + "." + suffix
	}
	return prefix + suffix
}