From 9eb299c3ac08e2bea4dfe9e3355178566bcf0501 Mon Sep 17 00:00:00 2001 From: RanXom Date: Fri, 17 Jul 2026 00:36:31 +0530 Subject: refactor(watcher): isolate debounce loop --- internal/watcher/debounce.go | 62 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 internal/watcher/debounce.go (limited to 'internal/watcher/debounce.go') diff --git a/internal/watcher/debounce.go b/internal/watcher/debounce.go new file mode 100644 index 0000000..b2961bd --- /dev/null +++ b/internal/watcher/debounce.go @@ -0,0 +1,62 @@ +package watcher + +import ( + "context" + "time" +) + +// notify schedules a debounced notification. +// +// Multiple filesystem events collapse into a single callback. +func (w *Watcher) notify() { + if w.config.OnChange == nil { + return + } + + select { + case w.debounce <- struct{}{}: + default: + } +} + +func (w *Watcher) debounceLoop(ctx context.Context) { + if w.config.OnChange == nil { + return + } + + timer := time.NewTimer(time.Hour) + + if !timer.Stop() { + select { + case <-timer.C: + default: + } + } + + var pending bool + + for { + select { + case <-ctx.Done(): + return + + case <-w.debounce: + pending = true + + if !timer.Stop() { + select { + case <-timer.C: + default: + } + } + + timer.Reset(w.config.Debounce) + + case <-timer.C: + if pending { + pending = false + w.config.OnChange() + } + } + } +} -- cgit v1.2.3