-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemory.go
77 lines (60 loc) · 1.76 KB
/
memory.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package circuitbreaker
import (
"context"
"sync/atomic"
"time"
)
var _ Storage = &MemoryStorage{}
// NewMemoryStorage create new instance of Memory.
func NewMemoryStorage(options ...StorageOption) *MemoryStorage {
storage := MemoryStorage{lastErrorAt: atomic.Value{}}
for _, op := range options {
op(&storage.options)
}
storage.lastErrorAt.Store(time.Time{})
return &storage
}
// MemoryStorage is memory based storage for circuit breaker and is concurrent safe.
// do not use single MemoryStorage for multiple service, it will override the other services state.
type MemoryStorage struct {
options StorageOptions
failures atomic.Int64
success atomic.Int64
lastErrorAt atomic.Value
}
// Failure is responsible to store failures.
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
}
// Success is responsible to store success.
func (m *MemoryStorage) Success(ctx context.Context, delta int64) error {
if m.success.Add(delta) >= m.options.SuccessRateThreshold {
return m.Reset(ctx)
}
return nil
}
// GetState current state.
func (m *MemoryStorage) GetState(ctx context.Context) (State, error) {
lastErrorAt := m.lastErrorAt.Load().(time.Time)
errorExpireTTL := lastErrorAt.Add(m.options.OpenWindow).Sub(time.Now().UTC())
if errorExpireTTL <= 0 {
return StateClose, m.Reset(ctx)
}
if errorExpireTTL <= m.options.HalfOpenWindow {
return StateHalfOpen, nil
}
if m.failures.Load() >= m.options.FailureRateThreshold {
return StateOpen, nil
}
return StateClose, nil
}
// Reset the state.
func (m *MemoryStorage) Reset(ctx context.Context) error {
m.success.Store(0)
m.failures.Store(0)
m.lastErrorAt.Store(time.Time{})
return nil
}