Skip to content

Commit e43e0d8

Browse files
committed
[common-go] backoff and retry watching files
1 parent 6d58e92 commit e43e0d8

File tree

1 file changed

+32
-8
lines changed

1 file changed

+32
-8
lines changed

components/common-go/watch/file.go

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"io"
1313
"os"
1414
"path/filepath"
15+
"time"
1516

1617
"github.com/fsnotify/fsnotify"
1718

@@ -59,6 +60,12 @@ func File(ctx context.Context, path string, onChange func()) error {
5960
fw.hash = hash
6061

6162
go func() {
63+
const (
64+
initialBackoff = 100 * time.Millisecond
65+
maxBackoff = 15 * time.Second
66+
)
67+
var currentBackoff time.Duration
68+
6269
defer func() {
6370
if err != nil {
6471
log.WithError(err).Error("Stopping file watch")
@@ -83,23 +90,40 @@ func File(ctx context.Context, path string, onChange func()) error {
8390
continue
8491
}
8592

86-
currentHash, err := hashConfig(path)
87-
if err != nil {
88-
log.WithError(err).WithField("event", event.Name).Warn("Cannot check if config has changed")
89-
return
93+
currentHash, hashErr := hashConfig(path)
94+
if hashErr != nil {
95+
log.WithError(hashErr).WithField("event", event.Name).Warn("Cannot check if config has changed, backing off")
96+
97+
if currentBackoff == 0 {
98+
currentBackoff = initialBackoff
99+
} else {
100+
currentBackoff *= 2
101+
if currentBackoff > maxBackoff {
102+
currentBackoff = maxBackoff
103+
}
104+
}
105+
106+
select {
107+
case <-time.After(currentBackoff):
108+
case <-ctx.Done():
109+
log.Info("Context cancelled during backoff sleep, stopping file watcher")
110+
return
111+
}
112+
continue
90113
}
91114

92-
// no change
115+
currentBackoff = 0
116+
93117
if currentHash == fw.hash {
118+
log.WithField("path", path).Debug("Config file changed but content hash is the same")
94119
continue
95120
}
96121

97122
log.WithField("path", path).Info("reloading file after change")
98-
99123
fw.hash = currentHash
100124
fw.onChange()
101-
case err := <-watcher.Errors:
102-
log.WithError(err).Error("Unexpected error watching event")
125+
case watchErr := <-watcher.Errors:
126+
log.WithError(watchErr).Error("Unexpected error watching event")
103127
case <-ctx.Done():
104128
return
105129
}

0 commit comments

Comments
 (0)