1
0
mirror of https://github.com/open-telemetry/opentelemetry-go.git synced 2025-08-10 22:31:50 +02:00

chore: enable gocritic linter (#7095)

#### Description

Enable and fixes several rules from
[gocritic](https://golangci-lint.run/usage/linters/#gocritic) linter

---------

Signed-off-by: Matthieu MOREL <matthieu.morel35@gmail.com>
Co-authored-by: Tyler Yahn <MrAlias@users.noreply.github.com>
This commit is contained in:
Matthieu MOREL
2025-07-29 18:20:32 +02:00
committed by GitHub
parent 8955578fef
commit 982391315f
37 changed files with 158 additions and 146 deletions

View File

@@ -10,6 +10,7 @@ linters:
- depguard - depguard
- errcheck - errcheck
- errorlint - errorlint
- gocritic
- godot - godot
- gosec - gosec
- govet - govet
@@ -86,6 +87,20 @@ linters:
deny: deny:
- pkg: go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal - pkg: go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal
desc: Do not use cross-module internal packages. desc: Do not use cross-module internal packages.
gocritic:
disabled-checks:
- appendAssign
- commentedOutCode
- dupArg
- hugeParam
- importShadow
- paramTypeCombine
- ptrToRefParam
- preferDecodeRune
- rangeValCopy
- unnamedResult
- whyNoLint
enable-all: true
godot: godot:
exclude: exclude:
# Exclude links. # Exclude links.
@@ -225,10 +240,6 @@ linters:
- linters: - linters:
- gosec - gosec
text: 'G402: TLS MinVersion too low.' text: 'G402: TLS MinVersion too low.'
paths:
- third_party$
- builtin$
- examples$
issues: issues:
max-issues-per-linter: 0 max-issues-per-linter: 0
max-same-issues: 0 max-same-issues: 0
@@ -245,7 +256,3 @@ formatters:
max-len: 120 max-len: 120
exclusions: exclusions:
generated: lax generated: lax
paths:
- third_party$
- builtin$
- examples$

View File

@@ -96,11 +96,11 @@ func (d *defaultAttrEncoder) Encode(iter Iterator) string {
for iter.Next() { for iter.Next() {
i, keyValue := iter.IndexedAttribute() i, keyValue := iter.IndexedAttribute()
if i > 0 { if i > 0 {
_, _ = buf.WriteRune(',') _ = buf.WriteByte(',')
} }
copyAndEscape(buf, string(keyValue.Key)) copyAndEscape(buf, string(keyValue.Key))
_, _ = buf.WriteRune('=') _ = buf.WriteByte('=')
if keyValue.Value.Type() == STRING { if keyValue.Value.Type() == STRING {
copyAndEscape(buf, keyValue.Value.AsString()) copyAndEscape(buf, keyValue.Value.AsString())
@@ -122,7 +122,7 @@ func copyAndEscape(buf *bytes.Buffer, val string) {
for _, ch := range val { for _, ch := range val {
switch ch { switch ch {
case '=', ',', escapeChar: case '=', ',', escapeChar:
_, _ = buf.WriteRune(escapeChar) _ = buf.WriteByte(escapeChar)
} }
_, _ = buf.WriteRune(ch) _, _ = buf.WriteRune(ch)
} }

View File

@@ -15,7 +15,7 @@ type Filter func(KeyValue) bool
// //
// If keys is empty a deny-all filter is returned. // If keys is empty a deny-all filter is returned.
func NewAllowKeysFilter(keys ...Key) Filter { func NewAllowKeysFilter(keys ...Key) Filter {
if len(keys) <= 0 { if len(keys) == 0 {
return func(kv KeyValue) bool { return false } return func(kv KeyValue) bool { return false }
} }
@@ -34,7 +34,7 @@ func NewAllowKeysFilter(keys ...Key) Filter {
// //
// If keys is empty an allow-all filter is returned. // If keys is empty an allow-all filter is returned.
func NewDenyKeysFilter(keys ...Key) Filter { func NewDenyKeysFilter(keys ...Key) Filter {
if len(keys) <= 0 { if len(keys) == 0 {
return func(kv KeyValue) bool { return true } return func(kv KeyValue) bool { return true }
} }

View File

@@ -812,7 +812,7 @@ var safeKeyCharset = [utf8.RuneSelf]bool{
// validateBaggageName checks if the string is a valid OpenTelemetry Baggage name. // validateBaggageName checks if the string is a valid OpenTelemetry Baggage name.
// Baggage name is a valid, non-empty UTF-8 string. // Baggage name is a valid, non-empty UTF-8 string.
func validateBaggageName(s string) bool { func validateBaggageName(s string) bool {
if len(s) == 0 { if s == "" {
return false return false
} }
@@ -828,7 +828,7 @@ func validateBaggageValue(s string) bool {
// validateKey checks if the string is a valid W3C Baggage key. // validateKey checks if the string is a valid W3C Baggage key.
func validateKey(s string) bool { func validateKey(s string) bool {
if len(s) == 0 { if s == "" {
return false return false
} }

View File

@@ -134,13 +134,11 @@ func TestOTelSpanContextToOC(t *testing.T) {
gotTraceState = strings.Join(gotTraceStateEntries, ",") gotTraceState = strings.Join(gotTraceStateEntries, ",")
} }
assert.Equal(t, expectedTraceState, gotTraceState, "Tracestate should preserve entries") assert.Equal(t, expectedTraceState, gotTraceState, "Tracestate should preserve entries")
} else { } else if got.Tracestate != nil {
// For empty tracestate cases, ensure the field is properly handled // For empty tracestate cases, ensure the field is properly handled
if got.Tracestate != nil {
entries := got.Tracestate.Entries() entries := got.Tracestate.Entries()
assert.Empty(t, entries, "Empty tracestate should result in empty entries") assert.Empty(t, entries, "Empty tracestate should result in empty entries")
} }
}
}) })
} }
} }

View File

@@ -135,7 +135,7 @@ var (
type testTextMapPropagator struct{} type testTextMapPropagator struct{}
func (t testTextMapPropagator) Inject(ctx context.Context, carrier propagation.TextMapCarrier) { func (t testTextMapPropagator) Inject(ctx context.Context, carrier propagation.TextMapCarrier) {
carrier.Set(testHeader, strings.Join([]string{traceID.String(), spanID.String()}, ":")) carrier.Set(testHeader, traceID.String()+":"+spanID.String())
// Test for panic // Test for panic
_ = carrier.Get("test") _ = carrier.Get("test")

View File

@@ -86,11 +86,12 @@ func newGRPCDialOptions(cfg config) []grpc.DialOption {
dialOpts = append(dialOpts, grpc.WithDefaultServiceConfig(cfg.serviceConfig.Value)) dialOpts = append(dialOpts, grpc.WithDefaultServiceConfig(cfg.serviceConfig.Value))
} }
// Prioritize GRPCCredentials over Insecure (passing both is an error). // Prioritize GRPCCredentials over Insecure (passing both is an error).
if cfg.gRPCCredentials.Value != nil { switch {
case cfg.gRPCCredentials.Value != nil:
dialOpts = append(dialOpts, grpc.WithTransportCredentials(cfg.gRPCCredentials.Value)) dialOpts = append(dialOpts, grpc.WithTransportCredentials(cfg.gRPCCredentials.Value))
} else if cfg.insecure.Value { case cfg.insecure.Value:
dialOpts = append(dialOpts, grpc.WithTransportCredentials(insecure.NewCredentials())) dialOpts = append(dialOpts, grpc.WithTransportCredentials(insecure.NewCredentials()))
} else { default:
// Default to using the host's root CA. // Default to using the host's root CA.
dialOpts = append(dialOpts, grpc.WithTransportCredentials( dialOpts = append(dialOpts, grpc.WithTransportCredentials(
credentials.NewTLS(nil), credentials.NewTLS(nil),

View File

@@ -563,7 +563,7 @@ func loadCertificates(certPath, keyPath string) ([]tls.Certificate, error) {
func insecureFromScheme(prev setting[bool], scheme string) setting[bool] { func insecureFromScheme(prev setting[bool], scheme string) setting[bool] {
if scheme == "https" { if scheme == "https" {
return newSetting(false) return newSetting(false)
} else if len(scheme) > 0 { } else if scheme != "" {
return newSetting(true) return newSetting(true)
} }

View File

@@ -525,11 +525,9 @@ func assertTLSConfig(t *testing.T, want, got setting[*tls.Config]) {
if want.Value.RootCAs == nil { if want.Value.RootCAs == nil {
assert.Nil(t, got.Value.RootCAs, "*tls.Config.RootCAs") assert.Nil(t, got.Value.RootCAs, "*tls.Config.RootCAs")
} else { } else if assert.NotNil(t, got.Value.RootCAs, "RootCAs") {
if assert.NotNil(t, got.Value.RootCAs, "RootCAs") {
assert.True(t, want.Value.RootCAs.Equal(got.Value.RootCAs), "RootCAs equal") assert.True(t, want.Value.RootCAs.Equal(got.Value.RootCAs), "RootCAs equal")
} }
}
assert.Equal(t, want.Value.Certificates, got.Value.Certificates, "Certificates") assert.Equal(t, want.Value.Certificates, got.Value.Certificates, "Certificates")
} }

View File

@@ -200,7 +200,7 @@ func (c *httpClient) uploadLogs(ctx context.Context, data []*logpb.ResourceLogs)
return err return err
} }
respStr := strings.TrimSpace(respData.String()) respStr := strings.TrimSpace(respData.String())
if len(respStr) == 0 { if respStr == "" {
respStr = "(empty)" respStr = "(empty)"
} }
bodyErr := fmt.Errorf("body: %s", respStr) bodyErr := fmt.Errorf("body: %s", respStr)
@@ -232,7 +232,7 @@ func (c *httpClient) newRequest(ctx context.Context, body []byte) (request, erro
switch c.compression { switch c.compression {
case NoCompression: case NoCompression:
r.ContentLength = (int64)(len(body)) r.ContentLength = int64(len(body))
req.bodyReader = bodyReader(body) req.bodyReader = bodyReader(body)
case GzipCompression: case GzipCompression:
// Ensure the content length is not used. // Ensure the content length is not used.

View File

@@ -460,11 +460,9 @@ func assertTLSConfig(t *testing.T, want, got setting[*tls.Config]) {
if want.Value.RootCAs == nil { if want.Value.RootCAs == nil {
assert.Nil(t, got.Value.RootCAs, "*tls.Config.RootCAs") assert.Nil(t, got.Value.RootCAs, "*tls.Config.RootCAs")
} else { } else if assert.NotNil(t, got.Value.RootCAs, "RootCAs") {
if assert.NotNil(t, got.Value.RootCAs, "RootCAs") {
assert.True(t, want.Value.RootCAs.Equal(got.Value.RootCAs), "RootCAs equal") assert.True(t, want.Value.RootCAs.Equal(got.Value.RootCAs), "RootCAs equal")
} }
}
assert.Equal(t, want.Value.Certificates, got.Value.Certificates, "Certificates") assert.Equal(t, want.Value.Certificates, got.Value.Certificates, "Certificates")
} }

View File

@@ -203,7 +203,7 @@ func (c *client) UploadMetrics(ctx context.Context, protoMetrics *metricpb.Resou
return err return err
} }
respStr := strings.TrimSpace(respData.String()) respStr := strings.TrimSpace(respData.String())
if len(respStr) == 0 { if respStr == "" {
respStr = "(empty)" respStr = "(empty)"
} }
bodyErr := fmt.Errorf("body: %s", respStr) bodyErr := fmt.Errorf("body: %s", respStr)
@@ -235,7 +235,7 @@ func (c *client) newRequest(ctx context.Context, body []byte) (request, error) {
switch c.compression { switch c.compression {
case NoCompression: case NoCompression:
r.ContentLength = (int64)(len(body)) r.ContentLength = int64(len(body))
req.bodyReader = bodyReader(body) req.bodyReader = bodyReader(body)
case GzipCompression: case GzipCompression:
// Ensure the content length is not used. // Ensure the content length is not used.

View File

@@ -209,7 +209,7 @@ func (d *client) UploadTraces(ctx context.Context, protoSpans []*tracepb.Resourc
return err return err
} }
respStr := strings.TrimSpace(respData.String()) respStr := strings.TrimSpace(respData.String())
if len(respStr) == 0 { if respStr == "" {
respStr = "(empty)" respStr = "(empty)"
} }
bodyErr := fmt.Errorf("body: %s", respStr) bodyErr := fmt.Errorf("body: %s", respStr)
@@ -230,7 +230,7 @@ func (d *client) UploadTraces(ctx context.Context, protoSpans []*tracepb.Resourc
func (d *client) newRequest(body []byte) (request, error) { func (d *client) newRequest(body []byte) (request, error) {
u := url.URL{Scheme: d.getScheme(), Host: d.cfg.Endpoint, Path: d.cfg.URLPath} u := url.URL{Scheme: d.getScheme(), Host: d.cfg.Endpoint, Path: d.cfg.URLPath}
r, err := http.NewRequest(http.MethodPost, u.String(), nil) r, err := http.NewRequest(http.MethodPost, u.String(), http.NoBody)
if err != nil { if err != nil {
return request{Request: r}, err return request{Request: r}, err
} }
@@ -246,7 +246,7 @@ func (d *client) newRequest(body []byte) (request, error) {
req := request{Request: r} req := request{Request: r}
switch Compression(d.cfg.Compression) { switch Compression(d.cfg.Compression) {
case NoCompression: case NoCompression:
r.ContentLength = (int64)(len(body)) r.ContentLength = int64(len(body))
req.bodyReader = bodyReader(body) req.bodyReader = bodyReader(body)
case GzipCompression: case GzipCompression:
// Ensure the content length is not used. // Ensure the content length is not used.

View File

@@ -640,8 +640,8 @@ func addExemplars[N int64 | float64](
for i, exemplar := range exemplars { for i, exemplar := range exemplars {
labels := attributesToLabels(exemplar.FilteredAttributes, labelNamer) labels := attributesToLabels(exemplar.FilteredAttributes, labelNamer)
// Overwrite any existing trace ID or span ID attributes // Overwrite any existing trace ID or span ID attributes
labels[otlptranslator.ExemplarTraceIDKey] = hex.EncodeToString(exemplar.TraceID[:]) labels[otlptranslator.ExemplarTraceIDKey] = hex.EncodeToString(exemplar.TraceID)
labels[otlptranslator.ExemplarSpanIDKey] = hex.EncodeToString(exemplar.SpanID[:]) labels[otlptranslator.ExemplarSpanIDKey] = hex.EncodeToString(exemplar.SpanID)
promExemplars[i] = prometheus.Exemplar{ promExemplars[i] = prometheus.Exemplar{
Value: float64(exemplar.Value), Value: float64(exemplar.Value),
Timestamp: exemplar.Time, Timestamp: exemplar.Time,

View File

@@ -150,11 +150,11 @@ func toZipkinAnnotations(events []tracesdk.Event) []zkmodel.Annotation {
func attributesToJSONMapString(attributes []attribute.KeyValue) string { func attributesToJSONMapString(attributes []attribute.KeyValue) string {
m := make(map[string]any, len(attributes)) m := make(map[string]any, len(attributes))
for _, a := range attributes { for _, a := range attributes {
m[(string)(a.Key)] = a.Value.AsInterface() m[string(a.Key)] = a.Value.AsInterface()
} }
// if an error happens, the result will be an empty string // if an error happens, the result will be an empty string
jsonBytes, _ := json.Marshal(m) jsonBytes, _ := json.Marshal(m)
return (string)(jsonBytes) return string(jsonBytes)
} }
// attributeToStringPair serializes each attribute to a string pair. // attributeToStringPair serializes each attribute to a string pair.
@@ -163,18 +163,18 @@ func attributeToStringPair(kv attribute.KeyValue) (string, string) {
// For slice attributes, serialize as JSON list string. // For slice attributes, serialize as JSON list string.
case attribute.BOOLSLICE: case attribute.BOOLSLICE:
data, _ := json.Marshal(kv.Value.AsBoolSlice()) data, _ := json.Marshal(kv.Value.AsBoolSlice())
return (string)(kv.Key), (string)(data) return string(kv.Key), string(data)
case attribute.INT64SLICE: case attribute.INT64SLICE:
data, _ := json.Marshal(kv.Value.AsInt64Slice()) data, _ := json.Marshal(kv.Value.AsInt64Slice())
return (string)(kv.Key), (string)(data) return string(kv.Key), string(data)
case attribute.FLOAT64SLICE: case attribute.FLOAT64SLICE:
data, _ := json.Marshal(kv.Value.AsFloat64Slice()) data, _ := json.Marshal(kv.Value.AsFloat64Slice())
return (string)(kv.Key), (string)(data) return string(kv.Key), string(data)
case attribute.STRINGSLICE: case attribute.STRINGSLICE:
data, _ := json.Marshal(kv.Value.AsStringSlice()) data, _ := json.Marshal(kv.Value.AsStringSlice())
return (string)(kv.Key), (string)(data) return string(kv.Key), string(data)
default: default:
return (string)(kv.Key), kv.Value.Emit() return string(kv.Key), kv.Value.Emit()
} }
} }

View File

@@ -146,7 +146,7 @@ func (e *Exporter) ExportSpans(ctx context.Context, spans []sdktrace.ReadOnlySpa
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
for k, v := range e.headers { for k, v := range e.headers {
if strings.ToLower(k) == "host" { if strings.EqualFold(k, "host") {
req.Host = v req.Host = v
} else { } else {
req.Header.Set(k, v) req.Header.Set(k, v)

View File

@@ -171,7 +171,7 @@ type logStore struct {
} }
func (s *logStore) Write(p []byte) (n int, err error) { func (s *logStore) Write(p []byte) (n int, err error) {
msg := (string)(p) msg := string(p)
if s.T != nil { if s.T != nil {
s.T.Logf("%s", msg) s.T.Logf("%s", msg)
} }

View File

@@ -91,7 +91,7 @@ func TestLogLevel(t *testing.T) {
func newBuffLogger(buf *bytes.Buffer, verbosity int) logr.Logger { func newBuffLogger(buf *bytes.Buffer, verbosity int) logr.Logger {
return funcr.New(func(prefix, args string) { return funcr.New(func(prefix, args string) {
_, _ = buf.Write([]byte(args)) _, _ = buf.WriteString(args)
}, funcr.Options{ }, funcr.Options{
Verbosity: verbosity, Verbosity: verbosity,
}) })

View File

@@ -124,7 +124,7 @@ func TestExtractValidBaggage(t *testing.T) {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
mapCarr := propagation.MapCarrier{} mapCarr := propagation.MapCarrier{}
mapCarr["baggage"] = tt.header mapCarr["baggage"] = tt.header
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil) req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody)
req.Header.Set("baggage", tt.header) req.Header.Set("baggage", tt.header)
// test with http header carrier (which implements ValuesGetter) // test with http header carrier (which implements ValuesGetter)
@@ -183,7 +183,7 @@ func TestExtractValidMultipleBaggageHeaders(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil) req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody)
req.Header["Baggage"] = tt.headers req.Header["Baggage"] = tt.headers
ctx := context.Background() ctx := context.Background()
@@ -239,7 +239,7 @@ func TestExtractInvalidDistributedContextFromHTTPReq(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil) req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody)
req.Header.Set("baggage", tt.header) req.Header.Set("baggage", tt.header)
expected := tt.has.Baggage(t) expected := tt.has.Baggage(t)
@@ -292,7 +292,7 @@ func TestInjectBaggageToHTTPReq(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil) req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody)
ctx := baggage.ContextWithBaggage(context.Background(), tt.mems.Baggage(t)) ctx := baggage.ContextWithBaggage(context.Background(), tt.mems.Baggage(t))
propagator.Inject(ctx, propagation.HeaderCarrier(req.Header)) propagator.Inject(ctx, propagation.HeaderCarrier(req.Header))
@@ -339,7 +339,7 @@ func TestBaggageInjectExtractRoundtrip(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
b := tt.mems.Baggage(t) b := tt.mems.Baggage(t)
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil) req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody)
ctx := baggage.ContextWithBaggage(context.Background(), b) ctx := baggage.ContextWithBaggage(context.Background(), b)
propagator.Inject(ctx, propagation.HeaderCarrier(req.Header)) propagator.Inject(ctx, propagation.HeaderCarrier(req.Header))

View File

@@ -56,7 +56,7 @@ func BenchmarkExtract(b *testing.B) {
func extractSubBenchmarks(b *testing.B, fn func(*testing.B, *http.Request)) { func extractSubBenchmarks(b *testing.B, fn func(*testing.B, *http.Request)) {
b.Run("Sampled", func(b *testing.B) { b.Run("Sampled", func(b *testing.B) {
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil) req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody)
req.Header.Set("traceparent", "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01") req.Header.Set("traceparent", "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
b.ReportAllocs() b.ReportAllocs()
@@ -64,14 +64,14 @@ func extractSubBenchmarks(b *testing.B, fn func(*testing.B, *http.Request)) {
}) })
b.Run("BogusVersion", func(b *testing.B) { b.Run("BogusVersion", func(b *testing.B) {
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil) req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody)
req.Header.Set("traceparent", "qw-00000000000000000000000000000000-0000000000000000-01") req.Header.Set("traceparent", "qw-00000000000000000000000000000000-0000000000000000-01")
b.ReportAllocs() b.ReportAllocs()
fn(b, req) fn(b, req)
}) })
b.Run("FutureAdditionalData", func(b *testing.B) { b.Run("FutureAdditionalData", func(b *testing.B) {
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil) req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody)
req.Header.Set("traceparent", "02-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-09-XYZxsf09") req.Header.Set("traceparent", "02-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-09-XYZxsf09")
b.ReportAllocs() b.ReportAllocs()
fn(b, req) fn(b, req)

View File

@@ -19,7 +19,7 @@ import (
// to the case-insensitive string value of "true" (i.e. "True" and "TRUE" // to the case-insensitive string value of "true" (i.e. "True" and "TRUE"
// will also enable this). // will also enable this).
var Resource = newFeature("RESOURCE", func(v string) (string, bool) { var Resource = newFeature("RESOURCE", func(v string) (string, bool) {
if strings.ToLower(v) == "true" { if strings.EqualFold(v, "true") {
return v, true return v, true
} }
return "", false return "", false

View File

@@ -15,9 +15,9 @@ import (
"go.opentelemetry.io/otel/log" "go.opentelemetry.io/otel/log"
) )
func verifyRing(t *testing.T, r *ring, N int, sum int) { func verifyRing(t *testing.T, r *ring, num int, sum int) {
// Length. // Length.
assert.Equal(t, N, r.Len(), "r.Len()") assert.Equal(t, num, r.Len(), "r.Len()")
// Iteration. // Iteration.
var n, s int var n, s int
@@ -28,7 +28,7 @@ func verifyRing(t *testing.T, r *ring, N int, sum int) {
s += int(body.AsInt64()) s += int(body.AsInt64())
} }
}) })
assert.Equal(t, N, n, "number of forward iterations") assert.Equal(t, num, n, "number of forward iterations")
if sum >= 0 { if sum >= 0 {
assert.Equal(t, sum, s, "forward ring sum") assert.Equal(t, sum, s, "forward ring sum")
} }

View File

@@ -125,14 +125,12 @@ func (r *FixedSizeReservoir) Offer(ctx context.Context, t time.Time, n Value, a
if int(r.count) < cap(r.store) { if int(r.count) < cap(r.store) {
r.store[r.count] = newMeasurement(ctx, t, n, a) r.store[r.count] = newMeasurement(ctx, t, n, a)
} else { } else if r.count == r.next {
if r.count == r.next {
// Overwrite a random existing measurement with the one offered. // Overwrite a random existing measurement with the one offered.
idx := int(rand.Int64N(int64(cap(r.store)))) idx := int(rand.Int64N(int64(cap(r.store))))
r.store[idx] = newMeasurement(ctx, t, n, a) r.store[idx] = newMeasurement(ctx, t, n, a)
r.advance() r.advance()
} }
}
r.count++ r.count++
} }

View File

@@ -183,8 +183,8 @@ func (p *expoHistogramDataPoint[N]) scaleChange(bin, startBin int32, length int)
var count int32 var count int32
for high-low >= p.maxSize { for high-low >= p.maxSize {
low = low >> 1 low >>= 1
high = high >> 1 high >>= 1
count++ count++
if count > expoMaxScale-expoMinScale { if count > expoMaxScale-expoMinScale {
return count return count
@@ -225,7 +225,7 @@ func (b *expoBuckets) record(bin int32) {
b.counts = append(b.counts, make([]uint64, newLength-len(b.counts))...) b.counts = append(b.counts, make([]uint64, newLength-len(b.counts))...)
} }
copy(b.counts[shift:origLen+int(shift)], b.counts[:]) copy(b.counts[shift:origLen+int(shift)], b.counts)
b.counts = b.counts[:newLength] b.counts = b.counts[:newLength]
for i := 1; i < int(shift); i++ { for i := 1; i < int(shift); i++ {
b.counts[i] = 0 b.counts[i] = 0
@@ -264,7 +264,7 @@ func (b *expoBuckets) downscale(delta int32) {
// new Counts: [4, 14, 30, 10] // new Counts: [4, 14, 30, 10]
if len(b.counts) <= 1 || delta < 1 { if len(b.counts) <= 1 || delta < 1 {
b.startBin = b.startBin >> delta b.startBin >>= delta
return return
} }
@@ -282,7 +282,7 @@ func (b *expoBuckets) downscale(delta int32) {
lastIdx := (len(b.counts) - 1 + int(offset)) / int(steps) lastIdx := (len(b.counts) - 1 + int(offset)) / int(steps)
b.counts = b.counts[:lastIdx+1] b.counts = b.counts[:lastIdx+1]
b.startBin = b.startBin >> delta b.startBin >>= delta
} }
// newExponentialHistogram returns an Aggregator that summarizes a set of // newExponentialHistogram returns an Aggregator that summarizes a set of

View File

@@ -656,7 +656,7 @@ func BenchmarkPrepend(b *testing.B) {
n := math.MaxFloat64 n := math.MaxFloat64
for range 1024 { for range 1024 {
agg.record(n) agg.record(n)
n = n / 2 n /= 2
} }
} }
} }
@@ -667,7 +667,7 @@ func BenchmarkAppend(b *testing.B) {
n := smallestNonZeroNormalFloat64 n := smallestNonZeroNormalFloat64
for range 1024 { for range 1024 {
agg.record(n) agg.record(n)
n = n * 2 n *= 2
} }
} }
} }
@@ -1061,7 +1061,7 @@ func FuzzGetBin(f *testing.F) {
f.Fuzz(func(t *testing.T, v float64, scale int32) { f.Fuzz(func(t *testing.T, v float64, scale int32) {
// GetBin only works on positive values. // GetBin only works on positive values.
if math.Signbit(v) { if math.Signbit(v) {
v = v * -1 v *= -1
} }
// GetBin Doesn't work on zero. // GetBin Doesn't work on zero.
if v == 0.0 { if v == 0.0 {

View File

@@ -423,7 +423,7 @@ func (m *meter) Float64ObservableGauge(
} }
func validateInstrumentName(name string) error { func validateInstrumentName(name string) error {
if len(name) == 0 { if name == "" {
return fmt.Errorf("%w: %s: is empty", ErrInstrumentName, name) return fmt.Errorf("%w: %s: is empty", ErrInstrumentName, name)
} }
if len(name) > 255 { if len(name) > 255 {

View File

@@ -653,26 +653,25 @@ func TestPipelineProduceErrors(t *testing.T) {
var shouldReturnError bool // When true, the third callback returns an error var shouldReturnError bool // When true, the third callback returns an error
var callbackCounts [3]int var callbackCounts [3]int
pipe.callbacks = append(pipe.callbacks,
// Callback 1: cancels the context during execution but continues to populate data // Callback 1: cancels the context during execution but continues to populate data
pipe.callbacks = append(pipe.callbacks, func(ctx context.Context) error { func(ctx context.Context) error {
callbackCounts[0]++ callbackCounts[0]++
for _, m := range pipe.int64Measures[testObsID] { for _, m := range pipe.int64Measures[testObsID] {
m(ctx, 123, *attribute.EmptySet()) m(ctx, 123, *attribute.EmptySet())
} }
return nil return nil
}) },
// Callback 2: populates int64 observable data // Callback 2: populates int64 observable data
pipe.callbacks = append(pipe.callbacks, func(ctx context.Context) error { func(ctx context.Context) error {
callbackCounts[1]++ callbackCounts[1]++
if shouldCancelContext { if shouldCancelContext {
cancelCtx() cancelCtx()
} }
return nil return nil
}) },
// Callback 3: return an error // Callback 3: return an error
pipe.callbacks = append(pipe.callbacks, func(ctx context.Context) error { func(ctx context.Context) error {
callbackCounts[2]++ callbackCounts[2]++
if shouldReturnError { if shouldReturnError {
return fmt.Errorf("test callback error") return fmt.Errorf("test callback error")

View File

@@ -68,7 +68,7 @@ func parseOSReleaseFile(file io.Reader) map[string]string {
func skip(line string) bool { func skip(line string) bool {
line = strings.TrimSpace(line) line = strings.TrimSpace(line)
return len(line) == 0 || strings.HasPrefix(line, "#") return line == "" || strings.HasPrefix(line, "#")
} }
// parse attempts to split the provided line on the first '=' character, and then // parse attempts to split the provided line on the first '=' character, and then
@@ -76,7 +76,7 @@ func skip(line string) bool {
func parse(line string) (string, string, bool) { func parse(line string) (string, string, bool) {
k, v, found := strings.Cut(line, "=") k, v, found := strings.Cut(line, "=")
if !found || len(k) == 0 { if !found || k == "" {
return "", "", false return "", "", false
} }

View File

@@ -505,7 +505,7 @@ func TestBatchSpanProcessorDropBatchIfFailed(t *testing.T) {
func assertMaxSpanDiff(t *testing.T, want, got, maxDif int) { func assertMaxSpanDiff(t *testing.T, want, got, maxDif int) {
spanDifference := want - got spanDifference := want - got
if spanDifference < 0 { if spanDifference < 0 {
spanDifference = spanDifference * -1 spanDifference *= -1
} }
if spanDifference > maxDif { if spanDifference > maxDif {
t.Errorf("number of exported span not equal to or within %d less than: got %+v, want %+v\n", t.Errorf("number of exported span not equal to or within %d less than: got %+v, want %+v\n",
@@ -514,7 +514,7 @@ func assertMaxSpanDiff(t *testing.T, want, got, maxDif int) {
} }
type indefiniteExporter struct { type indefiniteExporter struct {
stop chan (struct{}) stop chan struct{}
} }
func newIndefiniteExporter(t *testing.T) indefiniteExporter { func newIndefiniteExporter(t *testing.T) indefiniteExporter {

View File

@@ -16,7 +16,7 @@ import (
// to the case-insensitive string value of "true" (i.e. "True" and "TRUE" // to the case-insensitive string value of "true" (i.e. "True" and "TRUE"
// will also enable this). // will also enable this).
var SelfObservability = newFeature("SELF_OBSERVABILITY", func(v string) (string, bool) { var SelfObservability = newFeature("SELF_OBSERVABILITY", func(v string) (string, bool) {
if strings.ToLower(v) == "true" { if strings.EqualFold(v, "true") {
return v, true return v, true
} }
return "", false return "", false

View File

@@ -92,13 +92,14 @@ func (tr *tracer) Start(
// Determine the sampling result and create the corresponding attribute. // Determine the sampling result and create the corresponding attribute.
var attrSamplingResult attribute.KeyValue var attrSamplingResult attribute.KeyValue
if s.SpanContext().IsSampled() && s.IsRecording() { switch {
case s.SpanContext().IsSampled() && s.IsRecording():
attrSamplingResult = tr.spanStartedMetric.AttrSpanSamplingResult( attrSamplingResult = tr.spanStartedMetric.AttrSpanSamplingResult(
otelconv.SpanSamplingResultRecordAndSample, otelconv.SpanSamplingResultRecordAndSample,
) )
} else if s.IsRecording() { case s.IsRecording():
attrSamplingResult = tr.spanStartedMetric.AttrSpanSamplingResult(otelconv.SpanSamplingResultRecordOnly) attrSamplingResult = tr.spanStartedMetric.AttrSpanSamplingResult(otelconv.SpanSamplingResultRecordOnly)
} else { default:
attrSamplingResult = tr.spanStartedMetric.AttrSpanSamplingResult(otelconv.SpanSamplingResultDrop) attrSamplingResult = tr.spanStartedMetric.AttrSpanSamplingResult(otelconv.SpanSamplingResultDrop)
} }

View File

@@ -1008,7 +1008,7 @@ func kvStr(kvs []attribute.KeyValue) string {
if idx > 0 { if idx > 0 {
_, _ = sb.WriteString(", ") _, _ = sb.WriteString(", ")
} }
_, _ = sb.WriteString((string)(attr.Key)) _, _ = sb.WriteString(string(attr.Key))
_, _ = sb.WriteString(": ") _, _ = sb.WriteString(": ")
_, _ = sb.WriteString(attr.Value.Emit()) _, _ = sb.WriteString(attr.Value.Emit())
} }

View File

@@ -91,8 +91,7 @@ func (c *HTTPConv) ClientRequest(req *http.Request) []attribute.KeyValue {
} }
attrs := make([]attribute.KeyValue, 0, n) attrs := make([]attribute.KeyValue, 0, n)
attrs = append(attrs, c.method(req.Method)) attrs = append(attrs, c.method(req.Method), c.proto(req.Proto))
attrs = append(attrs, c.proto(req.Proto))
var u string var u string
if req.URL != nil { if req.URL != nil {
@@ -103,9 +102,11 @@ func (c *HTTPConv) ClientRequest(req *http.Request) []attribute.KeyValue {
// Restore any username/password info that was removed. // Restore any username/password info that was removed.
req.URL.User = userinfo req.URL.User = userinfo
} }
attrs = append(attrs, c.HTTPURLKey.String(u)) attrs = append(
attrs,
attrs = append(attrs, c.NetConv.PeerName(peer)) c.HTTPURLKey.String(u),
c.NetConv.PeerName(peer),
)
if port > 0 { if port > 0 {
attrs = append(attrs, c.NetConv.PeerPort(port)) attrs = append(attrs, c.NetConv.PeerPort(port))
} }
@@ -191,10 +192,13 @@ func (c *HTTPConv) ServerRequest(server string, req *http.Request) []attribute.K
} }
attrs := make([]attribute.KeyValue, 0, n) attrs := make([]attribute.KeyValue, 0, n)
attrs = append(attrs, c.method(req.Method)) attrs = append(
attrs = append(attrs, c.scheme(req.TLS != nil)) attrs,
attrs = append(attrs, c.proto(req.Proto)) c.method(req.Method),
attrs = append(attrs, c.NetConv.HostName(host)) c.scheme(req.TLS != nil),
c.proto(req.Proto),
c.NetConv.HostName(host),
)
if hostPort > 0 { if hostPort > 0 {
attrs = append(attrs, c.NetConv.HostPort(hostPort)) attrs = append(attrs, c.NetConv.HostPort(hostPort))

View File

@@ -91,8 +91,7 @@ func (c *HTTPConv) ClientRequest(req *http.Request) []attribute.KeyValue {
} }
attrs := make([]attribute.KeyValue, 0, n) attrs := make([]attribute.KeyValue, 0, n)
attrs = append(attrs, c.method(req.Method)) attrs = append(attrs, c.method(req.Method), c.proto(req.Proto))
attrs = append(attrs, c.proto(req.Proto))
var u string var u string
if req.URL != nil { if req.URL != nil {
@@ -103,9 +102,11 @@ func (c *HTTPConv) ClientRequest(req *http.Request) []attribute.KeyValue {
// Restore any username/password info that was removed. // Restore any username/password info that was removed.
req.URL.User = userinfo req.URL.User = userinfo
} }
attrs = append(attrs, c.HTTPURLKey.String(u)) attrs = append(
attrs,
attrs = append(attrs, c.NetConv.PeerName(peer)) c.HTTPURLKey.String(u),
c.NetConv.PeerName(peer),
)
if port > 0 { if port > 0 {
attrs = append(attrs, c.NetConv.PeerPort(port)) attrs = append(attrs, c.NetConv.PeerPort(port))
} }
@@ -191,10 +192,13 @@ func (c *HTTPConv) ServerRequest(server string, req *http.Request) []attribute.K
} }
attrs := make([]attribute.KeyValue, 0, n) attrs := make([]attribute.KeyValue, 0, n)
attrs = append(attrs, c.method(req.Method)) attrs = append(
attrs = append(attrs, c.scheme(req.TLS != nil)) attrs,
attrs = append(attrs, c.proto(req.Proto)) c.method(req.Method),
attrs = append(attrs, c.NetConv.HostName(host)) c.scheme(req.TLS != nil),
c.proto(req.Proto),
c.NetConv.HostName(host),
)
if hostPort > 0 { if hostPort > 0 {
attrs = append(attrs, c.NetConv.HostPort(hostPort)) attrs = append(attrs, c.NetConv.HostPort(hostPort))

View File

@@ -92,8 +92,7 @@ func (c *HTTPConv) ClientRequest(req *http.Request) []attribute.KeyValue {
} }
attrs := make([]attribute.KeyValue, 0, n) attrs := make([]attribute.KeyValue, 0, n)
attrs = append(attrs, c.method(req.Method)) attrs = append(attrs, c.method(req.Method), c.proto(req.Proto))
attrs = append(attrs, c.proto(req.Proto))
var u string var u string
if req.URL != nil { if req.URL != nil {
@@ -104,9 +103,11 @@ func (c *HTTPConv) ClientRequest(req *http.Request) []attribute.KeyValue {
// Restore any username/password info that was removed. // Restore any username/password info that was removed.
req.URL.User = userinfo req.URL.User = userinfo
} }
attrs = append(attrs, c.HTTPURLKey.String(u)) attrs = append(
attrs,
attrs = append(attrs, c.NetConv.PeerName(peer)) c.HTTPURLKey.String(u),
c.NetConv.PeerName(peer),
)
if port > 0 { if port > 0 {
attrs = append(attrs, c.NetConv.PeerPort(port)) attrs = append(attrs, c.NetConv.PeerPort(port))
} }
@@ -192,10 +193,13 @@ func (c *HTTPConv) ServerRequest(server string, req *http.Request) []attribute.K
} }
attrs := make([]attribute.KeyValue, 0, n) attrs := make([]attribute.KeyValue, 0, n)
attrs = append(attrs, c.method(req.Method)) attrs = append(
attrs = append(attrs, c.scheme(req.TLS != nil)) attrs,
attrs = append(attrs, c.proto(req.Proto)) c.method(req.Method),
attrs = append(attrs, c.NetConv.HostName(host)) c.scheme(req.TLS != nil),
c.proto(req.Proto),
c.NetConv.HostName(host),
)
if hostPort > 0 { if hostPort > 0 {
attrs = append(attrs, c.NetConv.HostPort(hostPort)) attrs = append(attrs, c.NetConv.HostPort(hostPort))

View File

@@ -165,7 +165,7 @@ func (tf TraceFlags) MarshalJSON() ([]byte, error) {
// String returns the hex string representation form of TraceFlags. // String returns the hex string representation form of TraceFlags.
func (tf TraceFlags) String() string { func (tf TraceFlags) String() string {
return hex.EncodeToString([]byte{byte(tf)}[:]) return hex.EncodeToString([]byte{byte(tf)})
} }
// SpanContextConfig contains mutable fields usable for constructing // SpanContextConfig contains mutable fields usable for constructing

View File

@@ -80,7 +80,7 @@ func checkKeyRemain(key string) bool {
// //
// param n is remain part length, should be 255 in simple-key or 13 in system-id. // param n is remain part length, should be 255 in simple-key or 13 in system-id.
func checkKeyPart(key string, n int) bool { func checkKeyPart(key string, n int) bool {
if len(key) == 0 { if key == "" {
return false return false
} }
first := key[0] // key's first char first := key[0] // key's first char
@@ -102,7 +102,7 @@ func isAlphaNum(c byte) bool {
// //
// param n is remain part length, should be 240 exactly. // param n is remain part length, should be 240 exactly.
func checkKeyTenant(key string, n int) bool { func checkKeyTenant(key string, n int) bool {
if len(key) == 0 { if key == "" {
return false return false
} }
return isAlphaNum(key[0]) && len(key[1:]) <= n && checkKeyRemain(key[1:]) return isAlphaNum(key[0]) && len(key[1:]) <= n && checkKeyRemain(key[1:])
@@ -191,7 +191,7 @@ func ParseTraceState(ts string) (TraceState, error) {
for ts != "" { for ts != "" {
var memberStr string var memberStr string
memberStr, ts, _ = strings.Cut(ts, listDelimiters) memberStr, ts, _ = strings.Cut(ts, listDelimiters)
if len(memberStr) == 0 { if memberStr == "" {
continue continue
} }