github.com/geph-official/geph2@v0.22.6-0.20210211030601-f527cb59b0df/cmd/geph-exit/limitercache.go (about)

     1  package main
     2  
     3  import (
     4  	"math/rand"
     5  
     6  	lru "github.com/hashicorp/golang-lru"
     7  	log "github.com/sirupsen/logrus"
     8  	"golang.org/x/time/rate"
     9  )
    10  
    11  type limitFactory struct {
    12  	lcache *lru.Cache
    13  	limit  rate.Limit
    14  }
    15  
    16  func (lf *limitFactory) getLimiter(sessid string) *rate.Limiter {
    17  	limit := rate.Limit(float64(lf.limit) * (0.9 + rand.Float64()/5))
    18  	new := rate.NewLimiter(limit, 1024*1024)
    19  	prev, _, _ := lf.lcache.PeekOrAdd(sessid, new)
    20  	if prev != nil {
    21  		return prev.(*rate.Limiter)
    22  	}
    23  	log.Println("limit for sessid is", limit)
    24  	return new
    25  }
    26  
    27  func newLimitFactory(limit rate.Limit) *limitFactory {
    28  	l, _ := lru.New(65536)
    29  	return &limitFactory{
    30  		limit:  limit,
    31  		lcache: l,
    32  	}
    33  }
    34  
    35  var slowLimitFactory = newLimitFactory(100 * 1024)