Debian Codegraph @

exp/api/remote/remote_headers.go

raw
1 // Copyright 2024 The Prometheus Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package remote
15
16 import (
17 "errors"
18 "fmt"
19 "net/http"
20 "slices"
21 "strconv"
22 "strings"
23 )
24
25 const (
26 versionHeader = "X-Prometheus-Remote-Write-Version"
27 version1HeaderValue = "0.1.0"
28 version20HeaderValue = "2.0.0"
29 appProtoContentType = "application/x-protobuf"
30 )
31
32 // Compression represents the encoding. Currently remote storage supports only
33 // one, but we experiment with more, thus leaving the compression scaffolding
34 // for now.
35 type Compression string
36
37 const (
38 // SnappyBlockCompression represents https://github.com/google/snappy/blob/2c94e11145f0b7b184b831577c93e5a41c4c0346/format_description.txt
39 SnappyBlockCompression Compression = "snappy"
40 )
41
42 // WriteMessageType represents the fully qualified name of the protobuf message
43 // to use in Remote write 1.0 and 2.0 protocols.
44 // See https://prometheus.io/docs/specs/remote_write_spec_2_0/#protocol.
45 type WriteMessageType string
46
47 const (
48 // WriteV1MessageType represents the `prometheus.WriteRequest` protobuf
49 // message introduced in the https://prometheus.io/docs/specs/remote_write_spec/.
50 // DEPRECATED: Use WriteV2MessageType instead.
51 WriteV1MessageType WriteMessageType = "prometheus.WriteRequest"
52 // WriteV2MessageType represents the `io.prometheus.write.v2.Request` protobuf
53 // message introduced in https://prometheus.io/docs/specs/remote_write_spec_2_0/
54 WriteV2MessageType WriteMessageType = "io.prometheus.write.v2.Request"
55 )
56
57 // Validate returns error if the given reference for the protobuf message is not supported.
58 func (n WriteMessageType) Validate() error {
59 switch n {
60 case WriteV1MessageType, WriteV2MessageType:
61 return nil
62 default:
63 return fmt.Errorf("unknown type for remote write protobuf message %v, supported: %v", n, MessageTypes{WriteV1MessageType, WriteV2MessageType}.String())
64 }
65 }
66
67 type MessageTypes []WriteMessageType
68
69 func (m MessageTypes) Strings() []string {
70 ret := make([]string, 0, len(m))
71 for _, typ := range m {
72 ret = append(ret, string(typ))
73 }
74 return ret
75 }
76
77 func (m MessageTypes) String() string {
78 return strings.Join(m.Strings(), ", ")
79 }
80
81 func (m MessageTypes) Contains(mType WriteMessageType) bool {
82 return slices.Contains(m, mType)
83 }
84
85 var contentTypeHeaders = map[WriteMessageType]string{
86 WriteV1MessageType: appProtoContentType, // Also application/x-protobuf;proto=prometheus.WriteRequest but simplified for compatibility with 1.x spec.
87 WriteV2MessageType: appProtoContentType + ";proto=io.prometheus.write.v2.Request",
88 }
89
90 // ContentTypeHeader returns content type header value for the given proto message
91 // or empty string for unknown proto message.
92 func contentTypeHeader(m WriteMessageType) string {
93 return contentTypeHeaders[m]
94 }
95
96 const (
97 writtenSamplesHeader = "X-Prometheus-Remote-Write-Samples-Written"
98 writtenHistogramsHeader = "X-Prometheus-Remote-Write-Histograms-Written"
99 writtenExemplarsHeader = "X-Prometheus-Remote-Write-Exemplars-Written"
100 )
101
102 // WriteResponse represents the response from the remote storage upon receiving a remote write request.
103 type WriteResponse struct {
104 WriteResponseStats
105 statusCode int
106 extraHeaders http.Header
107 }
108
109 // NewWriteResponse creates a new WriteResponse with empty stats and status code http.StatusNoContent.
110 func NewWriteResponse() *WriteResponse {
111 return &WriteResponse{
112 WriteResponseStats: WriteResponseStats{},
113 statusCode: http.StatusNoContent,
114 extraHeaders: make(http.Header),
115 }
116 }
117
118 // Stats returns the current statistics.
119 func (w *WriteResponse) Stats() WriteResponseStats {
120 return w.WriteResponseStats
121 }
122
123 // SetStatusCode sets the HTTP status code for the response. http.StatusNoContent is the default unless 5xx is set.
124 func (w *WriteResponse) SetStatusCode(code int) {
125 w.statusCode = code
126 }
127
128 // StatusCode returns the current HTTP status code.
129 func (w *WriteResponse) StatusCode() int {
130 return w.statusCode
131 }
132
133 // SetExtraHeader adds additional headers to be set in the response (apart from stats headers)
134 func (w *WriteResponse) SetExtraHeader(key, value string) {
135 w.extraHeaders.Set(key, value)
136 }
137
138 // ExtraHeaders returns all additional headers to be set in the response (apart from stats headers).
139 func (w *WriteResponse) ExtraHeaders() http.Header {
140 return w.extraHeaders
141 }
142
143 // SetHeaders sets response headers in a given response writer.
144 // Make sure to use it before http.ResponseWriter.WriteHeader and .Write.
145 func (r *WriteResponse) SetHeaders(w http.ResponseWriter) {
146 h := w.Header()
147 h.Set(writtenSamplesHeader, strconv.Itoa(r.Samples))
148 h.Set(writtenHistogramsHeader, strconv.Itoa(r.Histograms))
149 h.Set(writtenExemplarsHeader, strconv.Itoa(r.Exemplars))
150 for k, v := range r.ExtraHeaders() {
151 for _, vv := range v {
152 h.Add(k, vv)
153 }
154 }
155 }
156
157 // WriteResponseStats represents the response, remote write statistics.
158 type WriteResponseStats struct {
159 // Samples represents X-Prometheus-Remote-Write-Written-Samples
160 Samples int
161 // Histograms represents X-Prometheus-Remote-Write-Written-Histograms
162 Histograms int
163 // Exemplars represents X-Prometheus-Remote-Write-Written-Exemplars
164 Exemplars int
165
166 // Confirmed means we can trust those statistics from the point of view
167 // of the PRW 2.0 spec. When parsed from headers, it means we got at least one
168 // response header from the Receiver to confirm those numbers, meaning it must
169 // be at least 2.0 Receiver. See ParseWriteResponseStats for details.
170 confirmed bool
171 }
172
173 // NoDataWritten returns true if statistics indicate no data was written.
174 func (s WriteResponseStats) NoDataWritten() bool {
175 return (s.Samples + s.Histograms + s.Exemplars) == 0
176 }
177
178 // AllSamples returns both float and histogram sample numbers.
179 func (s WriteResponseStats) AllSamples() int {
180 return s.Samples + s.Histograms
181 }
182
183 // Add adds the given WriteResponseStats to this WriteResponseStats.
184 // If this WriteResponseStats is empty, it will be replaced by the given WriteResponseStats.
185 func (s *WriteResponseStats) Add(rs WriteResponseStats) {
186 s.confirmed = rs.confirmed
187 s.Samples += rs.Samples
188 s.Histograms += rs.Histograms
189 s.Exemplars += rs.Exemplars
190 }
191
192 // parseWriteResponseStats returns WriteResponseStats parsed from the response headers.
193 //
194 // As per 2.0 spec, missing header means 0. However, abrupt HTTP errors, 1.0 Receivers
195 // or buggy 2.0 Receivers might result in no response headers specified and that
196 // might NOT necessarily mean nothing was written. To represent that we set
197 // s.Confirmed = true only when see at least on response header.
198 //
199 // Error is returned when any of the header fails to parse as int64.
200 func parseWriteResponseStats(r *http.Response) (s WriteResponseStats, err error) {
201 var (
202 errs []error
203 h = r.Header
204 )
205 if v := h.Get(writtenSamplesHeader); v != "" { // Empty means zero.
206 s.confirmed = true
207 if s.Samples, err = strconv.Atoi(v); err != nil {
208 s.Samples = 0
209 errs = append(errs, err)
210 }
211 }
212 if v := h.Get(writtenHistogramsHeader); v != "" { // Empty means zero.
213 s.confirmed = true
214 if s.Histograms, err = strconv.Atoi(v); err != nil {
215 s.Histograms = 0
216 errs = append(errs, err)
217 }
218 }
219 if v := h.Get(writtenExemplarsHeader); v != "" { // Empty means zero.
220 s.confirmed = true
221 if s.Exemplars, err = strconv.Atoi(v); err != nil {
222 s.Exemplars = 0
223 errs = append(errs, err)
224 }
225 }
226 return s, errors.Join(errs...)
227 }