Debian Codegraph @

sdk/metric/internal/x/x.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Package x contains support for OTel metric SDK experimental features.
5 //
6 // This package should only be used for features defined in the specification.
7 // It should not be used for experiments or new project ideas.
8 package x // import "go.opentelemetry.io/otel/sdk/metric/internal/x"
9
10 import (
11 "os"
12 )
13
14 // Feature is an experimental feature control flag. It provides a uniform way
15 // to interact with these feature flags and parse their values.
16 type Feature[T any] struct {
17 key string
18 parse func(v string) (T, bool)
19 }
20
21 //nolint:unused
22 func newFeature[T any](suffix string, parse func(string) (T, bool)) Feature[T] {
23 const envKeyRoot = "OTEL_GO_X_"
24 return Feature[T]{
25 key: envKeyRoot + suffix,
26 parse: parse,
27 }
28 }
29
30 // Key returns the environment variable key that needs to be set to enable the
31 // feature.
32 func (f Feature[T]) Key() string { return f.key }
33
34 // Lookup returns the user configured value for the feature and true if the
35 // user has enabled the feature. Otherwise, if the feature is not enabled, a
36 // zero-value and false are returned.
37 func (f Feature[T]) Lookup() (v T, ok bool) {
38 // https://github.com/open-telemetry/opentelemetry-specification/blob/62effed618589a0bec416a87e559c0a9d96289bb/specification/configuration/sdk-environment-variables.md#parsing-empty-value
39 //
40 // > The SDK MUST interpret an empty value of an environment variable the
41 // > same way as when the variable is unset.
42 vRaw := os.Getenv(f.key)
43 if vRaw == "" {
44 return v, ok
45 }
46 return f.parse(vRaw)
47 }
48
49 // Enabled reports whether the feature is enabled.
50 func (f Feature[T]) Enabled() bool {
51 _, ok := f.Lookup()
52 return ok
53 }