github.com/volts-dev/volts@v0.0.0-20240120094013-5e9c65924106/selector/selector.go (about) 1 package selector 2 3 import ( 4 "errors" 5 6 "github.com/volts-dev/volts/logger" 7 "github.com/volts-dev/volts/registry" 8 ) 9 10 var ( 11 defaultSelector ISelector //New() 12 log = logger.New("selector") 13 ErrNotFound = errors.New("not found") 14 ErrNoneAvailable = errors.New("service none available") 15 ) 16 17 type ( 18 // Selector builds on the registry as a mechanism to pick nodes 19 // and mark their status. This allows host pools and other things 20 // to be built using various algorithms. 21 ISelector interface { 22 Init(opts ...Option) error 23 Config() *Config 24 Match(endpoint string, opts ...SelectOption) (Next, error) 25 // Select returns a function which should return the next node 26 Select(service string, opts ...SelectOption) (Next, error) 27 // Mark sets the success/error against a node 28 Mark(service string, node *registry.Node, err error) 29 // Reset returns state back to zero for a service 30 Reset(service string) 31 // Close renders the selector unusable 32 Close() error 33 // Name of the selector 34 String() string 35 } 36 37 // Next is a function that returns the next node 38 // based on the selector's strategy 39 Next func() (*registry.Node, error) 40 41 // Filter is used to filter a service during the selection process 42 Filter func([]*registry.Service) []*registry.Service 43 44 // Strategy is a selection strategy e.g random, round robin 45 Strategy func([]*registry.Service) Next 46 ) 47 48 func New(opts ...Option) ISelector { 49 s := ®istrySelector{ 50 config: newConfig(opts...), 51 } 52 s.rc = s.newCache() 53 54 return s 55 } 56 57 func Default(new ...ISelector) ISelector { 58 if new != nil { 59 defaultSelector = new[0] 60 } else if defaultSelector == nil { 61 defaultSelector = New() 62 } 63 64 return defaultSelector 65 }