Skip to content

Commit

Permalink
(refactor): The closed field type is changed from atomic.Value to…
Browse files Browse the repository at this point in the history
… `*gtype.Bool` type, and the `Proceed` method is modified to return an unreasonable error: `context.Canceled`
  • Loading branch information
zishang520 committed Jul 30, 2024
1 parent bb2c585 commit 94735f3
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 11 deletions.
4 changes: 3 additions & 1 deletion 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,9 +56,10 @@ 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.Load() != nil {
if fileWatcher.closed.Val() {
return
}
if event.IsChmod() {
Expand Down
20 changes: 10 additions & 10 deletions contrib/registry/file/file_watcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ package file

import (
"context"
"sync/atomic"

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

Expand All @@ -18,25 +19,24 @@ 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 atomic.Value // Whether the channel has been closed
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.Load() == nil {
<-w.ch
return w.discovery.Search(context.Background(), gsvc.SearchInput{
Prefix: w.prefix,
})
if w.closed.Val() {
return nil, gerror.New("discovery service was closed")
}
return nil, context.Canceled
<-w.ch
return w.discovery.Search(context.Background(), gsvc.SearchInput{
Prefix: w.prefix,
})
}

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

0 comments on commit 94735f3

Please sign in to comment.