github.com/xmidt-org/webpa-common@v1.11.9/store/value.go (about) 1 package store 2 3 // Value fronts an arbitrary object resulting from some nontrivial operation. 4 // For example, the parsed object resulting from a JSON message, or a secure 5 // key resulting from parsing a PEM block. 6 // 7 // This type is subtley different from atomic.Value. This Value type should be 8 // assumed to use an external resource or some complex algorithm in order to obtain its values. 9 // That's why Load() returns an error secondary parameter. 10 type Value interface { 11 // Load returns the value object. The mechanism used to obtain the value can 12 // be arbitrarily complex and might fail. For example, an external resource 13 // such as an http server might be consulted. 14 Load() (interface{}, error) 15 } 16 17 // ValueFunc is a function type that implements Value 18 type ValueFunc func() (interface{}, error) 19 20 func (v ValueFunc) Load() (interface{}, error) { 21 return v() 22 } 23 24 // singleton is an internal Value implementation that returns the same 25 // value all the time. It's primarily used when NewValue() is called 26 // with CachePeriodForever. 27 type singleton struct { 28 value interface{} 29 } 30 31 func (s *singleton) Load() (interface{}, error) { 32 return s.value, nil 33 } 34 35 // NewValue creates a dynamic implementation of Value based on the period 36 // parameter. 37 // 38 // If period is 0 (CachePeriodForever), this function will immediately attempt 39 // to invoke source.Load() and return a singleton Value. If source.Load() fails, 40 // this function returns nil plus that error. 41 func NewValue(source Value, period CachePeriod) (Value, error) { 42 if period == CachePeriodForever { 43 if once, err := source.Load(); err != nil { 44 return nil, err 45 } else { 46 return &singleton{once}, nil 47 } 48 } else if period < 0 { 49 // never cache ... so just return the source 50 return source, nil 51 } 52 53 return NewCache(source, period) 54 }