Procházet zdrojové kódy

fix: wait for a replaced file to resolve before reloading it

A file replaced by a dangling symlink queued a reload that could only fail.
A create at the watched path now reloads only once the file resolves; a
write still always reloads. A watch that has been stopped now also drops an
event that was already waiting, and the tests no longer rely on a fixed
delay for the watcher to be ready.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jamesread před 2 dny
rodič
revize
fc21afd3a6

+ 42 - 11
service/internal/filehelper/file_change_notify.go

@@ -228,12 +228,23 @@ func waitForWatcherEventOrCancel(ctx *watchContext, watcher *fsnotify.Watcher, d
 	case <-done:
 	case <-done:
 		return false
 		return false
 	case event, ok := <-watcher.Events:
 	case event, ok := <-watcher.Events:
-		return handleWatcherEvent(ctx, event, ok)
+		return !isStopped(done) && handleWatcherEvent(ctx, event, ok)
 	case err, ok := <-watcher.Errors:
 	case err, ok := <-watcher.Errors:
 		return handleWatcherError(ctx, err, ok)
 		return handleWatcherError(ctx, err, ok)
 	}
 	}
 }
 }
 
 
+// isStopped stops a watch that has been asked to stop even when an event was
+// already waiting, because select picks between ready channels at random.
+func isStopped(done <-chan struct{}) bool {
+	select {
+	case <-done:
+		return true
+	default:
+		return false
+	}
+}
+
 func handleWatcherEvent(ctx *watchContext, event fsnotify.Event, ok bool) bool {
 func handleWatcherEvent(ctx *watchContext, event fsnotify.Event, ok bool) bool {
 	if !ok {
 	if !ok {
 		return false
 		return false
@@ -287,9 +298,7 @@ func consumeRelevantEvents(ctx *watchContext) {
 // target of its symlink changes.
 // target of its symlink changes.
 func consumeFileEvent(ctx *watchContext) {
 func consumeFileEvent(ctx *watchContext) {
 	if isWatchedFileChange(ctx) {
 	if isWatchedFileChange(ctx) {
-		refreshResolvedPath(ctx)
-		log.Debugf("fsnotify event relevant: %v", ctx.event)
-		processDebounce(ctx)
+		consumeWatchedFileChange(ctx)
 		return
 		return
 	}
 	}
 
 
@@ -302,6 +311,20 @@ func consumeFileEvent(ctx *watchContext) {
 	log.Tracef("fsnotify event irrelevant: %v", ctx.event)
 	log.Tracef("fsnotify event irrelevant: %v", ctx.event)
 }
 }
 
 
+// consumeWatchedFileChange reloads after a write or create at the watched
+// path. A create can leave a dangling symlink, so it only reloads once the
+// file can be read. A write always reloads, as it always has.
+func consumeWatchedFileChange(ctx *watchContext) {
+	_, resolved := resolveWatchedPath(ctx)
+	if !resolved && !ctx.event.Has(fsnotify.Write) {
+		log.Debugf("fsnotify event waiting for %v to resolve: %v", ctx.watchedPath, ctx.event)
+		return
+	}
+
+	log.Debugf("fsnotify event relevant: %v", ctx.event)
+	processDebounce(ctx)
+}
+
 func isWatchedFileChange(ctx *watchContext) bool {
 func isWatchedFileChange(ctx *watchContext) bool {
 	if !ctx.event.Has(fsnotify.Write) && !ctx.event.Has(fsnotify.Create) {
 	if !ctx.event.Has(fsnotify.Write) && !ctx.event.Has(fsnotify.Create) {
 		return false
 		return false
@@ -320,19 +343,27 @@ func isDirectoryChange(event *fsnotify.Event) bool {
 // for example part way through a replacement, the last target is kept and no
 // for example part way through a replacement, the last target is kept and no
 // change is reported, so the file is not reloaded until it can be read.
 // change is reported, so the file is not reloaded until it can be read.
 func refreshResolvedPath(ctx *watchContext) bool {
 func refreshResolvedPath(ctx *watchContext) bool {
-	resolved, err := filepath.EvalSymlinks(ctx.watchedPath)
+	changed, _ := resolveWatchedPath(ctx)
+	return changed
+}
+
+// resolveWatchedPath updates where the watched file points. It reports
+// whether the target changed, and separately whether the file resolved at
+// all.
+func resolveWatchedPath(ctx *watchContext) (changed bool, resolved bool) {
+	target, err := filepath.EvalSymlinks(ctx.watchedPath)
 	if err != nil {
 	if err != nil {
 		log.Debugf("fsnotify could not resolve %v: %v", ctx.watchedPath, err)
 		log.Debugf("fsnotify could not resolve %v: %v", ctx.watchedPath, err)
-		return false
+		return false, false
 	}
 	}
 
 
-	if resolved == ctx.resolvedPath {
-		return false
+	if target == ctx.resolvedPath {
+		return false, true
 	}
 	}
 
 
-	ctx.resolvedPath = resolved
-	watchResolvedDir(ctx, filepath.Dir(resolved))
-	return true
+	ctx.resolvedPath = target
+	watchResolvedDir(ctx, filepath.Dir(target))
+	return true, true
 }
 }
 
 
 func watchResolvedDir(ctx *watchContext, dir string) {
 func watchResolvedDir(ctx *watchContext, dir string) {

+ 24 - 4
service/internal/filehelper/file_watch_symlink_test.go

@@ -175,6 +175,23 @@ func TestWatchFileWriteWaitsForDanglingConfigMapLink(t *testing.T) {
 	recorder.expectOneCall(t)
 	recorder.expectOneCall(t)
 }
 }
 
 
+func TestWatchFileWriteWaitsForDanglingReplacement(t *testing.T) {
+	skipWithoutSymlinks(t)
+
+	dir := t.TempDir()
+	path := filepath.Join(dir, "entities.yaml")
+	writeFile(t, path, "a: 1\n")
+	recorder := watchFileForTest(t, path)
+
+	temporary := filepath.Join(dir, "entities.yaml.tmp")
+	require.NoError(t, os.Symlink(filepath.Join(dir, "missing.yaml"), temporary))
+	require.NoError(t, os.Rename(temporary, path))
+	recorder.expectNone(t)
+
+	writeFile(t, filepath.Join(dir, "missing.yaml"), "a: 2\n")
+	recorder.expectOneCall(t)
+}
+
 func TestWatchFileWriteReloadsRenameSave(t *testing.T) {
 func TestWatchFileWriteReloadsRenameSave(t *testing.T) {
 	path := filepath.Join(t.TempDir(), "entities.yaml")
 	path := filepath.Join(t.TempDir(), "entities.yaml")
 	writeFile(t, path, "a: 1\n")
 	writeFile(t, path, "a: 1\n")
@@ -280,7 +297,6 @@ func TestWatchFileWriteStopsAfterStopFileWatch(t *testing.T) {
 	recorder := watchFileForTest(t, cm.path())
 	recorder := watchFileForTest(t, cm.path())
 
 
 	StopFileWatch(cm.path())
 	StopFileWatch(cm.path())
-	time.Sleep(50 * time.Millisecond)
 	cm.update(t, "a: 2\n")
 	cm.update(t, "a: 2\n")
 
 
 	recorder.expectNone(t)
 	recorder.expectNone(t)
@@ -296,12 +312,16 @@ func TestWatchDirectoryCreateStillFiresForNewFiles(t *testing.T) {
 	done := make(chan struct{})
 	done := make(chan struct{})
 	t.Cleanup(func() { close(done) })
 	t.Cleanup(func() { close(done) })
 
 
-	go watchPath(&watchContext{
+	// The watch is added before the event loop starts, so the file created
+	// below cannot be missed.
+	watcher, err := fsnotify.NewWatcher()
+	require.NoError(t, err)
+	require.NoError(t, watcher.Add(dir))
+	go runWatcher(&watchContext{
 		filedir:         dir,
 		filedir:         dir,
 		callback:        func(filename string) { calls <- filename },
 		callback:        func(filename string) { calls <- filename },
 		interestedEvent: fsnotify.Create,
 		interestedEvent: fsnotify.Create,
-	}, done)
-	time.Sleep(50 * time.Millisecond)
+	}, watcher, done)
 
 
 	created := filepath.Join(dir, "new.txt")
 	created := filepath.Join(dir, "new.txt")
 	writeFile(t, created, "x")
 	writeFile(t, created, "x")