File size: 2,813 Bytes
e89cd08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
//                           _       _
// __      _____  __ ___   ___  __ _| |_ ___
// \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
//  \ V  V /  __/ (_| |\ V /| | (_| | ||  __/
//   \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
//
//  Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
//
//  CONTACT: hello@weaviate.io
//

package monitoring

import (
	"io"
	"net/http"
	"strconv"

	"github.com/felixge/httpsnoop"
	"github.com/prometheus/client_golang/prometheus"
)

// StaticRouteLabel takes any http request and return canonical and static route label
// that can used in metrics without worrying about unbounded cardinality.

// Examples:
// `/schema/Movies/properties` -> `/schema/{className}`
// `/replicas/indices/Movies/shards/hello0/objects` -> `/replicas/indices`
type StaticRouteLabel func(r *http.Request) (*http.Request, string)

type InstrumentHandler struct {
	inflightRequests *prometheus.GaugeVec
	duration         *prometheus.HistogramVec

	// in bytes
	requestSize  *prometheus.HistogramVec
	responseSize *prometheus.HistogramVec

	// next is original http handler we instrument
	next http.Handler

	routeLabel StaticRouteLabel
}

func InstrumentHTTP(
	next http.Handler,
	routeLabel StaticRouteLabel,
	inflight *prometheus.GaugeVec,
	duration *prometheus.HistogramVec,
	requestSize *prometheus.HistogramVec,
	responseSize *prometheus.HistogramVec,
) *InstrumentHandler {
	return &InstrumentHandler{
		next:             next,
		routeLabel:       routeLabel,
		inflightRequests: inflight,
		duration:         duration,
		requestSize:      requestSize,
		responseSize:     responseSize,
	}
}

func (i *InstrumentHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	r, route := i.routeLabel(r)
	method := r.Method

	inflight := i.inflightRequests.WithLabelValues(method, route)
	inflight.Inc()
	defer inflight.Dec()

	origBody := r.Body
	defer func() {
		// We don't need `countingReadCloser` before this instrument handler
		r.Body = origBody
	}()

	cr := &countingReadCloser{
		r: r.Body,
	}
	r.Body = cr

	// This is where we run actual upstream http.Handler
	respWithMetrics := httpsnoop.CaptureMetricsFn(w, func(rw http.ResponseWriter) {
		i.next.ServeHTTP(rw, r)
	})

	i.requestSize.WithLabelValues(method, route).Observe(float64(cr.read))
	i.responseSize.WithLabelValues(method, route).Observe(float64(respWithMetrics.Written))

	labelValues := []string{
		method,
		route,
		strconv.Itoa(respWithMetrics.Code),
	}

	i.duration.WithLabelValues(labelValues...).Observe(respWithMetrics.Duration.Seconds())
}

type countingReadCloser struct {
	r    io.ReadCloser
	read int64
}

func (c *countingReadCloser) Read(p []byte) (int, error) {
	n, err := c.r.Read(p)
	if n > 0 {
		c.read += int64(n)
	}
	return n, err
}

func (c *countingReadCloser) Close() error {
	return c.r.Close()
}