From 12bc00f1af1fd55e8bad706c0842e6a565894f6b Mon Sep 17 00:00:00 2001 From: Mohammad Rajabloo Date: Mon, 26 Aug 2024 15:43:42 +0330 Subject: [PATCH] fix old success history in halfOpen state --- memory.go | 1 + memory_test.go | 6 ++++-- redis.go | 1 + redis_test.go | 1 + 4 files changed, 7 insertions(+), 2 deletions(-) diff --git a/memory.go b/memory.go index 9076c20..e1680db 100644 --- a/memory.go +++ b/memory.go @@ -34,6 +34,7 @@ type MemoryStorage struct { func (m *MemoryStorage) Failure(ctx context.Context, delta int64) error { m.lastErrorAt.Store(time.Now().UTC()) m.failures.Add(delta) + m.success.Store(0) return nil } diff --git a/memory_test.go b/memory_test.go index 9755819..75f8dc1 100644 --- a/memory_test.go +++ b/memory_test.go @@ -9,9 +9,11 @@ import ( ) func TestMemoryStorageStorage_Failure(t *testing.T) { - t.Run("expected to increment the failure count and last error at", func(t *testing.T) { + t.Run("expected to increment the failure count and last error at and reset success", func(t *testing.T) { ms := NewMemoryStorage(WithFailureRateThreshold(10)) + ms.success.Store(1) + err := ms.Failure(context.Background(), 5) assert.Nil(t, err) assert.Equal(t, int64(5), ms.failures.Load()) @@ -47,7 +49,7 @@ func TestMemoryStorageStorage_Success(t *testing.T) { }) } -func TestMemorystorage_getstatus(t *testing.T) { +func TestMemoryStorage_GetState(t *testing.T) { t.Run("the last error is expired, expect to reset the circuit", func(t *testing.T) { ms := NewMemoryStorage(WithOpenWindow(10 * time.Minute)) ms.lastErrorAt.Store(time.Now().UTC().Add(-11 * time.Minute)) diff --git a/redis.go b/redis.go index eb30fc5..e211ba0 100644 --- a/redis.go +++ b/redis.go @@ -39,6 +39,7 @@ func (r *RedisStorage) Failure(ctx context.Context, delta int64) error { pipe := r.client.Pipeline() pipe.HIncrBy(ctx, r.serviceKey, failuresField, delta) + pipe.HDel(ctx, r.serviceKey, successField) pipe.Expire(ctx, r.serviceKey, r.options.OpenWindow) return r.pipeExec(ctx, pipe) diff --git a/redis_test.go b/redis_test.go index a7a313a..05f161e 100644 --- a/redis_test.go +++ b/redis_test.go @@ -77,6 +77,7 @@ func TestRedisStorage_Failure(t *testing.T) { t.Run("incr failure count to change state to open", func(t *testing.T) { mock.ExpectHIncrBy(tempkey, failuresField, 2).SetVal(2) + mock.ExpectHDel(tempkey, successField).SetVal(2) mock.ExpectExpire(tempkey, circuitbreaker.DefaultOpenWindow).SetVal(true) err := rs.Failure(context.Background(), 2)