1// Copyright 2018, OpenCensus Authors
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
15package ocagent
16
17import (
18	"math/rand"
19	"time"
20)
21
22var randSrc = rand.New(rand.NewSource(time.Now().UnixNano()))
23
24// retries function fn upto n times, if fn returns an error lest it returns nil early.
25// It applies exponential backoff in units of (1<<n) + jitter microsends.
26func nTriesWithExponentialBackoff(nTries int64, timeBaseUnit time.Duration, fn func() error) (err error) {
27	for i := int64(0); i < nTries; i++ {
28		err = fn()
29		if err == nil {
30			return nil
31		}
32		// Backoff for a time period with a pseudo-random jitter
33		jitter := time.Duration(randSrc.Float64()*100) * time.Microsecond
34		ts := jitter + ((1 << uint64(i)) * timeBaseUnit)
35		<-time.After(ts)
36	}
37	return err
38}
39