github.com/livekit/protocol@v1.39.3/utils/retry.go (about) 1 // Copyright 2023 LiveKit, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package utils 16 17 import ( 18 "context" 19 "errors" 20 "math/rand/v2" 21 "time" 22 ) 23 24 type terminalError struct { 25 error 26 } 27 28 func (e terminalError) Unwrap() error { 29 return e.error 30 } 31 32 func TerminalError(err error) error { 33 return terminalError{err} 34 } 35 36 func ErrIsTerminal(err error) bool { 37 var terr terminalError 38 return errors.As(err, &terr) 39 } 40 41 func Retry(ctx context.Context, minTime, maxTime, timeout time.Duration, f func(ctx context.Context) error) error { 42 retryTime := minTime 43 44 ctx, cancel := context.WithTimeout(ctx, timeout) 45 defer cancel() 46 47 for { 48 err := f(ctx) 49 if err == nil || ErrIsTerminal(err) { 50 return err 51 } 52 53 select { 54 case <-ctx.Done(): 55 return err 56 case <-time.After(retryTime): 57 } 58 59 retryTime = min(maxTime, time.Duration((rand.Float64()+1)*float64(retryTime))) 60 } 61 }