amocrm/internal/workers/limiter/limiter.go

59 lines
1.0 KiB
Go
Raw Normal View History

2024-04-22 07:49:46 +00:00
package limiter
2024-04-10 10:53:19 +00:00
import (
"context"
"sync"
"time"
)
type RateLimiter struct {
requests chan struct{}
done chan struct{}
maxRequests int
2024-04-22 07:49:46 +00:00
Interval time.Duration
2024-04-10 10:53:19 +00:00
mutex sync.Mutex
}
func NewRateLimiter(ctx context.Context, maxRequests int, interval time.Duration) *RateLimiter {
limiter := &RateLimiter{
requests: make(chan struct{}, maxRequests),
done: make(chan struct{}),
maxRequests: maxRequests,
2024-04-22 07:49:46 +00:00
Interval: interval,
2024-04-10 10:53:19 +00:00
}
go limiter.start(ctx)
return limiter
}
func (limiter *RateLimiter) start(ctx context.Context) {
2024-04-22 07:49:46 +00:00
ticker := time.NewTicker(limiter.Interval)
2024-04-10 10:53:19 +00:00
defer ticker.Stop()
for {
select {
case <-ticker.C:
limiter.mutex.Lock()
for i := 0; i < len(limiter.requests); i++ {
<-limiter.requests
}
limiter.mutex.Unlock()
case <-ctx.Done():
return
}
}
}
func (limiter *RateLimiter) Check() bool {
select {
case limiter.requests <- struct{}{}:
return true
default:
return false
}
}
2024-05-06 20:35:08 +00:00
func (limiter *RateLimiter) Stop(_ context.Context) error {
2024-04-10 10:53:19 +00:00
return nil
}