debounce.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package watch
  14. import (
  15. "context"
  16. "time"
  17. "github.com/docker/compose/v2/pkg/utils"
  18. "github.com/jonboulle/clockwork"
  19. "github.com/sirupsen/logrus"
  20. )
  21. const QuietPeriod = 500 * time.Millisecond
  22. // BatchDebounceEvents groups identical file events within a sliding time window and writes the results to the returned
  23. // channel.
  24. //
  25. // The returned channel is closed when the debouncer is stopped via context cancellation or by closing the input channel.
  26. func BatchDebounceEvents(ctx context.Context, clock clockwork.Clock, input <-chan FileEvent) <-chan []FileEvent {
  27. out := make(chan []FileEvent)
  28. go func() {
  29. defer close(out)
  30. seen := utils.Set[FileEvent]{}
  31. flushEvents := func() {
  32. if len(seen) == 0 {
  33. return
  34. }
  35. logrus.Debugf("flush: %d events %s", len(seen), seen)
  36. events := make([]FileEvent, 0, len(seen))
  37. for e := range seen {
  38. events = append(events, e)
  39. }
  40. out <- events
  41. seen = utils.Set[FileEvent]{}
  42. }
  43. t := clock.NewTicker(QuietPeriod)
  44. defer t.Stop()
  45. for {
  46. select {
  47. case <-ctx.Done():
  48. return
  49. case <-t.Chan():
  50. flushEvents()
  51. case e, ok := <-input:
  52. if !ok {
  53. // input channel was closed
  54. flushEvents()
  55. return
  56. }
  57. if _, ok := seen[e]; !ok {
  58. seen.Add(e)
  59. }
  60. t.Reset(QuietPeriod)
  61. }
  62. }
  63. }()
  64. return out
  65. }