-
Notifications
You must be signed in to change notification settings - Fork 3
/
codel.go
238 lines (186 loc) · 4.81 KB
/
codel.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
// Package codel implements the Controlled Delay
// (https://queue.acm.org/detail.cfm?id=2209336) algorithm for
// overload detection, providing a mechanism to shed load when
// overloaded. It optimizes for latency while keeping throughput high,
// even when downstream rates dynamically change.
// It keeps latency low when even severely overloaded, by preemptively
// shedding some load when wait latency is long. It is comparable to
// using a queue to handle bursts of load, but improves upon this
// technique by avoiding the latency required to handle all previous
// entries in the queue.
package codel
import (
"container/list"
"context"
"errors"
"math"
"sync"
"time"
)
// Dropped is the error that will be returned if this token is dropped
var Dropped = errors.New("dropped")
const (
interval = 10 * time.Millisecond
)
// rendezvouz is for returning context to the calling goroutine
type rendezvouz struct {
enqueuedTime time.Time
errChan chan error
}
func (r rendezvouz) Drop() {
select {
case r.errChan <- Dropped:
default:
}
}
func (r rendezvouz) Signal() {
close(r.errChan)
}
// Options are options to configure a Lock.
type Options struct {
MaxPending int // The maximum number of pending acquires
MaxOutstanding int // The maximum number of concurrent acquires
TargetLatency time.Duration // The target latency to wait for an acquire. Acquires that take longer than this can fail.
}
// Lock implements a FIFO lock with concurrency control, based upon the CoDel algorithm (https://queue.acm.org/detail.cfm?id=2209336).
type Lock struct {
mu sync.Mutex
target time.Duration
firstAboveTime time.Time
dropNext time.Time
droppedCount int64
dropping bool
waiters list.List
maxPending int64
outstanding int64
maxOutstanding int64
}
func New(opts Options) *Lock {
q := Lock{
target: opts.TargetLatency,
maxOutstanding: int64(opts.MaxOutstanding),
maxPending: int64(opts.MaxPending),
}
return &q
}
// Acquire a Lock with FIFO ordering, respecting the context. Returns an error it fails to acquire.
func (l *Lock) Acquire(ctx context.Context) error {
l.mu.Lock()
// Fast path if we are unblocked.
if l.outstanding < l.maxOutstanding && l.waiters.Len() == 0 {
l.outstanding++
l.mu.Unlock()
return nil
}
// If our queue is full, drop
if int64(l.waiters.Len()) == l.maxPending {
l.externalDrop()
l.mu.Unlock()
return Dropped
}
r := rendezvouz{
enqueuedTime: time.Now(),
errChan: make(chan error),
}
elem := l.waiters.PushBack(r)
l.mu.Unlock()
select {
case err := <-r.errChan:
return err
case <-ctx.Done():
err := ctx.Err()
l.mu.Lock()
select {
case err = <-r.errChan:
default:
l.waiters.Remove(elem)
l.externalDrop()
}
l.mu.Unlock()
return err
}
}
// Release a previously acquired lock.
func (l *Lock) Release() {
l.mu.Lock()
l.outstanding--
if l.outstanding < 0 {
l.mu.Unlock()
panic("lock: bad release")
}
l.deque()
l.mu.Unlock()
}
// Adjust the time based upon interval / sqrt(droppedCount)
func (l *Lock) controlLaw(t time.Time) time.Time {
return t.Add(time.Duration(float64(interval) / math.Sqrt(float64(l.droppedCount))))
}
// Pull a single instance off the queue. This should be
func (l *Lock) doDeque(now time.Time) (r rendezvouz, ok bool, okToDrop bool) {
next := l.waiters.Front()
if next == nil {
return rendezvouz{}, false, false
}
l.waiters.Remove(next)
r = next.Value.(rendezvouz)
sojurnDuration := now.Sub(r.enqueuedTime)
if sojurnDuration < l.target || l.waiters.Len() == 0 {
l.firstAboveTime = time.Time{}
} else if (l.firstAboveTime == time.Time{}) {
l.firstAboveTime = now.Add(interval)
} else if now.After(l.firstAboveTime) {
okToDrop = true
}
return r, true, okToDrop
}
// Signal that we couldn't write to the queue
func (l *Lock) externalDrop() {
l.dropping = true
l.droppedCount++
l.dropNext = l.controlLaw(l.dropNext)
}
// Pull instances off the queue until we no longer drop
func (l *Lock) deque() {
now := time.Now()
rendezvouz, ok, okToDrop := l.doDeque(now)
// The queue has no entries, so return
if !ok {
return
}
if !okToDrop {
l.dropping = false
l.outstanding++
rendezvouz.Signal()
return
}
if l.dropping {
for now.After(l.dropNext) && l.dropping {
rendezvouz.Drop()
rendezvouz, ok, okToDrop = l.doDeque(now)
if !ok {
return
}
l.droppedCount++
if !okToDrop {
l.dropping = false
} else {
l.dropNext = l.controlLaw(l.dropNext)
}
}
} else if now.Sub(l.dropNext) < interval || now.Sub(l.firstAboveTime) >= interval {
rendezvouz.Drop()
rendezvouz, ok, _ = l.doDeque(now)
if !ok {
return
}
l.dropping = true
if l.droppedCount > 2 {
l.droppedCount -= 2
} else {
l.droppedCount = 1
}
l.dropNext = l.controlLaw(now)
}
l.outstanding++
rendezvouz.Signal()
}