|
| 1 | +package gobreaker |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "testing" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/alicebob/miniredis/v2" |
| 10 | + "github.com/redis/go-redis/v9" |
| 11 | + "github.com/stretchr/testify/assert" |
| 12 | +) |
| 13 | + |
| 14 | +type storeAdapter struct { |
| 15 | + client *redis.Client |
| 16 | +} |
| 17 | + |
| 18 | +func (r *storeAdapter) GetData(ctx context.Context, key string) ([]byte, error) { |
| 19 | + return r.client.Get(ctx, key).Bytes() |
| 20 | +} |
| 21 | + |
| 22 | +func (r *storeAdapter) SetData(ctx context.Context, key string, value []byte) error { |
| 23 | + return r.client.Set(ctx, key, value, 0).Err() |
| 24 | +} |
| 25 | + |
| 26 | +var redisServer *miniredis.Miniredis |
| 27 | + |
| 28 | +func setUpDCB(ctx context.Context) *DistributedCircuitBreaker[any] { |
| 29 | + var err error |
| 30 | + redisServer, err := miniredis.Run() |
| 31 | + if err != nil { |
| 32 | + panic(err) |
| 33 | + } |
| 34 | + |
| 35 | + client := redis.NewClient(&redis.Options{ |
| 36 | + Addr: redisServer.Addr(), |
| 37 | + }) |
| 38 | + |
| 39 | + store := &storeAdapter{client: client} |
| 40 | + |
| 41 | + dcb, err := NewDistributedCircuitBreaker[any](ctx, store, Settings{ |
| 42 | + Name: "TestBreaker", |
| 43 | + MaxRequests: 3, |
| 44 | + Interval: time.Second, |
| 45 | + Timeout: time.Second * 2, |
| 46 | + ReadyToTrip: func(counts Counts) bool { |
| 47 | + return counts.ConsecutiveFailures > 5 |
| 48 | + }, |
| 49 | + }) |
| 50 | + if err != nil { |
| 51 | + panic(err) |
| 52 | + } |
| 53 | + |
| 54 | + return dcb |
| 55 | +} |
| 56 | + |
| 57 | +func tearDownDCB(dcb *DistributedCircuitBreaker[any]) { |
| 58 | + if dcb != nil { |
| 59 | + store := dcb.store.(*storeAdapter) |
| 60 | + store.client.Close() |
| 61 | + store.client = nil |
| 62 | + } |
| 63 | + |
| 64 | + if redisServer != nil { |
| 65 | + redisServer.Close() |
| 66 | + redisServer = nil |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +func dcbPseudoSleep(ctx context.Context, dcb *DistributedCircuitBreaker[any], period time.Duration) { |
| 71 | + state, err := dcb.getSharedState(ctx) |
| 72 | + if err != nil { |
| 73 | + panic(err) |
| 74 | + } |
| 75 | + |
| 76 | + state.Expiry = state.Expiry.Add(-period) |
| 77 | + // Reset counts if the interval has passed |
| 78 | + if time.Now().After(state.Expiry) { |
| 79 | + state.Counts = Counts{} |
| 80 | + } |
| 81 | + |
| 82 | + err = dcb.setSharedState(ctx, state) |
| 83 | + if err != nil { |
| 84 | + panic(err) |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +func successRequest(ctx context.Context, dcb *DistributedCircuitBreaker[any]) error { |
| 89 | + _, err := dcb.Execute(ctx, func() (interface{}, error) { return nil, nil }) |
| 90 | + return err |
| 91 | +} |
| 92 | + |
| 93 | +func failRequest(ctx context.Context, dcb *DistributedCircuitBreaker[any]) error { |
| 94 | + _, err := dcb.Execute(ctx, func() (interface{}, error) { return nil, errors.New("fail") }) |
| 95 | + if err != nil && err.Error() == "fail" { |
| 96 | + return nil |
| 97 | + } |
| 98 | + return err |
| 99 | +} |
| 100 | + |
| 101 | +func assertState(ctx context.Context, t *testing.T, dcb *DistributedCircuitBreaker[any], expected State) { |
| 102 | + state, err := dcb.State(ctx) |
| 103 | + assert.Equal(t, expected, state) |
| 104 | + assert.NoError(t, err) |
| 105 | +} |
| 106 | + |
| 107 | +func TestDistributedCircuitBreakerInitialization(t *testing.T) { |
| 108 | + ctx := context.Background() |
| 109 | + dcb := setUpDCB(ctx) |
| 110 | + defer tearDownDCB(dcb) |
| 111 | + |
| 112 | + assert.Equal(t, "TestBreaker", dcb.Name()) |
| 113 | + assert.Equal(t, uint32(3), dcb.maxRequests) |
| 114 | + assert.Equal(t, time.Second, dcb.interval) |
| 115 | + assert.Equal(t, time.Second*2, dcb.timeout) |
| 116 | + assert.NotNil(t, dcb.readyToTrip) |
| 117 | + |
| 118 | + assertState(ctx, t, dcb, StateClosed) |
| 119 | +} |
| 120 | + |
| 121 | +func TestDistributedCircuitBreakerStateTransitions(t *testing.T) { |
| 122 | + ctx := context.Background() |
| 123 | + dcb := setUpDCB(ctx) |
| 124 | + defer tearDownDCB(dcb) |
| 125 | + |
| 126 | + // Check if initial state is closed |
| 127 | + assertState(ctx, t, dcb, StateClosed) |
| 128 | + |
| 129 | + // StateClosed to StateOpen |
| 130 | + for i := 0; i < 6; i++ { |
| 131 | + assert.NoError(t, failRequest(ctx, dcb)) |
| 132 | + } |
| 133 | + assertState(ctx, t, dcb, StateOpen) |
| 134 | + |
| 135 | + // Ensure requests fail when the circuit is open |
| 136 | + err := failRequest(ctx, dcb) |
| 137 | + assert.Equal(t, ErrOpenState, err) |
| 138 | + |
| 139 | + // Wait for timeout so that the state will move to half-open |
| 140 | + dcbPseudoSleep(ctx, dcb, dcb.timeout) |
| 141 | + assertState(ctx, t, dcb, StateHalfOpen) |
| 142 | + |
| 143 | + // StateHalfOpen to StateClosed |
| 144 | + for i := 0; i < int(dcb.maxRequests); i++ { |
| 145 | + assert.NoError(t, successRequest(ctx, dcb)) |
| 146 | + } |
| 147 | + assertState(ctx, t, dcb, StateClosed) |
| 148 | + |
| 149 | + // StateClosed to StateOpen (again) |
| 150 | + for i := 0; i < 6; i++ { |
| 151 | + assert.NoError(t, failRequest(ctx, dcb)) |
| 152 | + } |
| 153 | + assertState(ctx, t, dcb, StateOpen) |
| 154 | +} |
| 155 | + |
| 156 | +func TestDistributedCircuitBreakerExecution(t *testing.T) { |
| 157 | + ctx := context.Background() |
| 158 | + dcb := setUpDCB(ctx) |
| 159 | + defer tearDownDCB(dcb) |
| 160 | + |
| 161 | + // Test successful execution |
| 162 | + result, err := dcb.Execute(ctx, func() (interface{}, error) { |
| 163 | + return "success", nil |
| 164 | + }) |
| 165 | + assert.NoError(t, err) |
| 166 | + assert.Equal(t, "success", result) |
| 167 | + |
| 168 | + // Test failed execution |
| 169 | + _, err = dcb.Execute(ctx, func() (interface{}, error) { |
| 170 | + return nil, errors.New("test error") |
| 171 | + }) |
| 172 | + assert.Error(t, err) |
| 173 | + assert.Equal(t, "test error", err.Error()) |
| 174 | +} |
| 175 | + |
| 176 | +func TestDistributedCircuitBreakerCounts(t *testing.T) { |
| 177 | + ctx := context.Background() |
| 178 | + dcb := setUpDCB(ctx) |
| 179 | + defer tearDownDCB(dcb) |
| 180 | + |
| 181 | + for i := 0; i < 5; i++ { |
| 182 | + assert.Nil(t, successRequest(ctx, dcb)) |
| 183 | + } |
| 184 | + |
| 185 | + state, err := dcb.getSharedState(ctx) |
| 186 | + assert.Equal(t, Counts{5, 5, 0, 5, 0}, state.Counts) |
| 187 | + assert.NoError(t, err) |
| 188 | + |
| 189 | + assert.Nil(t, failRequest(ctx, dcb)) |
| 190 | + state, err = dcb.getSharedState(ctx) |
| 191 | + assert.Equal(t, Counts{6, 5, 1, 0, 1}, state.Counts) |
| 192 | + assert.NoError(t, err) |
| 193 | +} |
| 194 | + |
| 195 | +var customDCB *DistributedCircuitBreaker[any] |
| 196 | + |
| 197 | +func TestCustomDistributedCircuitBreaker(t *testing.T) { |
| 198 | + ctx := context.Background() |
| 199 | + |
| 200 | + mr, err := miniredis.Run() |
| 201 | + if err != nil { |
| 202 | + panic(err) |
| 203 | + } |
| 204 | + defer mr.Close() |
| 205 | + |
| 206 | + client := redis.NewClient(&redis.Options{ |
| 207 | + Addr: mr.Addr(), |
| 208 | + }) |
| 209 | + |
| 210 | + store := &storeAdapter{client: client} |
| 211 | + |
| 212 | + customDCB, err = NewDistributedCircuitBreaker[any](ctx, store, Settings{ |
| 213 | + Name: "CustomBreaker", |
| 214 | + MaxRequests: 3, |
| 215 | + Interval: time.Second * 30, |
| 216 | + Timeout: time.Second * 90, |
| 217 | + ReadyToTrip: func(counts Counts) bool { |
| 218 | + numReqs := counts.Requests |
| 219 | + failureRatio := float64(counts.TotalFailures) / float64(numReqs) |
| 220 | + return numReqs >= 3 && failureRatio >= 0.6 |
| 221 | + }, |
| 222 | + }) |
| 223 | + assert.NoError(t, err) |
| 224 | + |
| 225 | + t.Run("Initialization", func(t *testing.T) { |
| 226 | + assert.Equal(t, "CustomBreaker", customDCB.Name()) |
| 227 | + assertState(ctx, t, customDCB, StateClosed) |
| 228 | + }) |
| 229 | + |
| 230 | + t.Run("Counts and State Transitions", func(t *testing.T) { |
| 231 | + // Perform 5 successful and 5 failed requests |
| 232 | + for i := 0; i < 5; i++ { |
| 233 | + assert.NoError(t, successRequest(ctx, customDCB)) |
| 234 | + assert.NoError(t, failRequest(ctx, customDCB)) |
| 235 | + } |
| 236 | + |
| 237 | + state, err := customDCB.getSharedState(ctx) |
| 238 | + assert.NoError(t, err) |
| 239 | + assert.Equal(t, StateClosed, state.State) |
| 240 | + assert.Equal(t, Counts{10, 5, 5, 0, 1}, state.Counts) |
| 241 | + |
| 242 | + // Perform one more successful request |
| 243 | + assert.NoError(t, successRequest(ctx, customDCB)) |
| 244 | + state, err = customDCB.getSharedState(ctx) |
| 245 | + assert.NoError(t, err) |
| 246 | + assert.Equal(t, Counts{11, 6, 5, 1, 0}, state.Counts) |
| 247 | + |
| 248 | + // Simulate time passing to reset counts |
| 249 | + dcbPseudoSleep(ctx, customDCB, time.Second*30) |
| 250 | + |
| 251 | + // Perform requests to trigger StateOpen |
| 252 | + assert.NoError(t, successRequest(ctx, customDCB)) |
| 253 | + assert.NoError(t, failRequest(ctx, customDCB)) |
| 254 | + assert.NoError(t, failRequest(ctx, customDCB)) |
| 255 | + |
| 256 | + // Check if the circuit breaker is now open |
| 257 | + assertState(ctx, t, customDCB, StateOpen) |
| 258 | + |
| 259 | + state, err = customDCB.getSharedState(ctx) |
| 260 | + assert.NoError(t, err) |
| 261 | + assert.Equal(t, Counts{0, 0, 0, 0, 0}, state.Counts) |
| 262 | + }) |
| 263 | + |
| 264 | + t.Run("Timeout and Half-Open State", func(t *testing.T) { |
| 265 | + // Simulate timeout to transition to half-open state |
| 266 | + dcbPseudoSleep(ctx, customDCB, time.Second*90) |
| 267 | + assertState(ctx, t, customDCB, StateHalfOpen) |
| 268 | + |
| 269 | + // Successful requests in half-open state should close the circuit |
| 270 | + for i := 0; i < 3; i++ { |
| 271 | + assert.NoError(t, successRequest(ctx, customDCB)) |
| 272 | + } |
| 273 | + assertState(ctx, t, customDCB, StateClosed) |
| 274 | + }) |
| 275 | +} |
| 276 | + |
| 277 | +func TestCustomDistributedCircuitBreakerStateTransitions(t *testing.T) { |
| 278 | + // Setup |
| 279 | + var stateChange StateChange |
| 280 | + customSt := Settings{ |
| 281 | + Name: "cb", |
| 282 | + MaxRequests: 3, |
| 283 | + Interval: 5 * time.Second, |
| 284 | + Timeout: 5 * time.Second, |
| 285 | + ReadyToTrip: func(counts Counts) bool { |
| 286 | + return counts.ConsecutiveFailures >= 2 |
| 287 | + }, |
| 288 | + OnStateChange: func(name string, from State, to State) { |
| 289 | + stateChange = StateChange{name, from, to} |
| 290 | + }, |
| 291 | + } |
| 292 | + |
| 293 | + ctx := context.Background() |
| 294 | + |
| 295 | + mr, err := miniredis.Run() |
| 296 | + if err != nil { |
| 297 | + t.Fatalf("Failed to start miniredis: %v", err) |
| 298 | + } |
| 299 | + defer mr.Close() |
| 300 | + |
| 301 | + client := redis.NewClient(&redis.Options{ |
| 302 | + Addr: mr.Addr(), |
| 303 | + }) |
| 304 | + |
| 305 | + store := &storeAdapter{client: client} |
| 306 | + |
| 307 | + dcb, err := NewDistributedCircuitBreaker[any](ctx, store, customSt) |
| 308 | + assert.NoError(t, err) |
| 309 | + |
| 310 | + // Test case |
| 311 | + t.Run("Circuit Breaker State Transitions", func(t *testing.T) { |
| 312 | + // Initial state should be Closed |
| 313 | + assertState(ctx, t, dcb, StateClosed) |
| 314 | + |
| 315 | + // Cause two consecutive failures to trip the circuit |
| 316 | + for i := 0; i < 2; i++ { |
| 317 | + err := failRequest(ctx, dcb) |
| 318 | + assert.NoError(t, err, "Fail request should not return an error") |
| 319 | + } |
| 320 | + |
| 321 | + // Circuit should now be Open |
| 322 | + assertState(ctx, t, dcb, StateOpen) |
| 323 | + assert.Equal(t, StateChange{"cb", StateClosed, StateOpen}, stateChange) |
| 324 | + |
| 325 | + // Requests should fail immediately when circuit is Open |
| 326 | + err := successRequest(ctx, dcb) |
| 327 | + assert.Error(t, err) |
| 328 | + assert.Equal(t, ErrOpenState, err) |
| 329 | + |
| 330 | + // Simulate timeout to transition to Half-Open |
| 331 | + dcbPseudoSleep(ctx, dcb, 6*time.Second) |
| 332 | + assertState(ctx, t, dcb, StateHalfOpen) |
| 333 | + assert.Equal(t, StateChange{"cb", StateOpen, StateHalfOpen}, stateChange) |
| 334 | + |
| 335 | + // Successful requests in Half-Open state should close the circuit |
| 336 | + for i := 0; i < int(dcb.maxRequests); i++ { |
| 337 | + err := successRequest(ctx, dcb) |
| 338 | + assert.NoError(t, err) |
| 339 | + } |
| 340 | + |
| 341 | + // Circuit should now be Closed |
| 342 | + assertState(ctx, t, dcb, StateClosed) |
| 343 | + assert.Equal(t, StateChange{"cb", StateHalfOpen, StateClosed}, stateChange) |
| 344 | + }) |
| 345 | +} |
0 commit comments