compose/pkg/watch/debounce.go
Sebastiaan van Stijn f03c1b7cfb remove jonboulle/clockwork for testing/synctest
The fake clock is only used by tests to control the debounce timer,
but requires carrying a clock abstraction through production code.

Use the standard time package for the debounce ticker and use
testing/synctest to control time in tests instead.

This removes the clock from composeService and BatchDebounceEvents,
and eliminates the clockwork dependency from the watch implementation.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2026-09-08 15:55:48 +02:00

73 lines
1.8 KiB
Go

/*
Copyright 2020 Docker Compose CLI authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package watch
import (
"context"
"time"
"github.com/sirupsen/logrus"
"github.com/docker/compose/v5/pkg/utils"
)
const QuietPeriod = 500 * time.Millisecond
// BatchDebounceEvents groups identical file events within a sliding time window and writes the results to the returned
// channel.
//
// The returned channel is closed when the debouncer is stopped via context cancellation or by closing the input channel.
func BatchDebounceEvents(ctx context.Context, input <-chan FileEvent) <-chan []FileEvent {
out := make(chan []FileEvent)
go func() {
defer close(out)
seen := utils.Set[FileEvent]{}
flushEvents := func() {
if len(seen) == 0 {
return
}
logrus.Debugf("flush: %d events %s", len(seen), seen)
events := make([]FileEvent, 0, len(seen))
for e := range seen {
events = append(events, e)
}
out <- events
seen = utils.Set[FileEvent]{}
}
t := time.NewTicker(QuietPeriod)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
flushEvents()
case e, ok := <-input:
if !ok {
// input channel was closed
flushEvents()
return
}
if _, ok := seen[e]; !ok {
seen.Add(e)
}
t.Reset(QuietPeriod)
}
}
}()
return out
}