2022-07-16 14:28:00 +00:00
|
|
|
package rate5
|
|
|
|
|
2022-12-18 10:38:43 +00:00
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"sync/atomic"
|
|
|
|
)
|
2022-07-16 14:28:00 +00:00
|
|
|
|
|
|
|
func (q *Limiter) debugPrintf(format string, a ...interface{}) {
|
2022-12-18 10:38:43 +00:00
|
|
|
if atomic.CompareAndSwapUint32(&q.debug, DebugDisabled, DebugDisabled) {
|
2022-07-16 14:28:00 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
msg := fmt.Sprintf(format, a...)
|
|
|
|
select {
|
|
|
|
case q.debugChannel <- msg:
|
2022-12-18 10:38:43 +00:00
|
|
|
//
|
2022-07-16 14:28:00 +00:00
|
|
|
default:
|
2022-12-18 10:38:43 +00:00
|
|
|
// drop the message but increment the lost counter
|
|
|
|
atomic.AddInt64(&q.debugLost, 1)
|
2022-07-16 14:28:00 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (q *Limiter) setDebugEvict() {
|
|
|
|
q.Patrons.OnEvicted(func(src string, count interface{}) {
|
|
|
|
q.debugPrintf("ratelimit (expired): %s | last count [%d]", src, count)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func (q *Limiter) SetDebug(on bool) {
|
2022-12-18 10:38:43 +00:00
|
|
|
switch on {
|
|
|
|
case true:
|
|
|
|
atomic.CompareAndSwapUint32(&q.debug, DebugDisabled, DebugEnabled)
|
|
|
|
q.debugPrintf("rate5 debug enabled")
|
|
|
|
case false:
|
|
|
|
atomic.CompareAndSwapUint32(&q.debug, DebugEnabled, DebugDisabled)
|
2022-07-16 14:28:00 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// DebugChannel enables debug mode and returns a channel where debug messages are sent.
|
2022-12-18 10:38:43 +00:00
|
|
|
//
|
|
|
|
// NOTE: If you do not read from this channel, the debug messages will eventually be lost.
|
|
|
|
// If this happens,
|
2022-07-16 14:28:00 +00:00
|
|
|
func (q *Limiter) DebugChannel() chan string {
|
|
|
|
defer func() {
|
2022-12-18 10:38:43 +00:00
|
|
|
atomic.CompareAndSwapUint32(&q.debug, DebugDisabled, DebugEnabled)
|
2022-07-16 14:28:00 +00:00
|
|
|
}()
|
|
|
|
q.debugMutex.RLock()
|
|
|
|
if q.debugChannel != nil {
|
|
|
|
q.debugMutex.RUnlock()
|
|
|
|
return q.debugChannel
|
|
|
|
}
|
|
|
|
q.debugMutex.RUnlock()
|
|
|
|
q.debugMutex.Lock()
|
|
|
|
defer q.debugMutex.Unlock()
|
2022-12-18 10:38:43 +00:00
|
|
|
q.debugChannel = make(chan string, 55)
|
2022-07-16 14:28:00 +00:00
|
|
|
q.setDebugEvict()
|
|
|
|
return q.debugChannel
|
|
|
|
}
|