github.com/mailru/activerecord@v1.12.2/pkg/tarantool/options.go (about) 1 package tarantool 2 3 import ( 4 "fmt" 5 "hash/crc32" 6 "time" 7 8 "github.com/mailru/activerecord/pkg/activerecord" 9 "github.com/tarantool/go-tarantool" 10 ) 11 12 const DefaultConnectionTimeout = 20 * time.Millisecond 13 14 type ConnectionOptions struct { 15 *activerecord.GroupHash 16 cfg tarantool.Opts 17 server string 18 Mode activerecord.ServerModeType 19 } 20 21 type ConnectionOption interface { 22 apply(*ConnectionOptions) error 23 } 24 25 type optionConnectionFunc func(*ConnectionOptions) error 26 27 func (o optionConnectionFunc) apply(c *ConnectionOptions) error { 28 return o(c) 29 } 30 31 // WithTimeout - опция для изменений таймаутов 32 func WithTimeout(request time.Duration) ConnectionOption { 33 return optionConnectionFunc(func(opts *ConnectionOptions) error { 34 opts.cfg.Timeout = request 35 36 return opts.UpdateHash("T", request) 37 }) 38 } 39 40 // WithCredential - опция авторизации 41 func WithCredential(user, pass string) ConnectionOption { 42 return optionConnectionFunc(func(opts *ConnectionOptions) error { 43 opts.cfg.User = user 44 opts.cfg.Pass = pass 45 46 return opts.UpdateHash("L", user, pass) 47 }) 48 } 49 50 func NewOptions(server string, mode activerecord.ServerModeType, opts ...ConnectionOption) (*ConnectionOptions, error) { 51 if server == "" { 52 return nil, fmt.Errorf("invalid param: server is empty") 53 } 54 55 connectionOpts := &ConnectionOptions{ 56 cfg: tarantool.Opts{ 57 Timeout: DefaultConnectionTimeout, 58 }, 59 server: server, 60 Mode: mode, 61 } 62 63 connectionOpts.GroupHash = activerecord.NewGroupHash(crc32.NewIEEE()) 64 65 for _, opt := range opts { 66 if err := opt.apply(connectionOpts); err != nil { 67 return nil, fmt.Errorf("error apply options: %w", err) 68 } 69 } 70 71 err := connectionOpts.UpdateHash("S", server) 72 if err != nil { 73 return nil, fmt.Errorf("can't get pool: %w", err) 74 } 75 76 return connectionOpts, nil 77 } 78 79 func (c *ConnectionOptions) GetConnectionID() string { 80 return c.GetHash() 81 } 82 83 func (c *ConnectionOptions) InstanceMode() activerecord.ServerModeType { 84 return c.Mode 85 }