-
Notifications
You must be signed in to change notification settings - Fork 478
/
codec.go
65 lines (51 loc) · 1.21 KB
/
codec.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package configstore
import (
"bytes"
"compress/gzip"
"fmt"
"io"
"strings"
"github.com/grafana/dskit/kv/codec"
)
// GetCodec returns the codec for encoding and decoding instance.Configs
// in the Remote store.
func GetCodec() codec.Codec {
return &yamlCodec{}
}
type yamlCodec struct{}
func (*yamlCodec) Decode(bb []byte) (interface{}, error) {
// Decode is called by kv.Clients with an empty slice when a
// key is deleted. We should stop early here and don't return
// an error so the deletion event propagates to watchers.
if len(bb) == 0 {
return nil, nil
}
r, err := gzip.NewReader(bytes.NewReader(bb))
if err != nil {
return nil, err
}
var sb strings.Builder
if _, err := io.Copy(&sb, r); err != nil {
return nil, err
}
return sb.String(), nil
}
func (*yamlCodec) Encode(v interface{}) ([]byte, error) {
var buf bytes.Buffer
var cfg string
switch v := v.(type) {
case string:
cfg = v
default:
panic(fmt.Sprintf("unexpected type %T passed to yamlCodec.Encode", v))
}
w := gzip.NewWriter(&buf)
if _, err := io.Copy(w, strings.NewReader(cfg)); err != nil {
return nil, err
}
w.Close()
return buf.Bytes(), nil
}
func (*yamlCodec) CodecID() string {
return "agentConfig/yaml"
}