Skip to content

Commit 206f5e4

Browse files
Refactor DistributedCircuitBreaker
1 parent 82103c9 commit 206f5e4

File tree

1 file changed

+29
-13
lines changed

1 file changed

+29
-13
lines changed

v2/distributed_gobreaker.go

Lines changed: 29 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -96,25 +96,41 @@ func (dcb *DistributedCircuitBreaker[T]) setSharedState(ctx context.Context, sta
9696
return dcb.store.SetData(ctx, dcb.sharedStateKey(), data)
9797
}
9898

99+
func (dcb *DistributedCircuitBreaker[T]) inject(shared SharedState) {
100+
dcb.mutex.Lock()
101+
defer dcb.mutex.Unlock()
102+
103+
dcb.state = shared.State
104+
dcb.generation = shared.Generation
105+
dcb.counts = shared.Counts
106+
dcb.expiry = shared.Expiry
107+
}
108+
109+
func (dcb *DistributedCircuitBreaker[T]) extract() SharedState {
110+
dcb.mutex.Lock()
111+
defer dcb.mutex.Unlock()
112+
113+
return SharedState{
114+
State: dcb.state,
115+
Generation: dcb.generation,
116+
Counts: dcb.counts,
117+
Expiry: dcb.expiry,
118+
}
119+
}
120+
99121
// State returns the State of DistributedCircuitBreaker.
100122
func (dcb *DistributedCircuitBreaker[T]) State(ctx context.Context) (State, error) {
101-
state, err := dcb.getSharedState(ctx)
123+
shared, err := dcb.getSharedState(ctx)
102124
if err != nil {
103-
return state.State, err
125+
return shared.State, err
104126
}
105127

106-
now := time.Now()
107-
currentState, _ := dcb.currentState(state, now)
128+
dcb.inject(shared)
129+
state := dcb.State()
130+
shared = dcb.extract()
108131

109-
// update the state if it has changed
110-
if currentState != state.State {
111-
state.State = currentState
112-
if err := dcb.setSharedState(ctx, state); err != nil {
113-
return state.State, err
114-
}
115-
}
116-
117-
return state.State, nil
132+
err = dcb.setSharedState(ctx, shared)
133+
return state, err
118134
}
119135

120136
// Execute runs the given request if the DistributedCircuitBreaker accepts it.

0 commit comments

Comments
 (0)