You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
kratos/config/reader.go

170 lines
3.7 KiB

4 years ago
package config
import (
"bytes"
"encoding/gob"
"encoding/json"
4 years ago
"fmt"
"strings"
"sync"
4 years ago
"github.com/go-kratos/kratos/v2/log"
4 years ago
"github.com/imdario/mergo"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
4 years ago
)
// Reader is config reader.
type Reader interface {
Merge(...*KeyValue) error
Value(string) (Value, bool)
Source() ([]byte, error)
Resolve() error
4 years ago
}
type reader struct {
opts options
values map[string]interface{}
lock sync.Mutex
4 years ago
}
func newReader(opts options) Reader {
return &reader{
opts: opts,
values: make(map[string]interface{}),
lock: sync.Mutex{},
4 years ago
}
}
func (r *reader) Merge(kvs ...*KeyValue) error {
r.lock.Lock()
4 years ago
merged, err := cloneMap(r.values)
r.lock.Unlock()
4 years ago
if err != nil {
return err
}
for _, kv := range kvs {
next := make(map[string]interface{})
if err := r.opts.decoder(kv, next); err != nil {
_ = r.opts.logger.Log(log.LevelError, fmt.Sprintf("config decode error, err: %v, key: %s, value: %s", err, kv.Key, string(kv.Value)))
4 years ago
return err
}
if err := mergo.Map(&merged, convertMap(next), mergo.WithOverride); err != nil {
_ = r.opts.logger.Log(log.LevelError, fmt.Sprintf("config merge error, err: %v, key: %s, value: %s", err, kv.Key, string(kv.Value)))
4 years ago
return err
}
}
r.lock.Lock()
4 years ago
r.values = merged
r.lock.Unlock()
4 years ago
return nil
}
func (r *reader) Value(path string) (Value, bool) {
r.lock.Lock()
defer r.lock.Unlock()
return readValue(r.values, path)
4 years ago
}
func (r *reader) Source() ([]byte, error) {
r.lock.Lock()
defer r.lock.Unlock()
return marshalJSON(convertMap(r.values))
4 years ago
}
func (r *reader) Resolve() error {
r.lock.Lock()
defer r.lock.Unlock()
return r.opts.resolver(r.values)
}
4 years ago
func cloneMap(src map[string]interface{}) (map[string]interface{}, error) {
// https://gist.github.com/soroushjp/0ec92102641ddfc3ad5515ca76405f4d
var buf bytes.Buffer
gob.Register(map[string]interface{}{})
gob.Register([]interface{}{})
enc := gob.NewEncoder(&buf)
dec := gob.NewDecoder(&buf)
err := enc.Encode(src)
4 years ago
if err != nil {
return nil, err
}
var copy map[string]interface{}
err = dec.Decode(&copy)
if err != nil {
4 years ago
return nil, err
}
return copy, nil
4 years ago
}
func convertMap(src interface{}) interface{} {
switch m := src.(type) {
case map[string]interface{}:
dst := make(map[string]interface{}, len(m))
for k, v := range m {
dst[k] = convertMap(v)
}
return dst
case map[interface{}]interface{}:
dst := make(map[string]interface{}, len(m))
for k, v := range m {
dst[fmt.Sprint(k)] = convertMap(v)
}
return dst
case []interface{}:
dst := make([]interface{}, len(m))
for k, v := range m {
dst[k] = convertMap(v)
}
return dst
case []byte:
// there will be no binary data in the config data
return string(m)
4 years ago
default:
return src
}
}
// readValue read Value in given map[string]interface{}
// by the given path, will return false if not found.
func readValue(values map[string]interface{}, path string) (Value, bool) {
var (
next = values
keys = strings.Split(path, ".")
last = len(keys) - 1
)
for idx, key := range keys {
value, ok := next[key]
if !ok {
return nil, false
}
if idx == last {
av := &atomicValue{}
av.Store(value)
return av, true
}
switch vm := value.(type) {
case map[string]interface{}:
next = vm
default:
return nil, false
}
}
return nil, false
}
func marshalJSON(v interface{}) ([]byte, error) {
if m, ok := v.(proto.Message); ok {
return protojson.MarshalOptions{EmitUnpopulated: true}.Marshal(m)
}
return json.Marshal(v)
}
func unmarshalJSON(data []byte, v interface{}) error {
if m, ok := v.(proto.Message); ok {
return protojson.UnmarshalOptions{DiscardUnknown: true}.Unmarshal(data, m)
}
return json.Unmarshal(data, v)
}