-
Notifications
You must be signed in to change notification settings - Fork 9
/
watch.go
184 lines (155 loc) · 4.74 KB
/
watch.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
// Copyright (c) 2024 The konf authors
// Use of this source code is governed by a MIT license found in the LICENSE file.
package konf
import (
"context"
"errors"
"fmt"
"log/slog"
"reflect"
"sync"
"time"
"github.com/nil-go/konf/internal/maps"
)
// Watch watches and updates configuration when it changes.
// It blocks until ctx is done, or the service returns an error.
//
// It only can be called once. Call after first has no effects.
func (c *Config) Watch(ctx context.Context) error { //nolint:cyclop,funlen,gocognit
c.nocopy.Check()
ctx, cancel := context.WithCancelCause(ctx)
defer cancel(nil)
// Start a goroutine to update the configuration while it has changes from watchers.
onChangesChannel := make(chan []func(*Config), 1)
defer close(onChangesChannel)
var waitGroup sync.WaitGroup
watchProvider := func(provider *provider) {
if !provider.watched.CompareAndSwap(false, true) {
return // Skip if the provider has been watched.
}
if watcher, ok := provider.loader.(Watcher); ok {
waitGroup.Add(1)
go func(ctx context.Context) {
defer waitGroup.Done()
onChange := func(values map[string]any) {
c.transformKeys(values)
oldValues := *provider.values.Swap(&values)
onChangesChannel <- c.onChanges.get(
func(path string) bool {
paths := c.splitPath(path)
return !reflect.DeepEqual(maps.Sub(oldValues, paths), maps.Sub(values, paths))
},
)
c.log(ctx, slog.LevelInfo,
"Configuration has been changed.",
slog.Any("loader", watcher),
)
}
c.log(ctx, slog.LevelDebug, "Watching configuration change.", slog.Any("loader", watcher))
if err := watcher.Watch(ctx, onChange); err != nil {
cancel(fmt.Errorf("watch configuration change on %v: %w", watcher, err))
}
}(ctx)
}
}
// Set c.watched so that the loader loaded after Watch can register the watch callback.
// It's also used for marker that Watch has been called.
if !c.watched.CompareAndSwap(nil, &watchProvider) {
c.log(ctx, slog.LevelWarn, "Config has been watched, call Watch more than once has no effects.")
return nil
}
waitGroup.Add(1)
go func() {
defer waitGroup.Done()
for {
select {
case <-ctx.Done():
return
case onChanges := <-onChangesChannel:
c.providers.changed()
c.log(ctx, slog.LevelDebug, "Configuration has been updated with change.")
if len(onChanges) > 0 {
func() {
done := make(chan struct{})
go func() {
defer close(done)
for _, onChange := range onChanges {
onChange(c)
}
}()
tctx, tcancel := context.WithTimeout(ctx, time.Minute)
defer tcancel()
select {
case <-done:
c.log(ctx, slog.LevelDebug, "Configuration has been applied to onChanges.")
case <-tctx.Done():
if errors.Is(tctx.Err(), context.DeadlineExceeded) {
c.log(
ctx, slog.LevelWarn,
"Configuration has not been fully applied to onChanges in one minute."+
" Please check if the onChanges is blocking or takes too long to complete.",
)
}
}
}()
}
}
}
}()
// Start a watching goroutine for each watcher registered.
c.providers.traverse(watchProvider)
waitGroup.Wait()
if err := context.Cause(ctx); err != nil && !errors.Is(err, ctx.Err()) {
return err //nolint:wrapcheck
}
return nil
}
// OnChange registers a callback function that is executed
// when the value of any given path in the Config changes.
// It requires Config.Watch has been called first.
// The paths are case-insensitive unless konf.WithCaseSensitive is set.
//
// The register function must be non-blocking and usually completes instantly.
// If it requires a long time to complete, it should be executed in a separate goroutine.
//
// This method is concurrent-safe.
func (c *Config) OnChange(onChange func(*Config), paths ...string) {
if onChange == nil {
return // Do nothing is onchange is nil.
}
c.nocopy.Check()
if !c.caseSensitive {
for i := range paths {
paths[i] = defaultKeyMap(paths[i])
}
}
c.onChanges.register(onChange, paths)
}
type onChanges struct {
subscribers map[string][]func(*Config)
mutex sync.RWMutex
}
func (o *onChanges) register(onChange func(*Config), paths []string) {
o.mutex.Lock()
defer o.mutex.Unlock()
if len(paths) == 0 {
paths = []string{""}
}
if o.subscribers == nil {
o.subscribers = make(map[string][]func(*Config))
}
for _, path := range paths {
o.subscribers[path] = append(o.subscribers[path], onChange)
}
}
func (o *onChanges) get(filter func(string) bool) []func(*Config) {
o.mutex.RLock()
defer o.mutex.RUnlock()
var callbacks []func(*Config)
for path, subscriber := range o.subscribers {
if filter(path) {
callbacks = append(callbacks, subscriber...)
}
}
return callbacks
}