feat(files): enable upload limiter
This commit is contained in:
parent
e01f5f8351
commit
fd5da3db37
5 changed files with 118 additions and 0 deletions
65
src/iolimiter/iolimiter.go
Normal file
65
src/iolimiter/iolimiter.go
Normal file
|
@ -0,0 +1,65 @@
|
|||
package iolimiter
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"github.com/ihexxa/quickshare/src/golimiter"
|
||||
"github.com/ihexxa/quickshare/src/userstore"
|
||||
)
|
||||
|
||||
const cacheSizeLimit = 1024
|
||||
|
||||
type ILimiter interface {
|
||||
CanUpload(id uint64, chunkSize int) (bool, error)
|
||||
}
|
||||
|
||||
type IOLimiter struct {
|
||||
mtx *sync.Mutex
|
||||
UploadLimiter *golimiter.Limiter
|
||||
users userstore.IUserStore
|
||||
quotaCache map[uint64]*userstore.Quota
|
||||
}
|
||||
|
||||
func NewIOLimiter(upCap, upCyc int, users userstore.IUserStore) *IOLimiter {
|
||||
return &IOLimiter{
|
||||
mtx: &sync.Mutex{},
|
||||
UploadLimiter: golimiter.New(upCap, upCyc),
|
||||
users: users,
|
||||
quotaCache: map[uint64]*userstore.Quota{},
|
||||
}
|
||||
}
|
||||
|
||||
func (lm *IOLimiter) CanUpload(id uint64, chunkSize int) (bool, error) {
|
||||
lm.mtx.Lock()
|
||||
defer lm.mtx.Unlock()
|
||||
|
||||
quota, ok := lm.quotaCache[id]
|
||||
if !ok {
|
||||
user, err := lm.users.GetUser(id)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
quota = user.Quota
|
||||
lm.quotaCache[id] = quota
|
||||
}
|
||||
if len(lm.quotaCache) > cacheSizeLimit {
|
||||
lm.clean()
|
||||
}
|
||||
|
||||
return lm.UploadLimiter.Access(
|
||||
fmt.Sprint(id),
|
||||
quota.UploadSpeedLimit,
|
||||
chunkSize,
|
||||
), nil
|
||||
}
|
||||
|
||||
func (lm *IOLimiter) clean() {
|
||||
count := 0
|
||||
for key := range lm.quotaCache {
|
||||
delete(lm.quotaCache, key)
|
||||
if count++; count > 5 {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue