// Creates a new RetryWaiter
485715
func NewRetryWaiter(minFailures int, minWait, maxWait time.Duration, jitter Jitter) *RetryWaiter {
	if minFailures < 0 {
		minFailures = defaultMinFailures
	}

	if maxWait <= 0 {
		maxWait = defaultMaxWait
	}

	if minWait <= 0 {
		minWait = 0 * time.Nanosecond
	}

	return &RetryWaiter{
		minFailures: uint(minFailures),
		minWait:     minWait,
		maxWait:     maxWait,
		failures:    0,
		jitter:      jitter,
	}
}
460812
func (rc *Context) Retry(err error) {
	rc.LastError = err

	if rc.Settings.Consumer != nil {
		rc.Settings.Consumer.PauseProgress()
		if neterr.IsNetworkError(err) {
			rc.Settings.Consumer.Infof("having network troubles...")
		} else {
			rc.Settings.Consumer.Infof("%v", err)
		}
	}

	// exponential backoff: 1, 2, 4, 8 seconds...
	delay := int(math.Pow(2, float64(rc.Tries)))
	// ...plus a random number of milliseconds.
	// see https://cloud.google.com/storage/docs/exponential-backoff
	jitter := rand.Int() % 1000

	if rc.Settings.Consumer != nil {
		rc.Settings.Consumer.Infof("Sleeping %d seconds then retrying", delay)
	}

	sleepDuration := time.Second*time.Duration(delay) + time.Millisecond*time.Duration(jitter)
	if rc.Settings.NoSleep {
		if rc.Settings.FakeSleep != nil {
			rc.Settings.FakeSleep(sleepDuration)
		}
	} else {
		time.Sleep(sleepDuration)
	}

	rc.Tries++

	if rc.Settings.Consumer != nil {
		rc.Settings.Consumer.ResumeProgress()
	}
}
59743
func NewResetTimer(init func(), done func(), d time.Duration, run, boot bool) *ResetTimer {
	rs := &ResetTimer{
		reset:    make(chan struct{}),
		kill:     make(chan struct{}),
		duration: d,
		do:       new(sync.Once),
		init:     init,
		done:     done,
		state:    0,
		started:  1,
		lock:     new(sync.Mutex),
	}

	if run {
		rs.runInit()
	}

	if boot {
		rs.handle()
	}

	return rs
}
582775
func NewErrRetryTaskLater(msg string, retryIn time.Duration) ErrRetryTaskLater {
	return ErrRetryTaskLater{msg: msg, retryIn: retryIn}
}
518972
func RetryAny(retryFns ...RetryFn) RetryFn {
	return func(attempt Attempt) bool {
		for _, fn := range retryFns {
			if fn(attempt) {
				return true
			}
		}
		return false
	}
}
404205
func (c oauthClient) CreateReminder(
	date string,
	taskID uint,
	createdByDeviceUdid string,
) (wl.Reminder, error) {

	if taskID == 0 {
		return wl.Reminder{}, errors.New("taskID must be > 0")
	}

	var body []byte
	if createdByDeviceUdid == "" {
		body = []byte(fmt.Sprintf(`{"date":"%s","task_id":%d}`, date, taskID))
	} else {
		body = []byte(fmt.Sprintf(`{"date":"%s","task_id":%d,"created_by_device_udid":"%s"}`, date, taskID, createdByDeviceUdid))
	}

	url := fmt.Sprintf("%s/reminders", c.apiURL)

	req, err := c.newPostRequest(url, body)
	if err != nil {
		return wl.Reminder{}, err
	}

	resp, err := c.do(req)
	if err != nil {
		return wl.Reminder{}, err
	}

	if resp.StatusCode != http.StatusCreated {
		return wl.Reminder{}, fmt.Errorf("Unexpected response code %d - expected %d", resp.StatusCode, http.StatusCreated)
	}

	reminder := wl.Reminder{}
	err = json.NewDecoder(resp.Body).Decode(&reminder)
	if err != nil {
		return wl.Reminder{}, err
	}
	return reminder, nil
}
203017
func NewRetrier(opts Options) Retrier {
	scope := opts.MetricsScope()
	errorTags := struct {
		retryable    map[string]string
		notRetryable map[string]string
	}{
		map[string]string{
			"type": "retryable",
		},
		map[string]string{
			"type": "not-retryable",
		},
	}
	return &retrier{
		initialBackoff: opts.InitialBackoff(),
		backoffFactor:  opts.BackoffFactor(),
		maxBackoff:     opts.MaxBackoff(),
		maxRetries:     opts.MaxRetries(),
		forever:        opts.Forever(),
		jitter:         opts.Jitter(),
		rngFn:          opts.RngFn(),
		sleepFn:        time.Sleep,
		metrics: retrierMetrics{
			success:            scope.Counter("success"),
			successLatency:     scope.Timer("success-latency"),
			errors:             scope.Tagged(errorTags.retryable).Counter("errors"),
			errorsNotRetryable: scope.Tagged(errorTags.notRetryable).Counter("errors"),
			errorsFinal:        scope.Counter("errors-final"),
			errorsLatency:      scope.Timer("errors-latency"),
			retries:            scope.Counter("retries"),
		},
	}
}
141110
func CreateIronQueue(name string) (*mq.Queue, error) {
	subscribers := []mq.QueueSubscriber{}
	subscription := mq.PushInfo{
		Retries:      3,
		RetriesDelay: 60,
		ErrorQueue:   "error_queue",
		Subscribers:  subscribers,
	}
	queue_type := "push"
	queueInfo := mq.QueueInfo{Type: queue_type, MessageExpiration: 60, MessageTimeout: 56, Push: &subscription}
	_, err := mq.CreateQueue(name, queueInfo)
	if err != nil {
		return nil, err
	}

	queue := mq.New(name)
	return &queue, nil
}
827285
func (s *AutoScaleService) CreateCounter(p *CreateCounterParams) (*CreateCounterResponse, error) {
	resp, err := s.cs.newRequest("createCounter", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r CreateCounterResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	// If we have a async client, we need to wait for the async result
	if s.cs.async {
		b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
		if err != nil {
			if err == AsyncTimeoutErr {
				return &r, err
			}
			return nil, err
		}

		b, err = getRawValue(b)
		if err != nil {
			return nil, err
		}

		if err := json.Unmarshal(b, &r); err != nil {
			return nil, err
		}
	}

	return &r, nil
}
1190245
func Retry(err error, message string, args ...interface{}) error {
	return WrapWithMessage(&RetryError{
		Message: fmt.Sprintf(message, args...),
		Err:     err,
	}, message, args...)
}
654328
func (az *Cloud) CreateOrUpdateVMWithRetry(resourceGroup, vmName string, newVM compute.VirtualMachine) error {
	return wait.ExponentialBackoff(az.requestBackoff(), func() (bool, error) {
		ctx, cancel := getContextWithCancel()
		defer cancel()

		resp, err := az.VirtualMachinesClient.CreateOrUpdate(ctx, resourceGroup, vmName, newVM)
		klog.V(10).Infof("VirtualMachinesClient.CreateOrUpdate(%s): end", vmName)
		return az.processHTTPRetryResponse(nil, "", resp, err)
	})
}
1298309
func RetryIsErr(fn func(error) bool) RetryFn {
	return func(attempt Attempt) bool {
		return fn(attempt.Error)
	}
}
713882
func Retry(ctx context.Context, p Policy, e Executer) error {
	b, cancel := p.Start(ctx)
	defer cancel()

	for Continue(b) {
		err := e.Execute(ctx)
		if err == nil {
			return nil
		}

		if IsPermanentError(err) {
			return errors.Wrap(err, `permanent error`)
		}
	}
	return errors.New(`retry attempts failed`)
}
181632
func (rh *RPCHandler) CreateRepo(
	ctx context.Context, arg keybase1.CreateRepoArg) (
	id keybase1.RepoID, err error) {
	rh.log.CDebugf(ctx, "Creating repo %s in folder %s/%s",
		arg.Name, arg.Folder.FolderType, arg.Folder.Name)
	defer func() {
		rh.log.CDebugf(ctx, "Done creating repo: %+v", err)
	}()

	ctx, cancel := context.WithCancel(ctx)
	defer cancel()
	ctx, gitConfig, tlfHandle, tempDir, err := rh.getHandleAndConfig(
		ctx, arg.Folder)
	if err != nil {
		return "", err
	}
	defer func() {
		rmErr := os.RemoveAll(tempDir)
		if rmErr != nil {
			rh.log.CDebugf(
				ctx, "Error cleaning storage dir %s: %+v\n", tempDir, rmErr)
		}
	}()
	defer gitConfig.Shutdown(ctx)

	ctx = context.WithValue(ctx, libkbfs.CtxAllowNameKey, kbfsRepoDir)
	gitID, err := CreateRepoAndID(ctx, gitConfig, tlfHandle, string(arg.Name))
	if err != nil {
		return "", err
	}

	err = rh.waitForJournal(ctx, gitConfig, tlfHandle)
	if err != nil {
		return "", err
	}

	return keybase1.RepoID(gitID.String()), nil
}
1177372
func StandardDelayRetryBehavior(maxRetries uint, retryDelay uint, delayLimit time.Duration, delayFunc RetryDelayFunction) *DelayRetryBehavior {
	return &DelayRetryBehavior{
		retryDelay: retryDelay,
		maxRetries: maxRetries,
		delayLimit: delayLimit,
		delayFunc:  delayFunc,
	}
}
662874
func (d DefaultRetryer) RetryRules(r *request.Request) time.Duration {
	// Set the upper limit of delay in retrying at ~five minutes
	minTime := 30
	throttle := d.shouldThrottle(r)
	if throttle {
		if delay, ok := getRetryDelay(r); ok {
			return delay
		}

		minTime = 500
	}

	retryCount := r.RetryCount
	if throttle && retryCount > 8 {
		retryCount = 8
	} else if retryCount > 13 {
		retryCount = 13
	}

	delay := (1 << uint(retryCount)) * (sdkrand.SeededRand.Intn(minTime) + minTime)
	return time.Duration(delay) * time.Millisecond
}
76141
func (p *asyncProducer) retryHandler() {
	var msg *ProducerMessage
	buf := queue.New()

	for {
		if buf.Length() == 0 {
			msg = <-p.retries
		} else {
			select {
			case msg = <-p.retries:
			case p.input <- buf.Peek().(*ProducerMessage):
				buf.Remove()
				continue
			}
		}

		if msg == nil {
			return
		}

		buf.Add(msg)
	}
}