Skip to content

Commit

Permalink
Block in filePoller.Close until loop is finished
Browse files Browse the repository at this point in the history
This is beneficial for housekeeping purposes, waiting until all resources are
released. More precisely, it should produce deterministic outcomes in testing
code, code coverage, etc.

[skip codecov]
  • Loading branch information
sevein committed Mar 8, 2024
1 parent 3779ee7 commit 7380286
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
2 changes: 2 additions & 0 deletions internal/filenotify/filenotify.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,12 @@ func NewPollingWatcher(cfg Config) (FileWatcher, error) {
wr: watcher.New(),
events: make(chan fsnotify.Event),
errors: make(chan error),
done: make(chan struct{}),
}
poller.wr.FilterOps(watcher.Create, watcher.Rename, watcher.Move)
go poller.loop()

// Block until radovskyb's watcher is started.
done := make(chan error)
{
go func() {
Expand Down
14 changes: 13 additions & 1 deletion internal/filenotify/poller.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package filenotify

import (
"errors"
"time"

"github.com/fsnotify/fsnotify"
"github.com/radovskyb/watcher"
)
Expand All @@ -16,6 +19,9 @@ type filePoller struct {

// errors is the channel to listen to for watch errors.
errors chan error

// done signals that the loop is done when the channel is closed.
done chan struct{}
}

// loop captures and transform radovskyb's watcher into fsnotify events.
Expand Down Expand Up @@ -43,6 +49,7 @@ func (w *filePoller) loop() {
case err := <-w.wr.Error:
w.errors <- err
case <-w.wr.Closed:
close(w.done)
return
}
}
Expand Down Expand Up @@ -70,5 +77,10 @@ func (w *filePoller) Errors() <-chan error {
func (w *filePoller) Close() error {
w.wr.Close()

return nil
select {
case <-w.done:
return nil
case <-time.After(time.Second * 5):
return errors.New("filePoller.Close timeout")

Check warning on line 84 in internal/filenotify/poller.go

View check run for this annotation

Codecov / codecov/patch

internal/filenotify/poller.go#L83-L84

Added lines #L83 - L84 were not covered by tests
}
}

0 comments on commit 7380286

Please sign in to comment.