github.com/matrixorigin/matrixone@v0.7.0/pkg/vm/engine/tae/common/retry.go (about) 1 // Copyright 2022 Matrix Origin 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 common 16 17 import ( 18 "context" 19 "runtime" 20 "time" 21 22 "github.com/matrixorigin/matrixone/pkg/common/moerr" 23 ) 24 25 type RetryOp = func() error 26 type WaitOp = func() (ok bool, err error) 27 28 func DoRetry(op RetryOp, ctx context.Context) (err error) { 29 for { 30 if ctx != nil { 31 select { 32 case <-ctx.Done(): 33 return 34 default: 35 } 36 } 37 err = op() 38 if err == nil { 39 break 40 } 41 runtime.Gosched() 42 } 43 return 44 } 45 46 func RetryWithIntervalAndTimeout( 47 op WaitOp, 48 timeout time.Duration, 49 interval time.Duration, suppressTimout bool) (err error) { 50 51 ctx, cancel := context.WithTimeout(context.Background(), timeout) 52 defer cancel() 53 54 ticker := time.NewTicker(interval) 55 defer ticker.Stop() 56 57 var ok bool 58 ok, err = op() 59 if ok { 60 return 61 } 62 63 for { 64 select { 65 case <-ctx.Done(): 66 if suppressTimout { 67 return moerr.GetOkExpectedEOB() 68 } 69 return moerr.NewInternalError(ctx, "timeout") 70 case <-ticker.C: 71 ok, err = op() 72 if ok { 73 return 74 } 75 } 76 } 77 }