// toRetryFn combines retry and delay into a retryFn.
178022
func toRetryFn(retry RetryFn, delay DelayFn) retryFn {
	return func(attempt Attempt) (bool, time.Duration) {
		if ok := retry(attempt); !ok {
			return false, 0
		}
		return true, delay(attempt)
	}
}
203909
func (tx *Tx) tryRun(i int, fn TxFn, locked *[]*Ref) (ret interface{}, err error) {

	ret, err = nil, nil

	defer func() {
		r := recover()
		if r == retryError {
			ret, err = nil, retryError
		} else if r != nil {
			panic(r)
		}
	}()

	tx.getReadPoint()
	if i == 0 {
		tx.startPoint = tx.readPoint
		tx.startTime = time.Now()
	}

	tx.info = newTxInfo(txRunning, tx.startPoint)
	ret = fn(tx)

	// make sure no one has killed us before this point, and can't from now on
	if atomic.CompareAndSwapUint32(&tx.info.status, txRunning, txCommitting) {
		for r, calls := range tx.commutes {
			if _, ok := tx.sets[r]; ok {
				continue
			}
			_, wasEnsured := tx.ensures[r]
			tx.releaseIfEnsured(r)
			tryWriteLock(r)
			*locked = append(*locked, r)
			if wasEnsured && r.currValPoint() > tx.readPoint {
				panic(retryError)
			}

			refInfo := r.tinfo
			if refInfo != nil && refInfo != tx.info && refInfo.isRunning() {
				if !tx.barge(refInfo) {
					panic(retryError)
				}
			}
			val := r.tryGetVal()
			tx.vals[r] = val
			for _, call := range calls {
				tx.vals[r] = call.fn(tx.vals[r], call.args...)
			}
		}

		for r, _ := range tx.sets {
			tryWriteLock(r)
			*locked = append(*locked, r)
		}

		// if we do validations for refs, it goes here

		// at this point,
		//    all values are calculated,
		//    all refs to be written are locked
		//    no more client code to be called
		commitPoint := getCommitPoint()
		for r, newV := range tx.vals {
			//oldV := r.tryGetVal()
			r.setValue(newV, commitPoint)
			// todo: call notifies
		}
		atomic.StoreUint32(&tx.info.status, txCommitted)
	}

	return
}
1298309
func RetryIsErr(fn func(error) bool) RetryFn {
	return func(attempt Attempt) bool {
		return fn(attempt.Error)
	}
}
164020
func (t *NetTransport) tcpListen(tcpLn *net.TCPListener) {
	defer t.wg.Done()

	// baseDelay is the initial delay after an AcceptTCP() error before attempting again
	const baseDelay = 5 * time.Millisecond

	// maxDelay is the maximum delay after an AcceptTCP() error before attempting again.
	// In the case that tcpListen() is error-looping, it will delay the shutdown check.
	// Therefore, changes to maxDelay may have an effect on the latency of shutdown.
	const maxDelay = 1 * time.Second

	var loopDelay time.Duration
	for {
		conn, err := tcpLn.AcceptTCP()
		if err != nil {
			if s := atomic.LoadInt32(&t.shutdown); s == 1 {
				break
			}

			if loopDelay == 0 {
				loopDelay = baseDelay
			} else {
				loopDelay *= 2
			}

			if loopDelay > maxDelay {
				loopDelay = maxDelay
			}

			t.logger.Printf("[ERR] memberlist: Error accepting TCP connection: %v", err)
			time.Sleep(loopDelay)
			continue
		}
		// No error, reset loop delay
		loopDelay = 0

		t.streamCh <- conn
	}
}
1232525
func (f *FetchRetrier) Failure(ctx context.Context, uid gregor1.UID, desc types.RetryDescription) (err error) {
	f.Lock()
	defer f.Unlock()
	defer f.Trace(ctx, func() error { return err }, fmt.Sprintf("Failure(%s)", desc))()
	if !f.running {
		f.Debug(ctx, "Failure: not starting new retrier, not running")
		return nil
	}
	key := f.key(uid, desc)
	if _, ok := f.retriers[key]; !ok {
		f.Debug(ctx, "Failure: spawning new retrier: desc: %s", desc)
		control := newRetrierControl(desc)
		f.retriers[key] = control
		f.spawnRetrier(ctx, uid, desc, control)
	}

	return nil
}
574228
func InvariantErrorf(format string, a ...interface{}) error {
	var (
		invariantFormat = InvariantViolatedMetricName + ": " + format
		err             = fmt.Errorf(invariantFormat, a...)
	)

	panicIfEnvSetWithMessage(err.Error())
	return err
}
547006
func (c *Client) retryIntv(base time.Duration) time.Duration {
	if c.config.DevMode {
		return devModeRetryIntv
	}
	return base + lib.RandomStagger(base)
}
143393
func Retry(ctx context.Context, f func() error) error {
	// container for atomic error value
	type errWrap struct {
		E error
	}

	// Try the function in a goroutine
	var errVal atomic.Value
	doneCh := make(chan struct{})
	go func() {
		defer close(doneCh)

		delay := time.Duration(0)
		for {
			// If our context ended, we want to exit right away.
			select {
			case <-ctx.Done():
				return
			case <-time.After(delay):
			}

			// Try the function call
			err := f()

			// return if we have no error, or a FatalError
			done := false
			switch e := err.(type) {
			case nil:
				done = true
			case Fatal:
				err = e.FatalError()
				done = true
			}

			errVal.Store(errWrap{err})

			if done {
				return
			}

			log.Printf("[WARN] retryable error: %v", err)

			delay *= 2

			if delay == 0 {
				delay = initialBackoffDelay
			}

			if delay > maxBackoffDelay {
				delay = maxBackoffDelay
			}

			log.Printf("[INFO] sleeping for %s", delay)
		}
	}()

	// Wait for completion
	select {
	case <-ctx.Done():
	case <-doneCh:
	}

	var lastErr error
	// Check if we got an error executing
	if ev, ok := errVal.Load().(errWrap); ok {
		lastErr = ev.E
	}

	// Check if we have a context error to check if we're interrupted or timeout
	switch ctx.Err() {
	case context.Canceled:
		return fmt.Errorf("interrupted - last error: %v", lastErr)
	case context.DeadlineExceeded:
		return fmt.Errorf("timeout - last error: %v", lastErr)
	}

	if lastErr != nil {
		return lastErr
	}
	return nil
}
266468
func (s *LayerFailure) SetFailureReason(v string) *LayerFailure {
	s.FailureReason = &v
	return s
}
777544
func (r *BulkIndexRequest) RetryOnConflict(retryOnConflict int) *BulkIndexRequest {
	r.retryOnConflict = &retryOnConflict
	r.source = nil
	return r
}
488069
func (d *namespacedResourcesDeleter) retryOnConflictError(namespace *v1.Namespace, fn updateNamespaceFunc) (result *v1.Namespace, err error) {
	latestNamespace := namespace
	for {
		result, err = fn(latestNamespace)
		if err == nil {
			return result, nil
		}
		if !errors.IsConflict(err) {
			return nil, err
		}
		prevNamespace := latestNamespace
		latestNamespace, err = d.nsClient.Get(latestNamespace.Name, metav1.GetOptions{})
		if err != nil {
			return nil, err
		}
		if prevNamespace.UID != latestNamespace.UID {
			return nil, fmt.Errorf("namespace uid has changed across retries")
		}
	}
}
245774
func (f RetrierFunc) Retry(ctx context.Context, retry int, req *http.Request, resp *http.Response, err error) (time.Duration, bool, error) {
	return f(ctx, retry, req, resp, err)
}
650511
func Retry(attempts int, callback func() error) (err error) {
	return RetryAfter(attempts, callback, 0)
}
471827
func (r *StopRetrier) Retry(ctx context.Context, retry int, req *http.Request, resp *http.Response, err error) (time.Duration, bool, error) {
	return 0, false, nil
}
953431
func ToReadCloser(r io.Reader) io.ReadCloser {
	if rc, ok := r.(io.ReadCloser); ok {
		return rc
	}

	return struct {
		io.Reader
		io.Closer
	}{
		r,
		ioutil.NopCloser(nil),
	}
}
919666
func (bot *TgBot) ForwardFn(f func(TgBot, Message, User, int)) *TgBot {
	bot.addToConditionalFuncs(ForwardConditionalCall{f})
	return bot
}
1177372
func StandardDelayRetryBehavior(maxRetries uint, retryDelay uint, delayLimit time.Duration, delayFunc RetryDelayFunction) *DelayRetryBehavior {
	return &DelayRetryBehavior{
		retryDelay: retryDelay,
		maxRetries: maxRetries,
		delayLimit: delayLimit,
		delayFunc:  delayFunc,
	}
}