fix: prevent deadlock when watching files (#2599)

* fix deadlock

* improve patch

* re-trigger ci

* improve patch
This commit is contained in:
valoq authored and GitHub committed 2026-05-30 19:20:06 +10:00
1 parent c53aacf373
commit 9e9a988e33
1 file changed
+28 -18
+28 -18
View File
@@ -2,24 +2,27 @@ package main
import (
"log"
"maps"
"os"
"path/filepath"
"slices"
"sync"
"time"
"github.com/fsnotify/fsnotify"
)
type watch struct {
watcher *fsnotify.Watcher
events <-chan fsnotify.Event
quit chan struct{}
pending map[watchUpdate]bool
timeout chan watchUpdate
dirChan chan<- *dir
fileChan chan<- *file
delChan chan<- string
addChan chan string
paths map[string]bool
watcher *fsnotify.Watcher
events <-chan fsnotify.Event
quit chan struct{}
pending map[watchUpdate]bool
timeout chan watchUpdate
dirChan chan<- *dir
fileChan chan<- *file
delChan chan<- string
paths map[string]bool
pathsLock sync.Mutex
}
func newWatch(dirChan chan<- *dir, fileChan chan<- *file, delChan chan<- string) *watch {
@@ -30,7 +33,6 @@ func newWatch(dirChan chan<- *dir, fileChan chan<- *file, delChan chan<- string)
dirChan: dirChan,
fileChan: fileChan,
delChan: delChan,
addChan: make(chan string, 1024),
paths: make(map[string]bool),
}
@@ -76,17 +78,19 @@ func (watch *watch) add(path string) {
return
}
watch.addChan <- path
if err := watch.watcher.Add(path); err != nil {
log.Printf("watch path %s: %s", path, err)
return
}
watch.pathsLock.Lock()
watch.paths[path] = true
watch.pathsLock.Unlock()
}
func (watch *watch) loop() {
for {
select {
case path := <-watch.addChan:
watch.paths[path] = true
if err := watch.watcher.Add(path); err != nil {
log.Printf("watch path %s: %s", path, err)
}
case ev := <-watch.events:
if ev.Has(fsnotify.Create) {
for _, path := range watch.getSameDirs(filepath.Dir(ev.Name)) {
@@ -127,7 +131,9 @@ func (watch *watch) loop() {
delete(watch.pending, update)
}
case <-watch.quit:
watch.pathsLock.Lock()
clear(watch.paths)
watch.pathsLock.Unlock()
return
}
}
@@ -175,7 +181,11 @@ func (watch *watch) getSameDirs(dir string) []string {
return nil
}
for path := range watch.paths {
watch.pathsLock.Lock()
all := slices.Collect(maps.Keys(watch.paths))
watch.pathsLock.Unlock()
for _, path := range all {
if path == dir {
paths = append(paths, path)
continue