Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(contrib/registry/file/v2): fix the panic caused by channel closing after resolver closed #3691

Merged
merged 1 commit into from
Aug 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions contrib/registry/file/file_discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"context"

"github.com/gogf/gf/v2/container/gmap"
"github.com/gogf/gf/v2/container/gtype"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/gsvc"
"github.com/gogf/gf/v2/os/gfile"
Expand Down Expand Up @@ -55,8 +56,12 @@ func (r *Registry) Watch(ctx context.Context, key string) (watcher gsvc.Watcher,
prefix: key,
discovery: r,
ch: make(chan gsvc.Service, 100),
closed: gtype.NewBool(false),
}
_, err = gfsnotify.Add(r.path, func(event *gfsnotify.Event) {
if fileWatcher.closed.Val() {
return
}
if event.IsChmod() {
return
}
Expand Down
10 changes: 9 additions & 1 deletion contrib/registry/file/file_watcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ package file
import (
"context"

"github.com/gogf/gf/v2/container/gtype"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/net/gsvc"
)

Expand All @@ -17,11 +19,15 @@ type Watcher struct {
prefix string // Watched prefix key, not file name prefix.
discovery gsvc.Discovery // Service discovery.
ch chan gsvc.Service // Changes that caused by inotify.
closed *gtype.Bool // Whether the channel has been closed
}

// Proceed proceeds watch in blocking way.
// It returns all complete services that watched by `key` if any change.
func (w *Watcher) Proceed() (services []gsvc.Service, err error) {
if w.closed.Val() {
return nil, gerror.New("discovery service was closed")
}
<-w.ch
return w.discovery.Search(context.Background(), gsvc.SearchInput{
Prefix: w.prefix,
Expand All @@ -30,6 +36,8 @@ func (w *Watcher) Proceed() (services []gsvc.Service, err error) {

// Close closes the watcher.
func (w *Watcher) Close() error {
close(w.ch)
if w.closed.Cas(false, true) {
close(w.ch)
}
return nil
}