Skip to content

Commit bb800b6

Browse files
authored
fix: ignore self and reduce network request (#22)
1 parent 0e5a318 commit bb800b6

File tree

1 file changed

+15
-28
lines changed

1 file changed

+15
-28
lines changed

watcher.go

Lines changed: 15 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -22,19 +22,19 @@ import (
2222
"time"
2323

2424
"github.com/casbin/casbin/v2/persist"
25-
"go.etcd.io/etcd/api/v3/v3rpc/rpctypes"
2625
client "go.etcd.io/etcd/client/v3"
2726
)
2827

2928
type Watcher struct {
3029
// lock for callback
31-
lock sync.RWMutex
32-
endpoints []string
33-
client *client.Client
34-
running bool
35-
callback func(string)
36-
keyName string
37-
password string
30+
lock sync.RWMutex
31+
endpoints []string
32+
client *client.Client
33+
running bool
34+
callback func(string)
35+
keyName string
36+
password string
37+
lastSentRev int64
3838
}
3939

4040
// finalizer is the destructor for Watcher.
@@ -106,25 +106,12 @@ func (w *Watcher) SetUpdateCallback(callback func(string)) error {
106106
// It is usually called after changing the policy in DB, like Enforcer.SavePolicy(),
107107
// Enforcer.AddPolicy(), Enforcer.RemovePolicy(), etc.
108108
func (w *Watcher) Update() error {
109-
rev := 0
110-
resp, err := w.client.Get(context.Background(), w.keyName)
109+
w.lock.Lock()
110+
defer w.lock.Unlock()
111+
resp, err := w.client.Put(context.TODO(), w.keyName, "")
111112
if err != nil {
112-
if err != rpctypes.ErrKeyNotFound {
113-
return err
114-
}
115-
} else {
116-
if resp.Count != 0 {
117-
rev, err = strconv.Atoi(string(resp.Kvs[0].Value))
118-
if err != nil {
119-
return err
120-
}
121-
rev += 1
122-
}
113+
w.lastSentRev = resp.Header.GetRevision()
123114
}
124-
125-
newRev := strconv.Itoa(rev)
126-
127-
_, err = w.client.Put(context.TODO(), w.keyName, newRev)
128115
return err
129116
}
130117

@@ -135,12 +122,12 @@ func (w *Watcher) startWatch() error {
135122
t := res.Events[0]
136123
if t.IsCreate() || t.IsModify() {
137124
w.lock.RLock()
138-
if w.callback != nil {
139-
w.callback(string(t.Kv.Value))
125+
//ignore self update
126+
if rev := t.Kv.ModRevision; rev > w.lastSentRev && w.callback != nil {
127+
w.callback(strconv.FormatInt(rev, 10))
140128
}
141129
w.lock.RUnlock()
142130
}
143-
144131
}
145132
return nil
146133
}

0 commit comments

Comments
 (0)