-
-
Notifications
You must be signed in to change notification settings - Fork 794
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Philipp Heckel
committed
Nov 1, 2021
1 parent
5f2bb4f
commit fa7a459
Showing
3 changed files
with
97 additions
and
37 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
package server | ||
|
||
import ( | ||
"golang.org/x/time/rate" | ||
"heckel.io/ntfy/config" | ||
"sync" | ||
"time" | ||
) | ||
|
||
const ( | ||
visitorExpungeAfter = 30 * time.Minute | ||
) | ||
|
||
// visitor represents an API user, and its associated rate.Limiter used for rate limiting | ||
type visitor struct { | ||
config *config.Config | ||
limiter *rate.Limiter | ||
subscriptions int | ||
seen time.Time | ||
mu sync.Mutex | ||
} | ||
|
||
func newVisitor(conf *config.Config) *visitor { | ||
return &visitor{ | ||
config: conf, | ||
limiter: rate.NewLimiter(conf.RequestLimit, conf.RequestLimitBurst), | ||
seen: time.Now(), | ||
} | ||
} | ||
|
||
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() | ||
if v.subscriptions >= v.config.SubscriptionLimit { | ||
return errHTTPTooManyRequests | ||
} | ||
v.subscriptions++ | ||
return nil | ||
} | ||
|
||
func (v *visitor) RemoveSubscription() { | ||
v.mu.Lock() | ||
defer v.mu.Unlock() | ||
v.subscriptions-- | ||
} | ||
|
||
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() | ||
v.seen = time.Now() | ||
return time.Since(v.seen) > visitorExpungeAfter | ||
} |