44 lines
916 B
Go
44 lines
916 B
Go
package config
|
|
|
|
import (
|
|
"errors"
|
|
"sync/atomic"
|
|
)
|
|
|
|
var ErrInvalidStore = errors.New("invalid configuration store")
|
|
|
|
// Store publishes complete validated configurations with one atomic pointer swap.
|
|
type Store struct {
|
|
current atomic.Pointer[Config]
|
|
}
|
|
|
|
func NewStore(initial *Config) (*Store, error) {
|
|
if err := Validate(initial); err != nil {
|
|
return nil, errors.Join(ErrInvalidStore, err)
|
|
}
|
|
store := &Store{}
|
|
store.Publish(initial)
|
|
return store, nil
|
|
}
|
|
|
|
func (store *Store) Current() *Config {
|
|
if store == nil {
|
|
return nil
|
|
}
|
|
current := store.current.Load()
|
|
if current == nil {
|
|
return nil
|
|
}
|
|
cloned := cloneConfig(*current)
|
|
return &cloned
|
|
}
|
|
|
|
// Publish accepts a non-nil configuration already validated by the caller.
|
|
func (store *Store) Publish(configuration *Config) {
|
|
if store == nil || configuration == nil {
|
|
return
|
|
}
|
|
cloned := cloneConfig(*configuration)
|
|
store.current.Store(&cloned)
|
|
}
|