feat: add BackoffUntilNil func in backoff

This commit is contained in:
wuqinqiang 2023-12-21 14:37:21 +08:00
parent 2d67e2e0c6
commit 2d4049d78d
2 changed files with 24 additions and 5 deletions

View File

@ -282,7 +282,6 @@ func (svr *Service) login() (conn net.Conn, connector Connector, err error) {
func (svr *Service) loopLoginUntilSuccess(maxInterval time.Duration, firstLoginExit bool) {
xl := xlog.FromContextSafe(svr.ctx)
successCh := make(chan struct{})
loginFunc := func() error {
xl.Info("try to connect to server...")
@ -327,13 +326,11 @@ func (svr *Service) loopLoginUntilSuccess(maxInterval time.Duration, firstLoginE
}
svr.ctl = ctl
svr.ctlMu.Unlock()
close(successCh)
return nil
}
// try to reconnect to server until success
wait.BackoffUntil(loginFunc, wait.NewFastBackoffManager(
wait.BackoffUntilNil(loginFunc, wait.NewFastBackoffManager(
wait.FastBackoffOptions{
Duration: time.Second,
Factor: 2,
@ -341,7 +338,7 @@ func (svr *Service) loopLoginUntilSuccess(maxInterval time.Duration, firstLoginE
MaxDuration: maxInterval,
}),
true,
wait.MergeAndCloseOnAnyStopChannel(svr.ctx.Done(), successCh))
wait.MergeAndCloseOnAnyStopChannel(svr.ctx.Done()))
}
func (svr *Service) UpdateAllConfigurer(proxyCfgs []v1.ProxyConfigurer, visitorCfgs []v1.VisitorConfigurer) error {

View File

@ -157,6 +157,28 @@ func BackoffUntil(f func() error, backoff BackoffManager, sliding bool, stopCh <
}
}
func BackoffUntilNil(f func() error, backoff BackoffManager, sliding bool, stopCh <-chan struct{}) {
//first try
delay := backoff.Backoff(0, false)
ticker := time.NewTicker(delay)
defer ticker.Stop()
for {
select {
case <-stopCh:
return
case <-ticker.C:
}
if err := f(); err == nil {
return
}
if sliding {
delay = backoff.Backoff(delay, true)
}
ticker.Reset(delay)
}
}
// Jitter returns a time.Duration between duration and duration + maxFactor *
// duration.
//