-
-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathmodules.go
78 lines (69 loc) · 2.23 KB
/
modules.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
package instadm
import (
"time"
"github.com/sirupsen/logrus"
)
/* Quota manager */
// QuotaManager data
type QuotaManager struct {
// HourTimestamp: hourly timestamp used to handle hour limitations
HourTimestamp time.Time
// DayTimestamp: daily timestamp used to handle day limitations
DayTimestamp time.Time
// DmSent: quantity of dm sent in the last hour
DmSent int
// DmSentDay: quantity of dm sent in the last day
DmSentDay int
// MaxDmHour: maximum dm quantity per hour
MaxDmHour int `yaml:"dm_per_hour"`
// MaxDmDay: maximum dm quantity per day
MaxDmDay int `yaml:"dm_per_day"`
// Activated: quota manager activation boolean
Activated bool `yaml:"activated"`
}
// InitializeQuotaManager initialize Quota manager with user settings
func (qm *QuotaManager) InitializeQuotaManager() {
qm.HourTimestamp = time.Now()
qm.DayTimestamp = time.Now()
}
// ResetDailyQuotas reset daily dm counter and update timestamp
func (qm *QuotaManager) ResetDailyQuotas() {
qm.DmSentDay = 0
qm.DayTimestamp = time.Now()
}
// ResetHourlyQuotas reset hourly dm counter and update timestamp
func (qm *QuotaManager) ResetHourlyQuotas() {
qm.DmSent = 0
qm.HourTimestamp = time.Now()
}
// AddDm report to the manager a message sending. It increment dm counter and check if quotas are still valid.
func (qm *QuotaManager) AddDm() {
qm.DmSent++
qm.DmSentDay++
qm.CheckQuotas()
}
// CheckQuotas check if quotas have not been exceeded and pauses the program otherwise.
func (qm *QuotaManager) CheckQuotas() {
// Hourly quota checking
if qm.DmSent >= qm.MaxDmHour {
if time.Since(qm.HourTimestamp).Seconds() < 3600 {
sleepDur := 3600 - time.Since(qm.HourTimestamp).Seconds()
logrus.Infof("Hourly quota reached, sleeping %f seconds...", sleepDur)
time.Sleep(time.Duration(sleepDur) * time.Second)
} else {
qm.ResetHourlyQuotas()
logrus.Info("Hourly quotas resetted.")
}
}
// Daily quota checking
if qm.DmSentDay >= qm.MaxDmDay {
if time.Since(qm.DayTimestamp).Seconds() < 86400 {
sleepDur := 86400 - time.Since(qm.DayTimestamp).Seconds()
logrus.Infof("Daily quota reached, sleeping %d seconds...", sleepDur)
time.Sleep(time.Duration(sleepDur) * time.Second)
} else {
qm.ResetDailyQuotas()
logrus.Info("Daily quotas resetted.")
}
}
}