-
Notifications
You must be signed in to change notification settings - Fork 181
/
fakelag.go
86 lines (73 loc) · 2.15 KB
/
fakelag.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
// Copyright (c) 2018 Shivaram Lingamneni <slingamn@cs.stanford.edu>
// released under the MIT license
package irc
import (
"time"
)
// fakelag is a system for artificially delaying commands when a user issues
// them too rapidly
type FakelagState uint
const (
// initially, the client is "bursting" and can send n commands without
// encountering fakelag
FakelagBursting FakelagState = iota
// after that, they're "throttled" and we sleep in between commands until
// they're spaced sufficiently far apart
FakelagThrottled
)
// this is intentionally not threadsafe, because it should only be touched
// from the loop that accepts the client's input and runs commands
type Fakelag struct {
config FakelagConfig
nowFunc func() time.Time
sleepFunc func(time.Duration)
state FakelagState
burstCount uint // number of messages sent in the current burst
lastTouch time.Time
}
func (fl *Fakelag) Initialize(config FakelagConfig) {
fl.config = config
fl.nowFunc = time.Now
fl.sleepFunc = time.Sleep
fl.state = FakelagBursting
}
// register a new command, sleep if necessary to delay it
func (fl *Fakelag) Touch() {
if !fl.config.Enabled {
return
}
now := fl.nowFunc()
// XXX if lastTouch.IsZero(), treat it as "very far in the past", which is fine
elapsed := now.Sub(fl.lastTouch)
fl.lastTouch = now
if fl.state == FakelagBursting {
// determine if the previous burst is over
if elapsed > fl.config.Cooldown {
fl.burstCount = 0
}
fl.burstCount++
if fl.burstCount > fl.config.BurstLimit {
// reset burst window for next time
fl.burstCount = 0
// transition to throttling
fl.state = FakelagThrottled
// continue to throttling logic
} else {
return
}
}
if fl.state == FakelagThrottled {
if elapsed > fl.config.Cooldown {
// let them burst again
fl.state = FakelagBursting
return
}
// space them out by at least window/messagesperwindow
sleepDuration := time.Duration((int64(fl.config.Window) / int64(fl.config.MessagesPerWindow)) - int64(elapsed))
if sleepDuration > 0 {
fl.sleepFunc(sleepDuration)
// the touch time should take into account the time we slept
fl.lastTouch = fl.nowFunc()
}
}
}