Skip to content

Commit

Permalink
fix old success history in halfOpen state
Browse files Browse the repository at this point in the history
  • Loading branch information
mrsoftware committed Aug 27, 2024
1 parent 1cc9dc1 commit 12bc00f
Show file tree
Hide file tree
Showing 4 changed files with 7 additions and 2 deletions.
1 change: 1 addition & 0 deletions memory.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
6 changes: 4 additions & 2 deletions memory_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down Expand Up @@ -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))
Expand Down
1 change: 1 addition & 0 deletions redis.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions redis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 12bc00f

Please sign in to comment.