1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
14 var requestLimiterQuietPeriod = time.Second
16 type requestLimiter struct {
24 // Acquire reserves one request slot, waiting if necessary.
26 // Acquire returns early if ctx cancels before a slot is available. It
27 // is assumed in this case the caller will immediately notice
28 // ctx.Err() != nil and call Release().
29 func (rl *requestLimiter) Acquire(ctx context.Context) {
32 // First use of requestLimiter. Initialize.
33 rl.cond = sync.NewCond(&rl.lock)
35 // Wait out the quiet period(s) immediately following a 503.
36 for ctx.Err() == nil {
37 delay := rl.quietUntil.Sub(time.Now())
41 // Wait for the end of the quiet period, which started
42 // when we last received a 503 response.
44 timer := time.NewTimer(delay)
52 ready := make(chan struct{})
54 // close ready when a slot is available _or_ we wake
55 // up and find ctx has been canceled (meaning Acquire
56 // has already returned, or is about to).
57 for rl.limit > 0 && rl.limit <= rl.current && ctx.Err() == nil {
64 // Wait() returned, so we have the lock.
68 // When Wait() returns the lock to our goroutine
69 // (which might have already happened) we need to
70 // release it (if we don't do this now, the following
71 // Lock() can deadlock).
76 // Note we may have current > limit until the caller
84 // Release releases a slot that has been reserved with Acquire.
85 func (rl *requestLimiter) Release() {
92 // Report uses the return values from (*http.Client)Do() to adjust the
93 // outgoing request limit (increase on success, decrease on 503).
94 func (rl *requestLimiter) Report(resp *http.Response, err error) {
99 defer rl.lock.Unlock()
100 if resp.StatusCode == http.StatusServiceUnavailable {
102 // Concurrency was unlimited until now.
103 // Calculate new limit based on actual
104 // concurrency instead of previous limit.
105 rl.limit = rl.current
107 if time.Now().After(rl.quietUntil) {
108 // Reduce concurrency limit by half.
109 rl.limit = (rl.limit + 1) / 2
110 // Don't start any new calls (or reduce the
111 // limit even further on additional 503s) for
113 rl.quietUntil = time.Now().Add(requestLimiterQuietPeriod)
115 } else if resp.StatusCode >= 200 && resp.StatusCode < 400 && rl.limit > 0 {
116 // After each non-server-error response, increase
117 // concurrency limit by at least 10% -- but not beyond
118 // 2x the highest concurrency level we've seen without
120 increase := rl.limit / 10
125 if max := rl.current * 2; max > rl.limit {