diff --git a/services/search/pkg/service/event/debouncer.go b/services/search/pkg/service/event/debouncer.go index 9d2a10b08c..a815c5d80d 100644 --- a/services/search/pkg/service/event/debouncer.go +++ b/services/search/pkg/service/event/debouncer.go @@ -61,17 +61,19 @@ func (d *SpaceDebouncer) Debounce(id *provider.StorageSpaceId, ack AckFunc, forc wi := &workItem{force: force} wi.work = func() { + d.mutex.Lock() + if d.pending[id.OpaqueId] != wi { + // the debounce timer and the timeout can both fire for the same item + d.mutex.Unlock() + return + } if _, ok := d.inProgress.Load(id.OpaqueId); ok { // Reschedule this run for when the previous run has finished - d.mutex.Lock() - if wi := d.pending[id.OpaqueId]; wi != nil { - wi.t.Reset(d.after) - } + wi.t.Reset(d.after) d.mutex.Unlock() return } - d.mutex.Lock() wi.timeout.Stop() // stop the timeout timer if it is running delete(d.pending, id.OpaqueId) force := wi.force diff --git a/services/search/pkg/service/event/debouncer_test.go b/services/search/pkg/service/event/debouncer_test.go index 1f3d0a19db..eed4111e52 100644 --- a/services/search/pkg/service/event/debouncer_test.go +++ b/services/search/pkg/service/event/debouncer_test.go @@ -115,6 +115,21 @@ var _ = Describe("SpaceDebouncer", func() { }, "300ms").Should(Equal(1)) }) + It("runs once when the debounce timer and the timeout are due together", func() { + debouncer = event.NewSpaceDebouncer(20*time.Millisecond, 20*time.Millisecond, func(id *sprovider.StorageSpaceId, _ bool) { + if id.OpaqueId == "spaceid" { + callCount.Add(1) + } + }, log.NewLogger()) + + for i := 0; i < 10; i++ { + callCount.Store(0) + debouncer.Debounce(spaceid, nil, false) + time.Sleep(60 * time.Millisecond) + Expect(int(callCount.Load())).To(Equal(1), "iteration %d", i) + } + }) + It("doesn't run the timeout function if the work function has been called", func() { debouncer = event.NewSpaceDebouncer(100*time.Millisecond, 250*time.Millisecond, func(id *sprovider.StorageSpaceId, _ bool) { if id.OpaqueId == "spaceid" {