aboutsummaryrefslogtreecommitdiff
path: root/internal/watcher/debounce.go
diff options
context:
space:
mode:
authorRanXom <saiyedshizain@gmail.com>2026-07-17 00:36:31 +0530
committerRanXom <saiyedshizain@gmail.com>2026-07-17 00:36:31 +0530
commit9eb299c3ac08e2bea4dfe9e3355178566bcf0501 (patch)
treeeaf1922cf46b4ca9e22a45de2f07e59ea47f5ee1 /internal/watcher/debounce.go
parentd2c0c970f690d52ee3675f377a5eebc22f84afab (diff)
downloadgalleryd-9eb299c3ac08e2bea4dfe9e3355178566bcf0501.tar.xz
galleryd-9eb299c3ac08e2bea4dfe9e3355178566bcf0501.zip
refactor(watcher): isolate debounce loop
Diffstat (limited to 'internal/watcher/debounce.go')
-rw-r--r--internal/watcher/debounce.go62
1 files changed, 62 insertions, 0 deletions
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()
+ }
+ }
+ }
+}