Debian Codegraph @

confmap/provider_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package confmap
5
6 import (
7 "context"
8 "errors"
9 "fmt"
10 "testing"
11 "time"
12
13 "github.com/stretchr/testify/assert"
14 "github.com/stretchr/testify/require"
15 )
16
17 // This is an example of a provider that calls a provided WatcherFunc to update configuration dynamically every second.
18 // The example is useful for implementing Providers of configuration that changes over time.
19 type UpdatingProvider struct{}
20
21 func (p UpdatingProvider) getCurrentConfig(_ string) any {
22 return "hello"
23 }
24
25 func (p UpdatingProvider) Retrieve(ctx context.Context, uri string, watcher WatcherFunc) (*Retrieved, error) {
26 ticker := time.NewTicker(1 * time.Second)
27 stop := make(chan bool, 1)
28
29 retrieved, err := NewRetrieved(p.getCurrentConfig(uri), WithRetrievedClose(func(_ context.Context) error {
30 // the retriever should call this function when it no longer wants config updates
31 ticker.Stop()
32 stop <- true
33 return nil
34 }))
35 if err != nil {
36 return nil, err
37 }
38 // it's necessary to start a go function that can notify the caller of changes asynchronously
39 go func() {
40 for {
41 select {
42 case <-ctx.Done():
43 // if the context is closed, then we should stop sending updates
44 ticker.Stop()
45 return
46 case <-stop:
47 // closeFunc was called, so stop updating the watcher
48 return
49 case <-ticker.C:
50 // the configuration has "changed". Notify the watcher that a new config is available
51 // the watcher is expected to call Provider.Retrieve again to get the update
52 // note that the collector calls closeFunc before calling Retrieve for the second time,
53 // so these go functions don't accumulate indefinitely. (see otelcol/collector.go, Collector.reloadConfiguration)
54 watcher(&ChangeEvent{})
55 }
56 }
57 }()
58
59 return retrieved, nil
60 }
61
62 func ExampleProvider() {
63 provider := UpdatingProvider{}
64
65 receivedNotification := make(chan bool)
66
67 watcherFunc := func(_ *ChangeEvent) {
68 fmt.Println("received notification of new config")
69 receivedNotification <- true
70 }
71
72 retrieved, err := provider.Retrieve(context.Background(), "example", watcherFunc)
73 if err != nil {
74 fmt.Println("received an error")
75 } else {
76 fmt.Printf("received: %s\n", retrieved.rawConf)
77 }
78
79 // after one second, we should receive a notification that config has changed
80 <-receivedNotification
81 // signal that we no longer want updates
82 retrieved.Close(context.Background())
83
84 // Output:
85 // received: hello
86 // received notification of new config
87 }
88
89 func TestNewRetrieved(t *testing.T) {
90 ret, err := NewRetrieved(nil)
91 require.NoError(t, err)
92 retMap, err := ret.AsConf()
93 require.NoError(t, err)
94 assert.Equal(t, New(), retMap)
95 assert.NoError(t, ret.Close(context.Background()))
96 }
97
98 func TestNewRetrievedWithOptions(t *testing.T) {
99 want := errors.New("my error")
100 ret, err := NewRetrieved(nil, WithRetrievedClose(func(context.Context) error { return want }))
101 require.NoError(t, err)
102 retMap, err := ret.AsConf()
103 require.NoError(t, err)
104 assert.Equal(t, New(), retMap)
105 assert.Equal(t, want, ret.Close(context.Background()))
106 }
107
108 func TestNewRetrievedUnsupportedType(t *testing.T) {
109 _, err := NewRetrieved(errors.New("my error"))
110 require.Error(t, err)
111 }
112
113 func TestNewRetrievedFromYAML(t *testing.T) {
114 ret, err := NewRetrievedFromYAML([]byte{})
115 require.NoError(t, err)
116 retMap, err := ret.AsConf()
117 require.NoError(t, err)
118 assert.Equal(t, New(), retMap)
119 assert.NoError(t, ret.Close(context.Background()))
120 }
121
122 func TestNewRetrievedFromYAMLWithOptions(t *testing.T) {
123 want := errors.New("my error")
124 ret, err := NewRetrievedFromYAML([]byte{}, WithRetrievedClose(func(context.Context) error { return want }))
125 require.NoError(t, err)
126 retMap, err := ret.AsConf()
127 require.NoError(t, err)
128 assert.Equal(t, New(), retMap)
129 assert.Equal(t, want, ret.Close(context.Background()))
130 }
131
132 func TestNewRetrievedFromYAMLInvalidYAMLBytes(t *testing.T) {
133 ret, err := NewRetrievedFromYAML([]byte("[invalid:,"))
134 require.NoError(t, err)
135
136 _, err = ret.AsConf()
137 require.EqualError(t, err,
138 "retrieved value (type=string) cannot be used as a Conf: assuming string type since contents are not valid YAML: yaml: line 1: did not find expected node content",
139 )
140
141 str, err := ret.AsString()
142 require.NoError(t, err)
143 assert.Equal(t, "[invalid:,", str)
144
145 raw, err := ret.AsRaw()
146 require.NoError(t, err)
147 assert.Equal(t, "[invalid:,", raw)
148 }
149
150 func TestNewRetrievedFromYAMLInvalidAsMap(t *testing.T) {
151 ret, err := NewRetrievedFromYAML([]byte("string"))
152 require.NoError(t, err)
153
154 _, err = ret.AsConf()
155 require.EqualError(t, err, "retrieved value (type=string) cannot be used as a Conf")
156
157 str, err := ret.AsString()
158 require.NoError(t, err)
159 assert.Equal(t, "string", str)
160 }
161
162 func TestNewRetrievedFromYAMLString(t *testing.T) {
163 tests := []struct {
164 yaml string
165 value any
166 altStrRepr string
167 strReprErr string
168 }{
169 {
170 yaml: "string",
171 value: "string",
172 },
173 {
174 yaml: "\"string\"",
175 value: "\"string\"",
176 altStrRepr: "\"string\"",
177 },
178 {
179 yaml: "123",
180 value: 123,
181 },
182 {
183 yaml: "2023-03-20T03:17:55.432328Z",
184 value: time.Date(2023, 3, 20, 3, 17, 55, 432328000, time.UTC),
185 },
186 {
187 yaml: "true",
188 value: true,
189 },
190 {
191 yaml: "0123",
192 value: 0o123,
193 },
194 {
195 yaml: "0x123",
196 value: 0x123,
197 },
198 {
199 yaml: "0b101",
200 value: 0b101,
201 },
202 {
203 yaml: "0.123",
204 value: 0.123,
205 },
206 {
207 yaml: "{key: value}",
208 value: map[string]any{"key": "value"},
209 },
210 }
211
212 for _, tt := range tests {
213 t.Run(tt.yaml, func(t *testing.T) {
214 ret, err := NewRetrievedFromYAML([]byte(tt.yaml))
215 require.NoError(t, err)
216
217 raw, err := ret.AsRaw()
218 require.NoError(t, err)
219 assert.Equal(t, tt.value, raw)
220
221 str, err := ret.AsString()
222 if tt.strReprErr != "" {
223 assert.ErrorContains(t, err, tt.strReprErr)
224 return
225 }
226 require.NoError(t, err)
227
228 if tt.altStrRepr != "" {
229 assert.Equal(t, tt.altStrRepr, str)
230 } else {
231 assert.Equal(t, tt.yaml, str)
232 }
233 })
234 }
235 }