From 94e0e4b0008c49d074b0797aa12b49978391ffc6 Mon Sep 17 00:00:00 2001 From: Dreamacro <305009791@qq.com> Date: Thu, 30 Apr 2020 20:13:27 +0800 Subject: [PATCH] Fix: make selector `react immediately` --- adapters/outboundgroup/selector.go | 1 + common/singledo/singledo.go | 4 ++++ common/singledo/singledo_test.go | 19 +++++++++++++++++-- 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/adapters/outboundgroup/selector.go b/adapters/outboundgroup/selector.go index 88ac815d..1215dadb 100644 --- a/adapters/outboundgroup/selector.go +++ b/adapters/outboundgroup/selector.go @@ -59,6 +59,7 @@ func (s *Selector) Set(name string) error { for _, proxy := range getProvidersProxies(s.providers) { if proxy.Name() == name { s.selected = name + s.single.Reset() return nil } } diff --git a/common/singledo/singledo.go b/common/singledo/singledo.go index 84978115..58a95434 100644 --- a/common/singledo/singledo.go +++ b/common/singledo/singledo.go @@ -50,6 +50,10 @@ func (s *Single) Do(fn func() (interface{}, error)) (v interface{}, err error, s return call.val, call.err, false } +func (s *Single) Reset() { + s.last = time.Time{} +} + func NewSingle(wait time.Duration) *Single { return &Single{wait: wait} } diff --git a/common/singledo/singledo_test.go b/common/singledo/singledo_test.go index c1e48ca8..637557c4 100644 --- a/common/singledo/singledo_test.go +++ b/common/singledo/singledo_test.go @@ -19,7 +19,7 @@ func TestBasic(t *testing.T) { } var wg sync.WaitGroup - const n = 10 + const n = 5 wg.Add(n) for i := 0; i < n; i++ { go func() { @@ -33,7 +33,7 @@ func TestBasic(t *testing.T) { wg.Wait() assert.Equal(t, 1, foo) - assert.Equal(t, 9, shardCount) + assert.Equal(t, 4, shardCount) } func TestTimer(t *testing.T) { @@ -51,3 +51,18 @@ func TestTimer(t *testing.T) { assert.Equal(t, 1, foo) assert.True(t, shard) } + +func TestReset(t *testing.T) { + single := NewSingle(time.Millisecond * 30) + foo := 0 + call := func() (interface{}, error) { + foo++ + return nil, nil + } + + single.Do(call) + single.Reset() + single.Do(call) + + assert.Equal(t, 2, foo) +}