-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathcoverage.html
580 lines (495 loc) · 18.2 KB
/
coverage.html
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>ratelimiter: Go Coverage Report</title>
<style>
body {
background: black;
color: rgb(80, 80, 80);
}
body, pre, #legend span {
font-family: Menlo, monospace;
font-weight: bold;
}
#topbar {
background: black;
position: fixed;
top: 0; left: 0; right: 0;
height: 42px;
border-bottom: 1px solid rgb(80, 80, 80);
}
#content {
margin-top: 50px;
}
#nav, #legend {
float: left;
margin-left: 10px;
}
#legend {
margin-top: 12px;
}
#nav {
margin-top: 10px;
}
#legend span {
margin: 0 5px;
}
.cov0 { color: rgb(192, 0, 0) }
.cov1 { color: rgb(128, 128, 128) }
.cov2 { color: rgb(116, 140, 131) }
.cov3 { color: rgb(104, 152, 134) }
.cov4 { color: rgb(92, 164, 137) }
.cov5 { color: rgb(80, 176, 140) }
.cov6 { color: rgb(68, 188, 143) }
.cov7 { color: rgb(56, 200, 146) }
.cov8 { color: rgb(44, 212, 149) }
.cov9 { color: rgb(32, 224, 152) }
.cov10 { color: rgb(20, 236, 155) }
</style>
</head>
<body>
<div id="topbar">
<div id="nav">
<select id="files">
<option value="file0">github.com/Narasimha1997/ratelimiter/attribute_limiter.go (93.6%)</option>
<option value="file1">github.com/Narasimha1997/ratelimiter/limiter.go (100.0%)</option>
<option value="file2">github.com/Narasimha1997/ratelimiter/window.go (100.0%)</option>
</select>
</div>
<div id="legend">
<span>not tracked</span>
<span class="cov0">not covered</span>
<span class="cov8">covered</span>
</div>
</div>
<div id="content">
<pre class="file" id="file0" style="display: none">package ratelimiter
import (
"fmt"
"sync"
"time"
)
// AttributeMap is a custom map type of string key and Limiter instance as value
type AttributeMap map[string]Limiter
// AttributeBasedLimiter is an instance that can manage multiple rate limiter instances
// with different configutations.
type AttributeBasedLimiter struct {
attributeMap AttributeMap
m sync.Mutex
syncMode bool
}
// HasKey check if AttributeBasedLimiter has a limiter for the key.
//
// Parameters:
//
// 1. key: a unique key string, example: IP address, token, uuid etc
//
// Returns a boolean flag, if true, the key is already present, false otherwise.
func (a *AttributeBasedLimiter) HasKey(key string) bool <span class="cov8" title="1">{
a.m.Lock()
_, ok := a.attributeMap[key]
a.m.Unlock()
return ok
}</span>
// CreateNewKey create a new key-limiter assiociation.
//
// Parameters:
//
// 1. key: a unique key string, example: IP address, token, uuid etc
//
// 2. limit: The number of tasks to be allowd
//
// 3. size: duration
//
// Returns error if the key already exists.
func (a *AttributeBasedLimiter) CreateNewKey(key string, limit uint64, size time.Duration) error <span class="cov8" title="1">{
a.m.Lock()
defer a.m.Unlock()
return a.createNewKey(key, limit, size)
}</span>
func (a *AttributeBasedLimiter) createNewKey(key string, limit uint64, size time.Duration) error <span class="cov8" title="1">{
if _, ok := a.attributeMap[key]; ok </span><span class="cov8" title="1">{
return fmt.Errorf(
"key %s is already defined", key,
)
}</span>
// create a new entry:
<span class="cov8" title="1">if !a.syncMode </span><span class="cov8" title="1">{
a.attributeMap[key] = NewDefaultLimiter(limit, size)
}</span> else<span class="cov8" title="1"> {
a.attributeMap[key] = NewSyncLimiter(limit, size)
}</span>
<span class="cov8" title="1">return nil</span>
}
// HasOrCreateKey check if AttributeBasedLimiter has a limiter for the key.
// Create a new key-limiter assiociation if the key not exists.
//
// Parameters:
//
// 1. key: a unique key string, example: IP address, token, uuid etc
//
// 2. limit: The number of tasks to be allowd
//
// 3. size: duration
//
// Return true if the key exists or is created successfully.
func (a *AttributeBasedLimiter) HasOrCreateKey(key string, limit uint64, size time.Duration) bool <span class="cov8" title="1">{
a.m.Lock()
defer a.m.Unlock()
if _, ok := a.attributeMap[key]; ok </span><span class="cov8" title="1">{
return true
}</span>
<span class="cov8" title="1">if err := a.createNewKey(key, limit, size); err == nil </span><span class="cov8" title="1">{
return true
}</span>
<span class="cov0" title="0">return false</span>
}
// ShouldAllow makes decison whether n tasks can be allowed or not.
//
// Parameters:
//
// key: a unique key string, example: IP address, token, uuid etc
//
// n: number of tasks to be processed, set this as 1 for a single task.
// (Example: An HTTP request)
//
// Returns (bool, error).
// (false, error) when limiter is inactive (or it is killed) or key is not present.
// (true/false, nil) if key exists and n tasks can be allowed or not.
func (a *AttributeBasedLimiter) ShouldAllow(key string, n uint64) (bool, error) <span class="cov8" title="1">{
a.m.Lock()
defer a.m.Unlock()
limiter, ok := a.attributeMap[key]
if ok </span><span class="cov8" title="1">{
return limiter.ShouldAllow(n)
}</span>
<span class="cov8" title="1">return false, fmt.Errorf("key %s not found", key)</span>
}
// MustShouldAllow makes decison whether n tasks can be allowed or not.
//
// Parameters:
//
// key: a unique key string, example: IP address, token, uuid etc
//
// n: number of tasks to be processed, set this as 1 for a single task.
// (Example: An HTTP request)
//
// Returns bool.
// (false) when limiter is inactive (or it is killed) or n tasks can be not allowed.
// (true) when n tasks can be allowed or new key-limiter.
func (a *AttributeBasedLimiter) MustShouldAllow(key string, n uint64, limit uint64, size time.Duration) bool <span class="cov8" title="1">{
a.m.Lock()
defer a.m.Unlock()
if limiter, ok := a.attributeMap[key]; ok </span><span class="cov8" title="1">{
allowed, err := limiter.ShouldAllow(n)
return allowed && err == nil
}</span>
<span class="cov8" title="1">err := a.createNewKey(key, limit, size)
if err != nil </span><span class="cov0" title="0">{
return err == nil
}</span>
// check ratelimiter on newly created key:
<span class="cov8" title="1">limiter := a.attributeMap[key]
allowed, err := limiter.ShouldAllow(n)
return allowed && err == nil</span>
}
// DeleteKey remove the key and kill its underlying limiter.
//
// Parameters:
//
// 1.key: a unique key string, example: IP address, token, uuid etc
//
// Returns an error if the key is not present.
func (a *AttributeBasedLimiter) DeleteKey(key string) error <span class="cov8" title="1">{
a.m.Lock()
defer a.m.Unlock()
if limiter, ok := a.attributeMap[key]; ok </span><span class="cov8" title="1">{
err := limiter.Kill()
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov8" title="1">delete(a.attributeMap, key)
return nil</span>
}
<span class="cov8" title="1">return fmt.Errorf("key %s not found", key)</span>
}
// NewAttributeBasedLimiter creates an instance of AttributeBasedLimiter and returns it's pointer.
//
// Parameters:
//
// 1. backgroundSliding: if set to true, DefaultLimiter will be used as an underlying limiter,
// else, SyncLimiter will be used.
func NewAttributeBasedLimiter(backgroundSliding bool) *AttributeBasedLimiter <span class="cov8" title="1">{
return &AttributeBasedLimiter{
attributeMap: make(AttributeMap),
syncMode: !backgroundSliding,
}
}</span>
</pre>
<pre class="file" id="file1" style="display: none">package ratelimiter
import (
"context"
"fmt"
"sync"
"time"
)
// Limiter is an interface that is implemented by DefaultLimiter and SyncLimiter
type Limiter interface {
Kill() error
ShouldAllow(n uint64) (bool, error)
}
// DefaultLimiter maintains all the structures used for rate limting using a background goroutine.
type DefaultLimiter struct {
previous *Window
current *Window
lock sync.Mutex
size time.Duration
limit uint64
killed bool
windowContext context.Context
cancelFn func()
}
// ShouldAllow makes decison whether n tasks can be allowed or not.
//
// Parameters:
//
// 1. n: number of tasks to be processed, set this as 1 for a single task. (Example: An HTTP request)
//
// Returns (bool, error). (false, error) if limiter is inactive (or it is killed). Otherwise,
// (true/false, nil) depending on whether n tasks can be allowed or not.
func (l *DefaultLimiter) ShouldAllow(n uint64) (bool, error) <span class="cov8" title="1">{
l.lock.Lock()
defer l.lock.Unlock()
if l.killed </span><span class="cov8" title="1">{
return false, fmt.Errorf("function ShouldAllow called on an inactive instance")
}</span>
<span class="cov8" title="1">if l.limit == 0 || l.size < time.Millisecond </span><span class="cov8" title="1">{
return false, fmt.Errorf("invalid limiter configuration")
}</span>
<span class="cov8" title="1">currentTime := time.Now()
currentWindowBoundary := currentTime.Sub(l.current.getStartTime())
w := float64(l.size-currentWindowBoundary) / float64(l.size)
currentSlidingRequests := uint64(w*float64(l.previous.count)) + l.current.count
if currentSlidingRequests+n > l.limit </span><span class="cov8" title="1">{
return false, nil
}</span>
// add current request count to window of current count
<span class="cov8" title="1">l.current.updateCount(n)
return true, nil</span>
}
func (l *DefaultLimiter) progressiveWindowSlider() <span class="cov8" title="1">{
for </span><span class="cov8" title="1">{
select </span>{
case <-l.windowContext.Done():<span class="cov8" title="1">
return</span>
default:<span class="cov8" title="1">
toSleepDuration := l.size - time.Since(l.current.getStartTime())
time.Sleep(toSleepDuration)
l.lock.Lock()
// make current as previous and create a new current window
l.previous.setStateFrom(l.current)
l.current.resetToTime(time.Now())
l.lock.Unlock()</span>
}
}
}
// Kill the limiter, returns error if the limiter has been killed already.
func (l *DefaultLimiter) Kill() error <span class="cov8" title="1">{
l.lock.Lock()
defer l.lock.Unlock()
if l.killed </span><span class="cov8" title="1">{
return fmt.Errorf("called Kill on already killed limiter")
}</span>
<span class="cov8" title="1">defer l.cancelFn()
l.killed = true
return nil</span>
}
// NewDefaultLimiter creates an instance of DefaultLimiter and returns it's pointer.
//
// Parameters:
//
// 1. limit: The number of tasks to be allowd
//
// 2. size: duration
func NewDefaultLimiter(limit uint64, size time.Duration) *DefaultLimiter <span class="cov8" title="1">{
previous := NewWindow(0, time.Unix(0, 0))
current := NewWindow(0, time.Unix(0, 0))
childCtx, cancelFn := context.WithCancel(context.Background())
limiter := &DefaultLimiter{
previous: previous,
current: current,
lock: sync.Mutex{},
size: size,
limit: limit,
killed: false,
windowContext: childCtx,
cancelFn: cancelFn,
}
go limiter.progressiveWindowSlider()
return limiter
}</span>
// SyncLimiter maintains all the structures used for rate limting on demand.
type SyncLimiter struct {
previous *Window
current *Window
lock sync.Mutex
size time.Duration
limit uint64
killed bool
}
func (s *SyncLimiter) getNSlidesSince(now time.Time) (time.Duration, time.Time) <span class="cov8" title="1">{
sizeAlignedTime := now.Truncate(s.size)
timeSinceStart := sizeAlignedTime.Sub(s.current.getStartTime())
return timeSinceStart / s.size, sizeAlignedTime
}</span>
// ShouldAllow makes decison whether n tasks can be allowed or not.
//
// Parameters:
//
// 1. n: number of tasks to be processed, set this as 1 for a single task. (Example: An HTTP request)
//
// Returns (bool, error). (false, error) if limiter is inactive (or it is killed). Otherwise,
// (true/false, error) depending on whether n tasks can be allowed or not.
func (s *SyncLimiter) ShouldAllow(n uint64) (bool, error) <span class="cov8" title="1">{
s.lock.Lock()
defer s.lock.Unlock()
if s.killed </span><span class="cov8" title="1">{
return false, fmt.Errorf("function ShouldAllow called on an inactive instance")
}</span>
<span class="cov8" title="1">if s.limit == 0 || s.size < time.Millisecond </span><span class="cov8" title="1">{
return false, fmt.Errorf("invalid limiter configuration")
}</span>
<span class="cov8" title="1">currentTime := time.Now()
// advance the window on demand, as this doesn't make use of goroutine.
nSlides, alignedCurrentTime := s.getNSlidesSince(currentTime)
// window slide shares both current and previous windows.
if nSlides == 1 </span><span class="cov8" title="1">{
s.previous.setToState(
alignedCurrentTime.Add(-s.size),
s.current.count,
)
s.current.resetToTime(
alignedCurrentTime,
)
}</span> else<span class="cov8" title="1"> if nSlides > 1 </span><span class="cov8" title="1">{
s.previous.resetToTime(
alignedCurrentTime.Add(-s.size),
)
s.current.resetToTime(
alignedCurrentTime,
)
}</span>
<span class="cov8" title="1">currentWindowBoundary := currentTime.Sub(s.current.getStartTime())
w := float64(s.size-currentWindowBoundary) / float64(s.size)
currentSlidingRequests := uint64(w*float64(s.previous.count)) + s.current.count
if currentSlidingRequests+n > s.limit </span><span class="cov8" title="1">{
return false, nil
}</span>
// add current request count to window of current count
<span class="cov8" title="1">s.current.updateCount(n)
return true, nil</span>
}
// Kill the limiter, returns error if the limiter has been killed already.
func (s *SyncLimiter) Kill() error <span class="cov8" title="1">{
s.lock.Lock()
defer s.lock.Unlock()
if s.killed </span><span class="cov8" title="1">{
return fmt.Errorf("called Kill on already killed limiter")
}</span>
// kill is a dummy implementation for SyncLimiter,
// because there is no need of stopping a go-routine.
<span class="cov8" title="1">s.killed = true
return nil</span>
}
// NewSyncLimiter creates an instance of SyncLimiter and returns it's pointer.
//
// Parameters:
//
// 1. limit: The number of tasks to be allowd
//
// 2. size: duration
func NewSyncLimiter(limit uint64, size time.Duration) *SyncLimiter <span class="cov8" title="1">{
current := NewWindow(0, time.Unix(0, 0))
previous := NewWindow(0, time.Unix(0, 0))
return &SyncLimiter{
previous: previous,
current: current,
lock: sync.Mutex{},
killed: false,
size: size,
limit: limit,
}
}</span>
</pre>
<pre class="file" id="file2" style="display: none">package ratelimiter
import (
"time"
)
// Window represents the structure of timing-window at given point of time.
type Window struct {
count uint64
startTime time.Time
}
func (w *Window) updateCount(n uint64) <span class="cov8" title="1">{
w.count += n
}</span>
func (w *Window) getStartTime() time.Time <span class="cov8" title="1">{
return w.startTime
}</span>
func (w *Window) setStateFrom(other *Window) <span class="cov8" title="1">{
w.count = other.count
w.startTime = other.startTime
}</span>
func (w *Window) resetToTime(startTime time.Time) <span class="cov8" title="1">{
w.count = 0
w.startTime = startTime
}</span>
func (w *Window) setToState(startTime time.Time, count uint64) <span class="cov8" title="1">{
w.startTime = startTime
w.count = count
}</span>
// Creates and returns a pointer to the new Window instance.
//
// Parameters:
//
// 1. count: The initial count of the window.
//
// 2. startTime: The initial starting time of the window.
func NewWindow(count uint64, startTime time.Time) *Window <span class="cov8" title="1">{
return &Window{
count: count,
startTime: startTime,
}
}</span>
</pre>
</div>
</body>
<script>
(function() {
var files = document.getElementById('files');
var visible;
files.addEventListener('change', onChange, false);
function select(part) {
if (visible)
visible.style.display = 'none';
visible = document.getElementById(part);
if (!visible)
return;
files.value = part;
visible.style.display = 'block';
location.hash = part;
}
function onChange() {
select(files.value);
window.scrollTo(0, 0);
}
if (location.hash != "") {
select(location.hash.substr(1));
}
if (!visible) {
select("file0");
}
})();
</script>
</html>