File: http_round_tripper.go

package info (click to toggle)
golang-gitlab-gitlab-org-labkit 1.17.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,092 kB
  • sloc: sh: 210; javascript: 49; makefile: 4
file content (70 lines) | stat: -rw-r--r-- 2,277 bytes parent folder | download | duplicates (3)
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
package http_round_tripper

import (
	"net/http"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

// Metric names for the recorded metrics.
// These are the conventional names prometheus uses for these metrics.
const (
	inFlightRequestsMetricName       = "in_flight_requests"
	requestsTotalMetricName          = "requests_total"
	requestDurationSecondsMetricName = "request_duration_seconds"
)

// Factory creates middleware instances. Created by NewFactory.
type Factory func(next http.RoundTripper, opts ...Option) http.RoundTripper

// NewFactory will create a function for creating metric middlewares.
// The resulting function can be called multiple times to obtain multiple middleware
// instances.
// Each instance can be configured with different options that will be applied to the
// same underlying metrics.
func NewFactory(opts ...FactoryOption) Factory {
	config := applyFactoryOptions(opts)

	inFlightRequests := prometheus.NewGauge(prometheus.GaugeOpts{
		Namespace: config.namespace,
		Subsystem: config.subsystem,
		Name:      inFlightRequestsMetricName,
		Help:      "A gauge of requests currently being handled.",
	})

	requestsTotal := prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Namespace: config.namespace,
			Subsystem: config.subsystem,
			Name:      requestsTotalMetricName,
			Help:      "A counter for total number of requests.",
		},
		config.labels,
	)

	requestDurationSeconds := prometheus.NewHistogramVec(
		prometheus.HistogramOpts{
			Namespace: config.namespace,
			Subsystem: config.subsystem,
			Name:      requestDurationSecondsMetricName,
			Help:      "A histogram of latencies for requests.",
			Buckets:   config.requestDurationBuckets,
		},
		config.labels,
	)

	prometheus.MustRegister(inFlightRequests, requestsTotal, requestDurationSeconds)

	return func(next http.RoundTripper, opts ...Option) http.RoundTripper {
		config := applyOptions(opts)

		rt := next

		rt = promhttp.InstrumentRoundTripperCounter(requestsTotal.MustCurryWith(config.labelValues), rt)
		rt = promhttp.InstrumentRoundTripperDuration(requestDurationSeconds.MustCurryWith(config.labelValues), rt)
		rt = promhttp.InstrumentRoundTripperInFlight(inFlightRequests, rt)

		return rt
	}
}