filter.go 767 B

123456789101112131415161718192021222324252627282930313233
  1. package eventbus
  2. import (
  3. "sync"
  4. "time"
  5. )
  6. // RateLimiter prevents notification spam from flapping events.
  7. type RateLimiter struct {
  8. mu sync.Mutex
  9. lastSent map[string]time.Time
  10. cooldown time.Duration
  11. }
  12. // NewRateLimiter creates a rate limiter with the given cooldown period.
  13. func NewRateLimiter(cooldown time.Duration) *RateLimiter {
  14. return &RateLimiter{
  15. lastSent: make(map[string]time.Time),
  16. cooldown: cooldown,
  17. }
  18. }
  19. // Allow returns true if the event should be sent (cooldown has elapsed).
  20. func (r *RateLimiter) Allow(eventType EventType, source string) bool {
  21. key := string(eventType) + ":" + source
  22. r.mu.Lock()
  23. defer r.mu.Unlock()
  24. if time.Since(r.lastSent[key]) < r.cooldown {
  25. return false
  26. }
  27. r.lastSent[key] = time.Now()
  28. return true
  29. }