web console

This commit is contained in:
TenderIronh
2022-02-03 23:43:28 +08:00
parent 7686af39e0
commit 95b46f51d0
17 changed files with 406 additions and 343 deletions
+19 -19
View File
@@ -7,39 +7,39 @@ import (
// BandwidthLimiter ...
type BandwidthLimiter struct {
freeFlowTime time.Time
bandwidth int // mbps
freeFlow int // bytes
maxFreeFlow int // bytes
freeFlowMtx sync.Mutex
ts time.Time
bw int // mbps
freeBytes int // bytes
maxFreeBytes int // bytes
mtx sync.Mutex
}
// mbps
func newBandwidthLimiter(bw int) *BandwidthLimiter {
return &BandwidthLimiter{
bandwidth: bw,
freeFlowTime: time.Now(),
maxFreeFlow: bw * 1024 * 1024 / 8,
freeFlow: bw * 1024 * 1024 / 8,
bw: bw,
ts: time.Now(),
maxFreeBytes: bw * 1024 * 1024 / 8,
freeBytes: bw * 1024 * 1024 / 8,
}
}
// Add ...
func (bl *BandwidthLimiter) Add(bytes int) {
if bl.bandwidth <= 0 {
if bl.bw <= 0 {
return
}
bl.freeFlowMtx.Lock()
defer bl.freeFlowMtx.Unlock()
bl.mtx.Lock()
defer bl.mtx.Unlock()
// calc free flow 1000*1000/1024/1024=0.954; 1024*1024/1000/1000=1.048
bl.freeFlow += int(time.Now().Sub(bl.freeFlowTime) * time.Duration(bl.bandwidth) / 8 / 954)
if bl.freeFlow > bl.maxFreeFlow {
bl.freeFlow = bl.maxFreeFlow
bl.freeBytes += int(time.Since(bl.ts) * time.Duration(bl.bw) / 8 / 954)
if bl.freeBytes > bl.maxFreeBytes {
bl.freeBytes = bl.maxFreeBytes
}
bl.freeFlow -= bytes
bl.freeFlowTime = time.Now()
if bl.freeFlow < 0 {
bl.freeBytes -= bytes
bl.ts = time.Now()
if bl.freeBytes < 0 {
// sleep for the overflow
time.Sleep(time.Millisecond * time.Duration(-bl.freeFlow/(bl.bandwidth*1048/8)))
time.Sleep(time.Millisecond * time.Duration(-bl.freeBytes/(bl.bw*1048/8)))
}
}