// ComputeDelayForRequest computes the delay required for a request, also
// updates internal state to count this request
487566
func (b *Backoff) ComputeDelayForRequest(now time.Time) time.Duration {
	b.mutex.Lock()
	defer b.mutex.Unlock()

	// Apply exponential decay to the counters
	timeDeltaSeconds := now.Unix() - b.lastDecay
	if timeDeltaSeconds > b.decayIntervalSeconds {
		intervals := float64(timeDeltaSeconds) / float64(b.decayIntervalSeconds)
		decay := float32(math.Pow(b.decayFraction, intervals))
		b.countErrorsRequestLimit *= decay
		b.countRequests *= decay
		b.lastDecay = now.Unix()
	}

	// Count this request
	b.countRequests += 1.0

	// Compute the failure rate
	errorFraction := float32(0.0)
	if b.countRequests > 0.5 {
		// Avoid tiny residuals & rounding errors
		errorFraction = b.countErrorsRequestLimit / b.countRequests
	}

	// Ignore a low fraction of errors
	// This also allows them to time-out
	if errorFraction < 0.1 {
		return time.Duration(0)
	}

	// Delay by the max delay multiplied by the recent error rate
	// (i.e. we apply a linear delay function)
	// TODO: This is pretty arbitrary
	delay := time.Nanosecond * time.Duration(float32(b.maxDelay.Nanoseconds())*errorFraction)
	// Round down to the nearest second for sanity
	return time.Second * time.Duration(int(delay.Seconds()))
}
1331281
func (m *MockLambdaAPI) CreateFunctionRequest(arg0 *lambda.CreateFunctionInput) (*request.Request, *lambda.FunctionConfiguration) {
	ret := m.ctrl.Call(m, "CreateFunctionRequest", arg0)
	ret0, _ := ret[0].(*request.Request)
	ret1, _ := ret[1].(*lambda.FunctionConfiguration)
	return ret0, ret1
}
500657
func (c *digisparkI2cConnection) UpdateDelay(duration uint) error {
	if !c.adaptor.i2c {
		return errors.New("Digispark i2c not initialized")
	}
	return c.adaptor.littleWire.i2cUpdateDelay(duration)
}
691983
func (svc *googleService) waitForOperationReady(operation string) error {
	return waitForOperation(OperationTimeout, func() (*googlecloud.Operation, error) {
		return svc.service.ZoneOperations.Get(svc.vm.Project, svc.vm.Zone, operation).Do()
	})
}
1323922
func (n *Node) NoReplyWait() error {
	return n.pool.Exec(nil, Query{ // nil = connection opts' timeout
		Type: p.Query_NOREPLY_WAIT,
	})
}
492761
func computeApproximateRequestSize(r *http.Request) int64 {
	s := 0
	if r.URL != nil {
		s += len(r.URL.String())
	}
	s += len(r.Method)
	s += len(r.Proto)
	s += len(r.Host)

	hs := 0
	for name, values := range r.Header {
		hs += len(name)
		for _, value := range values {
			hs += len(value)
		}
	}
	s += hs

	// N.B. r.Form and r.MultipartForm are assumed to be included in r.URL.

	var size int64
	size = int64(s)
	if r.ContentLength != -1 {
		size += r.ContentLength
	}
	log.Debug(nil, map[string]interface{}{
		"header_size": hs, "body_size": r.ContentLength, "req_size": size},
		"compute request size")
	return size
}
378947
func (m *podManager) waitRequest(request *cniserver.PodRequest) *cniserver.PodResult {
	return <-request.Result
}
619545
func (f *lightFetcher) nextRequest() (*distReq, uint64, bool) {
	var (
		bestHash    common.Hash
		bestAmount  uint64
		bestTd      *big.Int
		bestSyncing bool
	)
	bestHash, bestAmount, bestTd, bestSyncing = f.findBestRequest()

	if bestTd == f.maxConfirmedTd {
		return nil, 0, false
	}

	var rq *distReq
	reqID := genReqID()
	if bestSyncing {
		rq = f.newFetcherDistReqForSync(bestHash)
	} else {
		rq = f.newFetcherDistReq(bestHash, reqID, bestAmount)
	}
	return rq, reqID, bestSyncing
}
490246
func increaseDelay(oldDelay time.Duration, factor float64, min, max time.Duration) time.Duration {
	delay := time.Duration(float64(oldDelay) * factor)
	if delay < min {
		delay = min
	}
	if delay > max {
		delay = max
	}
	return delay
}
1199081
func (e *Element) WaitForReady() error {
	e.lock.RLock()
	ready := e.ready
	e.lock.RUnlock()

	if ready {
		return nil
	}

	timeout := time.NewTimer(e.tab.elementTimeout)
	defer timeout.Stop()

	select {
	case <-e.readyGate:
		return nil
	case <-timeout.C:
		return &ElementNotReadyErr{}
	}
}
1230843
func (s *Simulator) handleRequest(r task.Request) {
	dur := s.OnRequest(s, r)
	if dur <= 0 {
		panic("the invocation duration should be positive")
	}

	inv := &SimulatedInvocation{
		Request:  r,
		Created:  s.Now.Sub(s.Epoch),
		Duration: dur,
		Running:  true,
	}
	s.Invocations = append(s.Invocations, inv)

	s.nextInvID++
	id := s.nextInvID
	if s.invIDs == nil {
		s.invIDs = map[int64]*SimulatedInvocation{}
	}
	s.invIDs[id] = inv

	s.scheduleEvent(event{
		eta: s.Now.Add(inv.Duration),
		cb: func() {
			// On invocation completion, kick it from the active invocations set and
			// rerun the triggering policy function to decide what to do next.
			inv.Running = false
			delete(s.invIDs, id)
			s.triage()
		},
	})
}
1101761
func (p *EndpointPolicy) computeDesiredL4PolicyMapEntries(identityCache cache.IdentityCache) {

	if p.L4Policy == nil {
		return
	}
	p.computeDirectionL4PolicyMapEntries(identityCache, p.L4Policy.Ingress, trafficdirection.Ingress, p.DeniedIngressIdentities)
	p.computeDirectionL4PolicyMapEntries(identityCache, p.L4Policy.Egress, trafficdirection.Egress, p.DeniedEgressIdentities)
	return
}
1016860
func WithQuerySatelliteSyncWait(parent context.Context, value time.Duration) context.Context {
	return context.WithValue(contextOrBackground(parent), keyQueryOptSatSyncWait, value)
}
352414
func (m *MockLambdaAPI) InvokeRequest(arg0 *lambda.InvokeInput) (*request.Request, *lambda.InvokeOutput) {
	ret := m.ctrl.Call(m, "InvokeRequest", arg0)
	ret0, _ := ret[0].(*request.Request)
	ret1, _ := ret[1].(*lambda.InvokeOutput)
	return ret0, ret1
}
369013
func (brq *blockRetrievalQueue) request(ctx context.Context,
	priority int, kmd libkey.KeyMetadata, ptr data.BlockPointer, block data.Block,
	lifetime data.BlockCacheLifetime, action BlockRequestAction) <-chan error {
	brq.vlog.CLogf(ctx, libkb.VLog2,
		"Request of %v, action=%s, priority=%d", ptr, action, priority)

	// Only continue if we haven't been shut down
	brq.doneLock.RLock()
	defer brq.doneLock.RUnlock()

	ch := make(chan error, 1)
	select {
	case <-brq.doneCh:
		ch <- io.EOF
		if action.PrefetchTracked() {
			brq.Prefetcher().CancelPrefetch(ptr)
		}
		return ch
	default:
	}
	if block == nil {
		ch <- errors.New("nil block passed to blockRetrievalQueue.Request")
		if action.PrefetchTracked() {
			brq.Prefetcher().CancelPrefetch(ptr)
		}
		return ch
	}

	// Check caches before locking the mutex.
	prefetchStatus, err := brq.checkCaches(ctx, kmd, ptr, block, action)
	if err == nil {
		if action != BlockRequestSolo {
			brq.vlog.CLogf(
				ctx, libkb.VLog2, "Found %v in caches: %s", ptr, prefetchStatus)
		}
		if action.PrefetchTracked() {
			brq.Prefetcher().ProcessBlockForPrefetch(ctx, ptr, block, kmd,
				priority, lifetime, prefetchStatus, action)
		}
		ch <- nil
		return ch
	}
	err = checkDataVersion(brq.config, data.Path{}, ptr)
	if err != nil {
		if action.PrefetchTracked() {
			brq.Prefetcher().CancelPrefetch(ptr)
		}
		ch <- err
		return ch
	}

	bpLookup := blockPtrLookup{ptr, reflect.TypeOf(block)}

	brq.mtx.Lock()
	defer brq.mtx.Unlock()
	// We might have to retry if the context has been canceled.  This loop will
	// iterate a maximum of 2 times. It either hits the `break` statement at
	// the bottom on the first iteration, or the `continue` statement first
	// which causes it to `break` on the next iteration.
	var br *blockRetrieval
	for {
		exists := false
		br, exists = brq.ptrs[bpLookup]
		if !exists {
			// Add to the heap
			br = &blockRetrieval{
				blockPtr:       ptr,
				kmd:            kmd,
				index:          -1,
				priority:       priority,
				insertionOrder: brq.insertionCount,
				cacheLifetime:  lifetime,
				action:         action,
			}
			br.ctx, br.cancelFunc = NewCoalescingContext(ctx)
			brq.insertionCount++
			brq.ptrs[bpLookup] = br
			heap.Push(brq.heap, br)
			brq.notifyWorker(priority)
		} else {
			err := br.ctx.AddContext(ctx)
			if err == context.Canceled {
				// We need to delete the request pointer, but we'll still let
				// the existing request be processed by a worker.
				delete(brq.ptrs, bpLookup)
				continue
			}
		}
		break
	}
	if br.index == -1 {
		// Log newly-scheduled requests via the normal logger, so we
		// can understand why the bserver fetches certain blocks, and
		// be able to time the request from start to finish.
		brq.log.CDebugf(ctx,
			"Scheduling request of %v, action=%s, priority=%d",
			ptr, action, priority)
	}
	br.reqMtx.Lock()
	defer br.reqMtx.Unlock()
	br.requests = append(br.requests, &blockRetrievalRequest{
		block:  block,
		doneCh: ch,
	})
	if lifetime > br.cacheLifetime {
		br.cacheLifetime = lifetime
	}
	oldPriority := br.priority
	if priority > oldPriority {
		br.priority = priority
		// If the new request priority is higher, elevate the retrieval in the
		// queue.  Skip this if the request is no longer in the queue (which
		// means it's actively being processed).
		if br.index != -1 {
			heap.Fix(brq.heap, br.index)
			if (oldPriority < defaultOnDemandRequestPriority &&
				priority >= defaultOnDemandRequestPriority) ||
				(oldPriority <= throttleRequestPriority &&
					priority > throttleRequestPriority) {
				// We've crossed the priority threshold for a given
				// worker type, so we now need a worker for the new
				// priority level to pick up the request.  This means
				// that we might have up to two workers "activated"
				// per request. However, they won't leak because if a
				// worker sees an empty queue, it continues merrily
				// along.
				brq.notifyWorker(priority)
			}
		}
	}
	// Update the action if needed.
	brq.vlog.CLogf(
		ctx, libkb.VLog2, "Combining actions %s and %s", action, br.action)
	br.action = action.Combine(br.action)
	brq.vlog.CLogf(ctx, libkb.VLog2, "Got action %s", br.action)
	return ch
}
1124105
func (r Billing_Item_Virtual_DedicatedHost) GetCancellationRequests() (resp []datatypes.Billing_Item_Cancellation_Request, err error) {
	err = r.Session.DoRequest("SoftLayer_Billing_Item_Virtual_DedicatedHost", "getCancellationRequests", nil, &r.Options, &resp)
	return
}
269899
func (e *Endpoint) WaitForProxyCompletions(proxyWaitGroup *completion.WaitGroup) error {
	if proxyWaitGroup == nil {
		return nil
	}

	err := proxyWaitGroup.Context().Err()
	if err != nil {
		return fmt.Errorf("context cancelled before waiting for proxy updates: %s", err)
	}

	start := time.Now()

	e.getLogger().Debug("Waiting for proxy updates to complete...")
	err = proxyWaitGroup.Wait()
	if err != nil {
		return fmt.Errorf("proxy state changes failed: %s", err)
	}
	e.getLogger().Debug("Wait time for proxy updates: ", time.Since(start))

	return nil
}