Debian Codegraph @

sdk/metric/config_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package metric
5
6 import (
7 "context"
8 "errors"
9 "testing"
10
11 "github.com/google/go-cmp/cmp"
12 "github.com/stretchr/testify/assert"
13 "github.com/stretchr/testify/require"
14
15 "go.opentelemetry.io/otel/attribute"
16 "go.opentelemetry.io/otel/sdk/metric/exemplar"
17 "go.opentelemetry.io/otel/sdk/metric/metricdata"
18 "go.opentelemetry.io/otel/sdk/resource"
19 "go.opentelemetry.io/otel/trace"
20 )
21
22 type reader struct {
23 producer sdkProducer
24 externalProducers []Producer
25 temporalityFunc TemporalitySelector
26 aggregationFunc AggregationSelector
27 cardinalityLimitSelector CardinalityLimitSelector
28 collectFunc func(context.Context, *metricdata.ResourceMetrics) error
29 forceFlushFunc func(context.Context) error
30 shutdownFunc func(context.Context) error
31 }
32
33 const envVarResourceAttributes = "OTEL_RESOURCE_ATTRIBUTES"
34
35 var _ Reader = (*reader)(nil)
36
37 func (r *reader) aggregation(
38 kind InstrumentKind,
39 ) Aggregation { // nolint:revive // import-shadow for method scoped by type.
40 return r.aggregationFunc(kind)
41 }
42
43 func (r *reader) register(p sdkProducer) { r.producer = p }
44 func (r *reader) RegisterProducer(p Producer) { r.externalProducers = append(r.externalProducers, p) }
45 func (r *reader) temporality(kind InstrumentKind) metricdata.Temporality {
46 return r.temporalityFunc(kind)
47 }
48
49 func (r *reader) cardinalityLimit(kind InstrumentKind) (int, bool) {
50 if r.cardinalityLimitSelector != nil {
51 return r.cardinalityLimitSelector(kind)
52 }
53 return 0, true
54 }
55
56 func (r *reader) Collect(ctx context.Context, rm *metricdata.ResourceMetrics) error {
57 return r.collectFunc(ctx, rm)
58 }
59 func (r *reader) ForceFlush(ctx context.Context) error { return r.forceFlushFunc(ctx) }
60 func (r *reader) Shutdown(ctx context.Context) error { return r.shutdownFunc(ctx) }
61
62 func TestConfigReaderSignalsEmpty(t *testing.T) {
63 f, s := config{}.readerSignals()
64
65 require.NotNil(t, f)
66 require.NotNil(t, s)
67
68 ctx := t.Context()
69 assert.NoError(t, f(ctx))
70 assert.NoError(t, s(ctx))
71 assert.ErrorIs(t, s(ctx), ErrReaderShutdown)
72 }
73
74 func TestConfigReaderSignalsForwarded(t *testing.T) {
75 var flush, sdown int
76 r := &reader{
77 forceFlushFunc: func(context.Context) error {
78 flush++
79 return nil
80 },
81 shutdownFunc: func(context.Context) error {
82 sdown++
83 return nil
84 },
85 }
86 c := newConfig([]Option{WithReader(r)})
87 f, s := c.readerSignals()
88
89 require.NotNil(t, f)
90 require.NotNil(t, s)
91
92 ctx := t.Context()
93 assert.NoError(t, f(ctx))
94 assert.NoError(t, f(ctx))
95 assert.NoError(t, s(ctx))
96 assert.ErrorIs(t, s(ctx), ErrReaderShutdown)
97
98 assert.Equal(t, 2, flush, "flush not called 2 times")
99 assert.Equal(t, 1, sdown, "shutdown not called 1 time")
100 }
101
102 func TestConfigReaderSignalsForwardedErrors(t *testing.T) {
103 r := &reader{
104 forceFlushFunc: func(context.Context) error { return assert.AnError },
105 shutdownFunc: func(context.Context) error { return assert.AnError },
106 }
107 c := newConfig([]Option{WithReader(r)})
108 f, s := c.readerSignals()
109
110 require.NotNil(t, f)
111 require.NotNil(t, s)
112
113 ctx := t.Context()
114 assert.ErrorIs(t, f(ctx), assert.AnError)
115 assert.ErrorIs(t, s(ctx), assert.AnError)
116 assert.ErrorIs(t, s(ctx), ErrReaderShutdown)
117 }
118
119 func TestUnifyMultiError(t *testing.T) {
120 var (
121 e0 = errors.New("0")
122 e1 = errors.New("1")
123 e2 = errors.New("2")
124 )
125 err := unify([]func(context.Context) error{
126 func(context.Context) error { return e0 },
127 func(context.Context) error { return e1 },
128 func(context.Context) error { return e2 },
129 })(t.Context())
130 assert.ErrorIs(t, err, e0)
131 assert.ErrorIs(t, err, e1)
132 assert.ErrorIs(t, err, e2)
133 }
134
135 func mergeResource(t *testing.T, r1, r2 *resource.Resource) *resource.Resource {
136 r, err := resource.Merge(r1, r2)
137 assert.NoError(t, err)
138 return r
139 }
140
141 func TestWithResource(t *testing.T) {
142 t.Setenv(envVarResourceAttributes, "key=value,rk5=7")
143
144 cases := []struct {
145 name string
146 options []Option
147 want *resource.Resource
148 msg string
149 }{
150 {
151 name: "explicitly empty resource",
152 options: []Option{WithResource(resource.Empty())},
153 want: resource.Environment(),
154 },
155 {
156 name: "uses default if no resource option",
157 options: []Option{},
158 want: resource.Default(),
159 },
160 {
161 name: "explicit resource",
162 options: []Option{
163 WithResource(resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk2", 5))),
164 },
165 want: mergeResource(
166 t,
167 resource.Environment(),
168 resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk2", 5)),
169 ),
170 },
171 {
172 name: "last resource wins",
173 options: []Option{
174 WithResource(resource.NewSchemaless(attribute.String("rk1", "vk1"), attribute.Int64("rk2", 5))),
175 WithResource(resource.NewSchemaless(attribute.String("rk3", "rv3"), attribute.Int64("rk4", 10))),
176 },
177 want: mergeResource(
178 t,
179 resource.Environment(),
180 resource.NewSchemaless(attribute.String("rk3", "rv3"), attribute.Int64("rk4", 10)),
181 ),
182 },
183 {
184 name: "overlapping attributes with environment resource",
185 options: []Option{
186 WithResource(resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk5", 10))),
187 },
188 want: mergeResource(
189 t,
190 resource.Environment(),
191 resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk5", 10)),
192 ),
193 },
194 }
195 for _, tc := range cases {
196 t.Run(tc.name, func(t *testing.T) {
197 got := newConfig(tc.options).res
198 if diff := cmp.Diff(got, tc.want); diff != "" {
199 t.Errorf("WithResource:\n -got +want %s", diff)
200 }
201 })
202 }
203 }
204
205 func TestWithReader(t *testing.T) {
206 r := &reader{}
207 c := newConfig([]Option{WithReader(r)})
208 require.Len(t, c.readers, 1)
209 assert.Same(t, r, c.readers[0])
210 }
211
212 func TestWithView(t *testing.T) {
213 c := newConfig([]Option{WithView(
214 NewView(
215 Instrument{Kind: InstrumentKindObservableCounter},
216 Stream{Name: "a"},
217 ),
218 NewView(
219 Instrument{Kind: InstrumentKindCounter},
220 Stream{Name: "b"},
221 ),
222 )})
223 assert.Len(t, c.views, 2)
224 }
225
226 func TestWithExemplarFilterOff(t *testing.T) {
227 for _, tc := range []struct {
228 desc string
229 opts []Option
230 env string
231 expectFilterSampled bool
232 expectFilterNotSampled bool
233 }{
234 {
235 desc: "default",
236 expectFilterSampled: true,
237 expectFilterNotSampled: false,
238 },
239 {
240 desc: "always on option",
241 opts: []Option{WithExemplarFilter(exemplar.AlwaysOnFilter)},
242 expectFilterSampled: true,
243 expectFilterNotSampled: true,
244 },
245 {
246 desc: "always off option",
247 opts: []Option{WithExemplarFilter(exemplar.AlwaysOffFilter)},
248 expectFilterSampled: false,
249 expectFilterNotSampled: false,
250 },
251 {
252 desc: "trace based option",
253 opts: []Option{WithExemplarFilter(exemplar.TraceBasedFilter)},
254 expectFilterSampled: true,
255 expectFilterNotSampled: false,
256 },
257 {
258 desc: "last option takes precedence",
259 opts: []Option{
260 WithExemplarFilter(exemplar.AlwaysOffFilter),
261 WithExemplarFilter(exemplar.AlwaysOnFilter),
262 },
263 expectFilterSampled: true,
264 expectFilterNotSampled: true,
265 },
266 {
267 desc: "always_off env",
268 env: "always_off",
269 expectFilterSampled: false,
270 expectFilterNotSampled: false,
271 },
272 {
273 desc: "always_on env",
274 env: "always_on",
275 expectFilterSampled: true,
276 expectFilterNotSampled: true,
277 },
278 {
279 desc: "always_on case insensitiveenv",
280 env: "ALWAYS_ON",
281 expectFilterSampled: true,
282 expectFilterNotSampled: true,
283 },
284 {
285 desc: "trace_based env",
286 env: "trace_based",
287 expectFilterSampled: true,
288 expectFilterNotSampled: false,
289 },
290 {
291 desc: "wrong env",
292 env: "foo_bar",
293 expectFilterSampled: true,
294 expectFilterNotSampled: false,
295 },
296 {
297 desc: "option takes precedence over env var",
298 env: "always_off",
299 opts: []Option{WithExemplarFilter(exemplar.AlwaysOnFilter)},
300 expectFilterSampled: true,
301 expectFilterNotSampled: true,
302 },
303 } {
304 t.Run(tc.desc, func(t *testing.T) {
305 if tc.env != "" {
306 t.Setenv("OTEL_METRICS_EXEMPLAR_FILTER", tc.env)
307 }
308 c := newConfig(tc.opts)
309 assert.NotNil(t, c.exemplarFilter)
310 assert.Equal(t, tc.expectFilterNotSampled, c.exemplarFilter(t.Context()))
311 assert.Equal(t, tc.expectFilterSampled, c.exemplarFilter(sample(t.Context())))
312 })
313 }
314 }
315
316 func TestWithCardinalityLimit(t *testing.T) {
317 cases := []struct {
318 name string
319 envValue string
320 options []Option
321 expectedLimit int
322 }{
323 {
324 name: "only cardinality limit from option",
325 envValue: "",
326 options: []Option{WithCardinalityLimit(1000)},
327 expectedLimit: 1000,
328 },
329 {
330 name: "cardinality limit from option overrides env",
331 envValue: "500",
332 options: []Option{WithCardinalityLimit(1000)},
333 expectedLimit: 1000,
334 },
335 {
336 name: "cardinality limit from env",
337 envValue: "1234",
338 options: []Option{},
339 expectedLimit: 1234,
340 },
341 {
342 name: "invalid env value uses default",
343 envValue: "not-a-number",
344 options: []Option{},
345 expectedLimit: defaultCardinalityLimit,
346 },
347 {
348 name: "empty env and no option uses default",
349 envValue: "",
350 options: []Option{},
351 expectedLimit: defaultCardinalityLimit,
352 },
353 }
354
355 for _, tc := range cases {
356 t.Run(tc.name, func(t *testing.T) {
357 t.Setenv("OTEL_GO_X_CARDINALITY_LIMIT", tc.envValue)
358 c := newConfig(tc.options)
359 assert.Equal(t, tc.expectedLimit, c.cardinalityLimit)
360 })
361 }
362 }
363
364 func sample(parent context.Context) context.Context {
365 sc := trace.NewSpanContext(trace.SpanContextConfig{
366 TraceID: trace.TraceID{0x01},
367 SpanID: trace.SpanID{0x01},
368 TraceFlags: trace.FlagsSampled,
369 })
370 return trace.ContextWithSpanContext(parent, sc)
371 }