// shouldAttempt evaluates the provided strategies with the given attempt to
// determine if the Retry loop should make another attempt.
194973
func shouldAttempt(attempt uint, strategies ...strategy.Strategy) bool {
	shouldAttempt := true

	for i := 0; shouldAttempt && i < len(strategies); i++ {
		shouldAttempt = shouldAttempt && strategies[i](attempt)
	}

	return shouldAttempt
}
1077499
func (w *deploymentWatcher) shouldFail() (fail, rollback bool, err error) {
	snap, err := w.state.Snapshot()
	if err != nil {
		return false, false, err
	}

	d, err := snap.DeploymentByID(nil, w.deploymentID)
	if err != nil {
		return false, false, err
	}
	if d == nil {
		// The deployment wasn't in the state store, possibly due to a system gc
		return false, false, fmt.Errorf("deployment id not found: %q", w.deploymentID)
	}

	fail = false
	for tg, state := range d.TaskGroups {
		// If we are in a canary state we fail if there aren't enough healthy
		// allocs to satisfy DesiredCanaries
		if state.DesiredCanaries > 0 && !state.Promoted {
			if state.HealthyAllocs >= state.DesiredCanaries {
				continue
			}
		} else if state.HealthyAllocs >= state.DesiredTotal {
			continue
		}

		// We have failed this TG
		fail = true

		// We don't need to autorevert this group
		upd := w.j.LookupTaskGroup(tg).Update
		if upd == nil || !upd.AutoRevert {
			continue
		}

		// Unhealthy allocs and we need to autorevert
		return true, true, nil
	}

	return fail, false, nil
}
1337313
func ShouldResembleByKey(key string) func(actual interface{}, expected ...interface{}) string {
	const msg = "Expected: '%v'\nActual:   '%v'\n(Should equal slice: %v)!"

	return func(actual interface{}, expected ...interface{}) string {
		if len(expected) != 1 {
			return fmt.Sprintf("This assertion requires exactly %v comparison values (you provided %v).", 1, len(expected))
		}
		formatError := func(format string, args ...interface{}) string {
			errMsg := fmt.Sprintf(format, args...)
			return fmt.Sprintf(msg, spew.Sdump(expected[0]), spew.Sdump(actual), errMsg)
		}

		a := reflect.ValueOf(actual)
		e := reflect.ValueOf(expected[0])
		if a.Kind() != reflect.Slice || e.Kind() != reflect.Slice {
			return formatError("Both must be slice")
		}
		if errMsg := canGetKey(a.Type().Elem(), key); errMsg != "" {
			return formatError(errMsg)
		}
		if errMsg := canGetKey(e.Type().Elem(), key); errMsg != "" {
			return formatError(errMsg)
		}
		if a.Len() != e.Len() {
			return formatError("Length not equal")
		}

		collectIndexes := func(name string, list reflect.Value) (
			[]reflect.Value, map[interface{}]int, string,
		) {
			keys := make([]reflect.Value, list.Len())
			mapIndexes := make(map[interface{}]int)
			for i := 0; i < list.Len(); i++ {
				item := list.Index(i)
				switch item.Kind() {
				case reflect.Interface, reflect.Map, reflect.Ptr:
					if item.IsNil() {
						return nil, nil, formatError(
							"All items must not be nil (%v[%v] is nil)", name, i)
					}
				}

				itemKey := getKey(item, key)
				keys[i] = itemKey
				if !itemKey.IsValid() {
					return nil, nil, formatError(
						"Could not get key from %v[%v]", name, i)
				}

				keyValue := itemKey.Interface()
				if keyValue == nil {
					return nil, nil, formatError(
						"All item keys must not be nil (%v[%v].%v is nil)", name, i, key)
				}

				keyType := reflect.TypeOf(keyValue)
				if !keyType.Comparable() {
					return nil, nil, formatError(
						"All item keys must be comparable (%v[%v].%v is not, type is `%v`)",
						name, i, key, keyType)
				}
				if prev, ok := mapIndexes[keyValue]; ok {
					return nil, nil, formatError(
						"%v[%v] and %v[%v] has duplicated keys: `%v`",
						name, prev, name, i, keyValue)
				}
				mapIndexes[keyValue] = i
			}
			return keys, mapIndexes, ""
		}
		expectedKeys, _, errMsg := collectIndexes("expected", e)
		if errMsg != "" {
			return errMsg
		}
		_, mapActualIndexes, errMsg := collectIndexes("actual", a)
		if errMsg != "" {
			return errMsg
		}

		// Compare actual with the same order as expected
		for i, ekey := range expectedKeys {
			actualIndex, ok := mapActualIndexes[ekey.Interface()]
			if !ok {
				return formatError("Expected item with %v=`%v` but not found",
					key, ekey.Interface())
			}

			expectedItem := e.Index(i)
			actualItem := a.Index(actualIndex)

			diff := deep.Equal(actualItem.Interface(), expectedItem.Interface())
			if len(diff) > 0 {
				return formatError("Item with %v=`%v` is different: %v",
					key, ekey.Interface(), spew.Sdump(diff))
			}
		}
		return ""
	}
}
780385
func (s *BulkDeploymentMetrics) SetRetryAttempts(v int64) *BulkDeploymentMetrics {
	s.RetryAttempts = &v
	return s
}
536941
func shouldRetry(status int) bool {
	return status == http.StatusAccepted || status == http.StatusTooManyRequests
}
503066
func (pc *peerContainer) handleAttempt(event *peerEvent) []*peerEvent {
	bundle, events := pc.bundle(event.IP)
	bundle.Attempts = append(bundle.Attempts, &peerAttempt{
		Connected:    *event.Connected,
		Disconnected: *event.Disconnected,
	})
	pc.attemptOrder = append(pc.attemptOrder, event.IP)
	for len(pc.attemptOrder) > attemptLimit {
		// While the length of the connection attempt order array is greater
		// than the limit, remove the first element from the involved peer's
		// array and also from the super array.
		events = append(events, pc.removeAttempt(pc.attemptOrder[0])...)
		pc.attemptOrder = pc.attemptOrder[1:]
	}
	return events
}
1324189
func (s *RetryStrategy) SetAttempts(v int64) *RetryStrategy {
	s.Attempts = &v
	return s
}
846425
func (q *queue) ShouldThrottleReceipts() bool {
	q.lock.Lock()
	defer q.lock.Unlock()

	return q.resultSlots(q.receiptPendPool, q.receiptDonePool) <= 0
}
451537
func shouldExecute(when string) (bool, error) {
	if when == "" {
		return true, nil
	}
	expression, err := govaluate.NewEvaluableExpression(when)
	if err != nil {
		return false, errors.Errorf(errors.CodeBadRequest, "Invalid 'when' expression '%s': %v", when, err)
	}
	// The following loop converts govaluate variables (which we don't use), into strings. This
	// allows us to have expressions like: "foo != bar" without requiring foo and bar to be quoted.
	tokens := expression.Tokens()
	for i, tok := range tokens {
		switch tok.Kind {
		case govaluate.VARIABLE:
			tok.Kind = govaluate.STRING
		default:
			continue
		}
		tokens[i] = tok
	}
	expression, err = govaluate.NewEvaluableExpressionFromTokens(tokens)
	if err != nil {
		return false, errors.InternalWrapErrorf(err, "Failed to parse 'when' expression '%s': %v", when, err)
	}
	result, err := expression.Evaluate(nil)
	if err != nil {
		return false, errors.InternalWrapErrorf(err, "Failed to evaluate 'when' expresion '%s': %v", when, err)
	}
	boolRes, ok := result.(bool)
	if !ok {
		return false, errors.Errorf(errors.CodeBadRequest, "Expected boolean evaluation for '%s'. Got %v", when, result)
	}
	return boolRes, nil
}
714552
func MustTrytesToTrits(trytes Trytes) Trits {
	trits, err := TrytesToTrits(trytes)
	if err != nil {
		panic(err)
	}
	return trits
}
883999
func (t *partitionTracker) CompactionAttempted(level int, success bool, d time.Duration) {
	if !t.enabled {
		return
	}

	labels := t.Labels()
	labels["level"] = fmt.Sprint(level)
	if success {
		t.metrics.CompactionDuration.With(labels).Observe(d.Seconds())

		labels["status"] = "ok"
		t.metrics.Compactions.With(labels).Inc()
		return
	}

	labels["status"] = "error"
	t.metrics.Compactions.With(labels).Inc()
}
989296
func (r CustomRetryer) ShouldRetry(req *request.Request) bool {
	if req.HTTPResponse.StatusCode >= 500 {
		// Don't retry any 5xx status codes.
		return false
	}

	// Fallback to SDK's built in retry rules
	return r.DefaultRetryer.ShouldRetry(req)
}
111636
func ShouldResembleSlice(actual interface{}, expected ...interface{}) string {
	const msg = "Expected: '%v'\nActual:   '%v'\n(Should equal slice: %v)!"

	if len(expected) != 1 {
		return fmt.Sprintf("This assertion requires exactly %v comparison values (you provided %v).", 1, len(expected))
	}

	a := reflect.ValueOf(actual)
	e := reflect.ValueOf(expected[0])
	if a.Kind() != reflect.Slice || e.Kind() != reflect.Slice {
		return fmt.Sprintf(msg, spew.Sdump(expected[0]), spew.Sdump(actual),
			"Both must be slice")
	}

	if a.Len() != e.Len() {
		return fmt.Sprintf(msg, spew.Sdump(expected[0]), spew.Sdump(actual),
			"Length not equal")
	}

	count := 0
	indexes := make([]bool, a.Len())
	for i := 0; i < a.Len(); i++ {
		ai := a.Index(i)
		matched := false
		for j := 0; j < e.Len(); j++ {
			if ok := indexes[j]; ok {
				// already compared
				continue
			}
			ej := e.Index(j)
			if res := deep.Equal(ej.Interface(), ai.Interface()); res == nil {
				indexes[j] = true
				count++
				matched = true
				break
			}
		}
		if !matched {
			diff := deep.Equal(expected[0], actual)
			format := "Not match %d items: %v"
			if len(diff) == 1 {
				format = "Not match %d item: %v"
			}
			return fmt.Sprintf(msg, spew.Sdump(expected[0]), spew.Sdump(actual),
				fmt.Sprintf(format, len(diff), spew.Sdump(diff)),
			)
		}
	}
	if count != a.Len() {
		return fmt.Sprintf(msg, spew.Sdump(expected[0]), spew.Sdump(actual),
			"Slices are not equal")
	}
	return ""
}
663245
func (tx *TX) MustExecute(stmt Executable, args ...interface{}) sql.Result {
	s, params, err := tx.compile(stmt)
	if err != nil {
		log.Panicf(
			"aspect: failed to compile (%s): %s",
			stmt,
			err,
		)
	}
	if len(args) == 0 {
		args = params.args
	}
	result, err := tx.Exec(s, args...)
	if err != nil {
		log.Panicf(
			"aspect: failed to exec (%s) with parameters (%v): %s",
			s,
			args,
			err,
		)
	}
	return result
}
874935
func (s *scanner) shouldClose(resp *pb.ScanResponse, region hrpc.RegionInfo) bool {
	if resp.MoreResults != nil && !*resp.MoreResults {
		// the filter for the whole scan has been exhausted, close the scanner
		return true
	}

	if s.scannerID != noScannerID {
		// not done with this region yet
		return false
	}

	// Check to see if this region is the last we should scan because:
	// (1) it's the last region
	if len(region.StopKey()) == 0 && !s.rpc.Reversed() {
		return true
	}
	if s.rpc.Reversed() && len(region.StartKey()) == 0 {
		return true
	}
	// (3) because its stop_key is greater than or equal to the stop_key of this scanner,
	// provided that (2) we're not trying to scan until the end of the table.
	if !s.rpc.Reversed() {
		return len(s.rpc.StopRow()) != 0 && // (2)
			bytes.Compare(s.rpc.StopRow(), region.StopKey()) <= 0 // (3)
	}

	//  Reversed Scanner
	return len(s.rpc.StopRow()) != 0 && // (2)
		bytes.Compare(s.rpc.StopRow(), region.StartKey()) >= 0 // (3)
}
15023
func Retry(action Action, strategies ...strategy.Strategy) error {
	var err error

	for attempt := uint(0); (0 == attempt || nil != err) && shouldAttempt(attempt, strategies...); attempt++ {
		err = action(attempt)
	}

	return err
}
247333
func (tr *TaskRunner) shouldRestart() (bool, time.Duration) {
	// Determine if we should restart
	state, when := tr.restartTracker.GetState()
	reason := tr.restartTracker.GetReason()
	switch state {
	case structs.TaskKilled:
		// Never restart an explicitly killed task. Kill method handles
		// updating the server.
		tr.EmitEvent(structs.NewTaskEvent(state))
		return false, 0
	case structs.TaskNotRestarting, structs.TaskTerminated:
		tr.logger.Info("not restarting task", "reason", reason)
		if state == structs.TaskNotRestarting {
			tr.UpdateState(structs.TaskStateDead, structs.NewTaskEvent(structs.TaskNotRestarting).SetRestartReason(reason).SetFailsTask())
		}
		return false, 0
	case structs.TaskRestarting:
		tr.logger.Info("restarting task", "reason", reason, "delay", when)
		tr.UpdateState(structs.TaskStatePending, structs.NewTaskEvent(structs.TaskRestarting).SetRestartDelay(when).SetRestartReason(reason))
		return true, when
	default:
		tr.logger.Error("restart tracker returned unknown state", "state", state)
		return true, when
	}
}