ntfy/server/visitor.go

65 lines
1.3 KiB
Go
Raw Normal View History

2021-11-02 08:21:38 +13:00
package server
import (
"golang.org/x/time/rate"
2021-11-02 09:39:40 +13:00
"heckel.io/ntfy/util"
2021-11-02 08:21:38 +13:00
"sync"
"time"
)
const (
visitorExpungeAfter = 30 * time.Minute
)
// visitor represents an API user, and its associated rate.Limiter used for rate limiting
type visitor struct {
2021-12-19 16:02:36 +13:00
config *Config
2021-11-02 08:21:38 +13:00
limiter *rate.Limiter
2021-11-02 09:39:40 +13:00
subscriptions *util.Limiter
2021-11-02 08:21:38 +13:00
seen time.Time
mu sync.Mutex
}
2021-12-19 16:02:36 +13:00
func newVisitor(conf *Config) *visitor {
2021-11-02 08:21:38 +13:00
return &visitor{
2021-11-02 09:39:40 +13:00
config: conf,
limiter: rate.NewLimiter(rate.Every(conf.VisitorRequestLimitReplenish), conf.VisitorRequestLimitBurst),
2021-11-02 09:39:40 +13:00
subscriptions: util.NewLimiter(int64(conf.VisitorSubscriptionLimit)),
seen: time.Now(),
2021-11-02 08:21:38 +13:00
}
}
func (v *visitor) RequestAllowed() error {
if !v.limiter.Allow() {
return errHTTPTooManyRequests
}
return nil
}
func (v *visitor) AddSubscription() error {
v.mu.Lock()
defer v.mu.Unlock()
2021-11-02 09:39:40 +13:00
if err := v.subscriptions.Add(1); err != nil {
2021-11-02 08:21:38 +13:00
return errHTTPTooManyRequests
}
return nil
}
func (v *visitor) RemoveSubscription() {
v.mu.Lock()
defer v.mu.Unlock()
2021-11-02 09:39:40 +13:00
v.subscriptions.Sub(1)
2021-11-02 08:21:38 +13:00
}
func (v *visitor) Keepalive() {
v.mu.Lock()
defer v.mu.Unlock()
v.seen = time.Now()
}
func (v *visitor) Stale() bool {
v.mu.Lock()
defer v.mu.Unlock()
return time.Since(v.seen) > visitorExpungeAfter
}