-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathconfig.go
320 lines (273 loc) · 7.72 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
// Copyright (c) 2025 The konf authors
// Use of this source code is governed by a MIT license found in the LICENSE file.
package konf
import (
"context"
"encoding"
"fmt"
"log/slog"
"slices"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/nil-go/konf/internal"
"github.com/nil-go/konf/internal/convert"
"github.com/nil-go/konf/internal/credential"
"github.com/nil-go/konf/internal/maps"
)
// Config reads configuration from appropriate sources.
//
// To create a new Config, call [New].
type Config struct {
nocopy internal.NoCopy[Config]
// Options.
caseSensitive bool
mapKeyCaseSensitive bool
delimiter string
logger *slog.Logger
onStatus func(loader Loader, changed bool, err error)
converter *convert.Converter
providers providers
onChanges onChanges
watched atomic.Pointer[func(*provider)]
}
// New creates a new Config with the given Option(s).
func New(opts ...Option) *Config {
option := &options{}
for _, opt := range opts {
opt(option)
}
// Build converter from options.
if len(option.convertOpts) == 0 {
option.convertOpts = defaultHooks
}
if option.tagName == "" {
option.tagName = defaultTagName
}
option.convertOpts = append(option.convertOpts, convert.WithTagName(option.tagName))
if !option.caseSensitive {
option.convertOpts = append(option.convertOpts, convert.WithKeyMapper(defaultKeyMap))
}
option.converter = convert.New(option.convertOpts...)
return &(option.Config)
}
// Load loads configuration from the given loader.
// Each loader takes precedence over the loaders before it.
//
// This method is concurrent-safe.
func (c *Config) Load(loader Loader) error {
if loader == nil {
return nil
}
c.nocopy.Check()
// Register status callback if the loader is a Statuser.
if statuser, ok := loader.(Statuser); ok {
statuser.Status(func(changed bool, err error) {
if err != nil {
c.log(context.Background(),
slog.LevelWarn,
"Error when loading configuration.",
slog.Any("loader", loader),
slog.Any("error", err),
)
}
if c.onStatus != nil {
c.onStatus(loader, changed, err)
}
})
}
// Load values into a new provider.
values, err := loader.Load()
if err != nil {
return fmt.Errorf("load configuration: %w", err)
}
c.transformKeys(values)
provider := c.providers.append(loader, values)
if _, ok := loader.(Watcher); ok {
// Register watch callback if the loader is a Watcher and the watch is started.
// While Config.Watch is called, c.watched is set for registering the watch callback.
if watch := c.watched.Load(); watch != nil {
(*watch)(provider)
}
}
return nil
}
// Unmarshal reads configuration under the given path from the Config
// and decodes it into the given object pointed to by target.
// The path is case-insensitive unless konf.WithCaseSensitive is set.
func (c *Config) Unmarshal(path string, target any) error {
if c == nil { // To support nil
return nil
}
c.nocopy.Check()
value := c.providers.sub(c.splitPath(path))
if value == nil {
return nil
}
converter := c.converter
if converter == nil { // To support zero Config
converter = defaultConverter
}
if err := converter.Convert(value, target); err != nil {
return fmt.Errorf("decode: %w", err)
}
return nil
}
func (c *Config) log(ctx context.Context, level slog.Level, message string, attrs ...slog.Attr) {
logger := c.logger
if c.logger == nil { // To support zero Config
logger = slog.Default()
}
logger.LogAttrs(ctx, level, message, attrs...)
}
func (c *Config) splitPath(path string) []string {
if path == "" {
return nil
}
if !c.caseSensitive {
path = defaultKeyMap(path)
}
return strings.Split(path, c.delim())
}
func (c *Config) delim() string {
if c.delimiter == "" { // To support zero Config
return "."
}
return c.delimiter
}
func (c *Config) transformKeys(m map[string]any) {
if !c.caseSensitive {
maps.TransformKeys(m, defaultKeyMap, c.mapKeyCaseSensitive)
}
}
// Explain provides information about how Config resolve each value
// from loaders for the given path. It blur sensitive information.
// The path is case-insensitive unless konf.WithCaseSensitive is set.
func (c *Config) Explain(path string) string {
if c == nil { // To support nil
return path + " has no configuration.\n\n"
}
c.nocopy.Check()
value := c.providers.sub(c.splitPath(path))
if value == nil {
return path + " has no configuration.\n\n"
}
explanation := &strings.Builder{}
c.explain(explanation, path, value)
return explanation.String()
}
func (c *Config) explain(explanation *strings.Builder, path string, value any) {
if values, ok := value.(map[string]any); ok {
for key, val := range values {
newPath := path
if newPath != "" {
newPath += c.delim()
}
newPath += key
c.explain(explanation, newPath, val)
}
return
}
type loaderValue struct {
loader Loader
value any
}
var loaders []loaderValue
c.providers.traverse(func(provider *provider) {
if v := maps.Sub(*provider.values.Load(), c.splitPath(path)); v != nil {
loaders = append(loaders, loaderValue{provider.loader, v})
}
})
slices.Reverse(loaders)
if len(loaders) == 0 {
explanation.WriteString(path)
explanation.WriteString(" has no configuration.\n\n")
return
}
explanation.WriteString(path)
explanation.WriteString(" has value[")
explanation.WriteString(credential.Blur(path, loaders[0].value))
explanation.WriteString("] that is loaded by loader[")
explanation.WriteString(fmt.Sprintf("%v", loaders[0].loader))
explanation.WriteString("].\n")
if len(loaders) > 1 {
explanation.WriteString("Here are other value(loader)s:\n")
for _, loader := range loaders[1:] {
explanation.WriteString(" - ")
explanation.WriteString(credential.Blur(path, loader.value))
explanation.WriteString("(")
explanation.WriteString(fmt.Sprintf("%v", loader.loader))
explanation.WriteString(")\n")
}
}
explanation.WriteString("\n")
}
type (
providers struct {
providers []*provider
values atomic.Pointer[map[string]any]
mutex sync.RWMutex
}
provider struct {
loader Loader
values atomic.Pointer[map[string]any]
watched atomic.Bool
}
)
func (p *providers) append(loader Loader, values map[string]any) *provider {
p.mutex.Lock()
defer p.mutex.Unlock()
provider := &provider{loader: loader}
provider.values.Store(&values)
p.providers = append(p.providers, provider)
p.sync()
return provider
}
func (p *providers) changed() {
p.mutex.Lock()
defer p.mutex.Unlock()
p.sync()
}
func (p *providers) sync() {
values := make(map[string]any)
for _, w := range p.providers {
maps.Merge(values, *w.values.Load())
}
p.values.Store(&values)
}
func (p *providers) traverse(action func(*provider)) {
p.mutex.RLock()
defer p.mutex.RUnlock()
for _, provider := range p.providers {
action(provider)
}
}
func (p *providers) sub(path []string) any {
// Here does not need lock since p.values is atomic pointer.
// The map of configuration is just swapping in and out,
// but the map itself is immutable.
// So unmarshal isn't blocked by Config.Load or updating changes by Watch.
val := p.values.Load()
if val == nil { // To support zero Config
return nil
}
return maps.Sub(*val, path)
}
//nolint:gochecknoglobals
var (
defaultTagName = "konf"
defaultKeyMap = strings.ToLower
defaultHooks = []convert.Option{
convert.WithHook[string, time.Duration](time.ParseDuration),
convert.WithHook[string, []string](func(f string) ([]string, error) {
return strings.Split(f, ","), nil
}),
convert.WithHook[string, encoding.TextUnmarshaler](func(f string, t encoding.TextUnmarshaler) error {
return t.UnmarshalText(internal.String2ByteSlice(f))
}),
}
defaultConverter = convert.New(
append(defaultHooks, convert.WithTagName(defaultTagName), convert.WithKeyMapper(defaultKeyMap))...,
)
)