github.com/viant/toolbox@v0.34.5/sampler/service.go (about)

     1  package sampler
     2  
     3  import (
     4  	"math/rand"
     5  	"sync"
     6  	"time"
     7  )
     8  
     9  //Service represents a sampler service
    10  type Service struct {
    11  	rand            *rand.Rand
    12  	acceptThreshold int32
    13  	mux             sync.Mutex
    14  	PCT             float64
    15  }
    16  
    17  //Accept accept sample meeting accept gaol PCT
    18  func (s *Service) Accept() bool {
    19  	s.mux.Lock()
    20  	defer s.mux.Unlock()
    21  	n := s.rand.Int31n(100000)
    22  	return n < s.acceptThreshold
    23  }
    24  
    25  //Accept accept with threshold with PCT being ignored (same as PCT=100)
    26  func (s *Service) AcceptWithThreshold(threshold float64) bool {
    27  	s.mux.Lock()
    28  	defer s.mux.Unlock()
    29  	n := s.rand.Int31n(100000)
    30  	return n < int32(threshold*1000.0)
    31  }
    32  
    33  //New creates a pct sampler
    34  func New(acceptPCT float64) *Service {
    35  	source := rand.NewSource(time.Now().UnixNano())
    36  	return &Service{
    37  		PCT:             acceptPCT,
    38  		rand:            rand.New(source),
    39  		acceptThreshold: int32(acceptPCT * 1000.0),
    40  	}
    41  }