Debian Codegraph @

api/v1/lib/extras/metrics/metrics.go

raw symbols SCIP
1 package metrics
2
3 import (
4 "time"
5 )
6
7 func InMicroseconds(d time.Duration) float64 {
8 return float64(d.Nanoseconds() / time.Microsecond.Nanoseconds())
9 }
10
11 type (
12 Counter func(...string)
13 Adder func(float64, ...string)
14 Watcher func(float64, ...string)
15 )
16
17 // Int adds the value of `x`; convenience func for adding integers.
18 func (a Adder) Int(x int, s ...string) {
19 a(float64(x), s...)
20 }
21
22 // Since records an observation of time.Now().Sub(t) in microseconds
23 func (w Watcher) Since(t time.Time, s ...string) {
24 w(InMicroseconds(time.Now().Sub(t)), s...)
25 }
26
27 // Harness funcs execute the given func and record metrics concerning the execution. The error
28 // returned from the harness is the same error returned from the execution of the func param.
29 type Harness func(func() error, ...string) error
30
31 // NewHarness generates and returns an execution harness that records metrics. `counts` and `errors`
32 // are required; `timed` and `clock` must either both be nil, or both be non-nil.
33 func NewHarness(counts, errors Counter, timed Watcher, clock func() time.Time) Harness {
34 var harness Harness
35 if timed != nil && clock != nil {
36 harness = func(f func() error, labels ...string) error {
37 counts(labels...)
38 var (
39 t = clock()
40 err = f()
41 )
42 timed.Since(t, labels...)
43 if err != nil {
44 errors(labels...)
45 }
46 return err
47 }
48 } else {
49 harness = func(f func() error, labels ...string) error {
50 counts(labels...)
51 err := f()
52 if err != nil {
53 errors(labels...)
54 }
55 return err
56 }
57 }
58 return harness
59 }