throttle.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package scan
  2. import (
  3. "runtime"
  4. "github.com/zricethezav/gitleaks/v7/options"
  5. )
  6. const (
  7. singleThreadCommitBuffer = 1
  8. multiThreadCommitBufferMultiplier = 10
  9. )
  10. // Throttle is a struct that limits the number of concurrent goroutines and sets the
  11. // number of threads available for gitleaks to use via GOMAXPROCS.
  12. type Throttle struct {
  13. throttle chan bool
  14. }
  15. // NewThrottle accepts some options and returns a throttle for scanners to use
  16. func NewThrottle(opts options.Options) *Throttle {
  17. t := Throttle{}
  18. if opts.Threads <= 1 {
  19. runtime.GOMAXPROCS(1)
  20. t.throttle = make(chan bool, singleThreadCommitBuffer)
  21. return &t
  22. }
  23. runtime.GOMAXPROCS(opts.Threads)
  24. t.throttle = make(chan bool, multiThreadCommitBufferMultiplier*opts.Threads)
  25. return &t
  26. }
  27. // Limit blocks new goroutines from spinning up if throttle is at capacity
  28. func (t *Throttle) Limit() {
  29. t.throttle <- true
  30. }
  31. // Release releases the hold on the throttle, allowing more goroutines to be spun up
  32. func (t *Throttle) Release() {
  33. <-t.throttle
  34. }