Debian Codegraph @

instrumentation/github.com/labstack/echo/otelecho/internal/semconv/client.go

raw
1 // Code generated by gotmpl. DO NOT MODIFY.
2 // source: internal/shared/semconv/client.go.tmpl
3
4 // Copyright The OpenTelemetry Authors
5 // SPDX-License-Identifier: Apache-2.0
6
7 // Package semconv provides OpenTelemetry semantic convention types and
8 // functionality.
9 package semconv // import "go.opentelemetry.io/contrib/instrumentation/github.com/labstack/echo/otelecho/internal/semconv"
10
11 import (
12 "context"
13 "fmt"
14 "net/http"
15 "slices"
16 "strconv"
17 "strings"
18
19 "go.opentelemetry.io/otel/attribute"
20 "go.opentelemetry.io/otel/codes"
21 "go.opentelemetry.io/otel/metric"
22 "go.opentelemetry.io/otel/semconv/v1.40.0"
23 "go.opentelemetry.io/otel/semconv/v1.40.0/httpconv"
24 )
25
26 type HTTPClient struct {
27 requestBodySize httpconv.ClientRequestBodySize
28 requestDuration httpconv.ClientRequestDuration
29 }
30
31 func NewHTTPClient(meter metric.Meter) HTTPClient {
32 client := HTTPClient{}
33
34 var err error
35 client.requestBodySize, err = httpconv.NewClientRequestBodySize(meter)
36 handleErr(err)
37
38 client.requestDuration, err = httpconv.NewClientRequestDuration(
39 meter,
40 metric.WithExplicitBucketBoundaries(0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10),
41 )
42 handleErr(err)
43
44 return client
45 }
46
47 func (n HTTPClient) Status(code int) (codes.Code, string) {
48 if code < 100 || code >= 600 {
49 return codes.Error, fmt.Sprintf("Invalid HTTP status code %d", code)
50 }
51 if code >= 400 {
52 return codes.Error, ""
53 }
54 return codes.Unset, ""
55 }
56
57 // RequestTraceAttrs returns trace attributes for an HTTP request made by a client.
58 func (n HTTPClient) RequestTraceAttrs(req *http.Request) []attribute.KeyValue {
59 /*
60 below attributes are returned:
61 - http.request.method
62 - http.request.method.original
63 - url.full
64 - server.address
65 - server.port
66 - network.protocol.name
67 - network.protocol.version
68 */
69 numOfAttributes := 3 // URL, server address, proto, and method.
70
71 var urlHost string
72 if req.URL != nil {
73 urlHost = req.URL.Host
74 }
75 var requestHost string
76 var requestPort int
77 for _, hostport := range []string{urlHost, req.Header.Get("Host")} {
78 requestHost, requestPort = SplitHostPort(hostport)
79 if requestHost != "" || requestPort > 0 {
80 break
81 }
82 }
83
84 eligiblePort := requiredHTTPPort(req.URL != nil && req.URL.Scheme == "https", requestPort)
85 if eligiblePort > 0 {
86 numOfAttributes++
87 }
88 useragent := req.UserAgent()
89 if useragent != "" {
90 numOfAttributes++
91 }
92
93 protoName, protoVersion := netProtocol(req.Proto)
94 if protoName != "" && protoName != "http" {
95 numOfAttributes++
96 }
97 if protoVersion != "" {
98 numOfAttributes++
99 }
100
101 method, originalMethod := n.method(req.Method)
102 if originalMethod != (attribute.KeyValue{}) {
103 numOfAttributes++
104 }
105
106 attrs := make([]attribute.KeyValue, 0, numOfAttributes)
107
108 attrs = append(attrs, method)
109 if originalMethod != (attribute.KeyValue{}) {
110 attrs = append(attrs, originalMethod)
111 }
112
113 var u string
114 if req.URL != nil {
115 // Remove any username/password info that may be in the URL.
116 userinfo := req.URL.User
117 req.URL.User = nil
118 u = req.URL.String()
119 // Restore any username/password info that was removed.
120 req.URL.User = userinfo
121 }
122 attrs = append(attrs, semconv.URLFull(u))
123
124 attrs = append(attrs, semconv.ServerAddress(requestHost))
125 if eligiblePort > 0 {
126 attrs = append(attrs, semconv.ServerPort(eligiblePort))
127 }
128
129 if protoName != "" && protoName != "http" {
130 attrs = append(attrs, semconv.NetworkProtocolName(protoName))
131 }
132 if protoVersion != "" {
133 attrs = append(attrs, semconv.NetworkProtocolVersion(protoVersion))
134 }
135
136 return attrs
137 }
138
139 // ResponseTraceAttrs returns trace attributes for an HTTP response made by a client.
140 func (n HTTPClient) ResponseTraceAttrs(resp *http.Response) []attribute.KeyValue {
141 /*
142 below attributes are returned:
143 - http.response.status_code
144 - error.type
145 */
146 var count int
147 if resp.StatusCode > 0 {
148 count++
149 }
150
151 if isErrorStatusCode(resp.StatusCode) {
152 count++
153 }
154
155 attrs := make([]attribute.KeyValue, 0, count)
156 if resp.StatusCode > 0 {
157 attrs = append(attrs, semconv.HTTPResponseStatusCode(resp.StatusCode))
158 }
159
160 if isErrorStatusCode(resp.StatusCode) {
161 errorType := strconv.Itoa(resp.StatusCode)
162 attrs = append(attrs, semconv.ErrorTypeKey.String(errorType))
163 }
164 return attrs
165 }
166
167 func (n HTTPClient) method(method string) (attribute.KeyValue, attribute.KeyValue) {
168 if method == "" {
169 return semconv.HTTPRequestMethodGet, attribute.KeyValue{}
170 }
171 if attr, ok := methodLookup[method]; ok {
172 return attr, attribute.KeyValue{}
173 }
174
175 orig := semconv.HTTPRequestMethodOriginal(method)
176 if attr, ok := methodLookup[strings.ToUpper(method)]; ok {
177 return attr, orig
178 }
179 return semconv.HTTPRequestMethodGet, orig
180 }
181
182 func (n HTTPClient) MetricAttributes(req *http.Request, statusCode int, additionalAttributes []attribute.KeyValue) []attribute.KeyValue {
183 num := len(additionalAttributes) + 2
184 var h string
185 if req.URL != nil {
186 h = req.URL.Host
187 }
188 var requestHost string
189 var requestPort int
190 for _, hostport := range []string{h, req.Header.Get("Host")} {
191 requestHost, requestPort = SplitHostPort(hostport)
192 if requestHost != "" || requestPort > 0 {
193 break
194 }
195 }
196
197 port := requiredHTTPPort(req.URL != nil && req.URL.Scheme == "https", requestPort)
198 if port > 0 {
199 num++
200 }
201
202 protoName, protoVersion := netProtocol(req.Proto)
203 if protoName != "" {
204 num++
205 }
206 if protoVersion != "" {
207 num++
208 }
209
210 if statusCode > 0 {
211 num++
212 }
213
214 attributes := slices.Grow(additionalAttributes, num)
215 attributes = append(attributes,
216 semconv.HTTPRequestMethodKey.String(standardizeHTTPMethod(req.Method)),
217 semconv.ServerAddress(requestHost),
218 n.scheme(req),
219 )
220
221 if port > 0 {
222 attributes = append(attributes, semconv.ServerPort(port))
223 }
224 if protoName != "" {
225 attributes = append(attributes, semconv.NetworkProtocolName(protoName))
226 }
227 if protoVersion != "" {
228 attributes = append(attributes, semconv.NetworkProtocolVersion(protoVersion))
229 }
230
231 if statusCode > 0 {
232 attributes = append(attributes, semconv.HTTPResponseStatusCode(statusCode))
233 }
234 return attributes
235 }
236
237 type MetricOpts struct {
238 measurement metric.MeasurementOption
239 addOptions metric.AddOption
240 }
241
242 func (o MetricOpts) MeasurementOption() metric.MeasurementOption {
243 return o.measurement
244 }
245
246 func (o MetricOpts) AddOptions() metric.AddOption {
247 return o.addOptions
248 }
249
250 func (n HTTPClient) MetricOptions(ma MetricAttributes) MetricOpts {
251 attributes := n.MetricAttributes(ma.Req, ma.StatusCode, ma.AdditionalAttributes)
252 set := metric.WithAttributeSet(attribute.NewSet(attributes...))
253
254 return MetricOpts{
255 measurement: set,
256 addOptions: set,
257 }
258 }
259
260 func (n HTTPClient) RecordMetrics(ctx context.Context, md MetricData, opts MetricOpts) {
261 recordOpts := metricRecordOptionPool.Get().(*[]metric.RecordOption)
262 defer func() {
263 *recordOpts = (*recordOpts)[:0]
264 metricRecordOptionPool.Put(recordOpts)
265 }()
266 *recordOpts = append(*recordOpts, opts.MeasurementOption())
267
268 n.requestBodySize.Inst().Record(ctx, md.RequestSize, *recordOpts...)
269 n.requestDuration.Inst().Record(ctx, durationToSeconds(md.RequestDuration), *recordOpts...)
270 }
271
272 // TraceAttributes returns attributes for httptrace.
273 func (n HTTPClient) TraceAttributes(host string) []attribute.KeyValue {
274 return []attribute.KeyValue{
275 semconv.ServerAddress(host),
276 }
277 }
278
279 func (n HTTPClient) scheme(req *http.Request) attribute.KeyValue {
280 if req.URL != nil && req.URL.Scheme != "" {
281 return semconv.URLScheme(req.URL.Scheme)
282 }
283 if req.TLS != nil {
284 return semconv.URLScheme("https")
285 }
286 return semconv.URLScheme("http")
287 }
288
289 func isErrorStatusCode(code int) bool {
290 return code >= 400 || code < 100
291 }