forked from heetch/confita
/
etcd.go
104 lines (83 loc) · 2 KB
/
etcd.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package etcd
import (
"context"
"path"
"strings"
"github.com/HnH/confita/backend"
"github.com/coreos/etcd/clientv3"
)
// Backend loads keys from etcd.
type Backend struct {
client *clientv3.Client
prefix string
prefetch bool
cache map[string][]byte
}
// NewBackend creates a configuration loader that loads from etcd.
func NewBackend(client *clientv3.Client, opts ...Option) *Backend {
b := Backend{
client: client,
}
for _, opt := range opts {
opt(&b)
}
return &b
}
// Get loads the given key from etcd.
func (b *Backend) Get(ctx context.Context, key string) ([]byte, error) {
if b.cache == nil && b.prefetch {
err := b.fetchTree(ctx)
if err != nil {
return nil, err
}
}
if b.cache != nil {
return b.fromCache(ctx, key)
}
resp, err := b.client.Get(ctx, path.Join(b.prefix, key))
if err != nil {
return nil, err
}
if len(resp.Kvs) == 0 {
return nil, backend.ErrNotFound
}
return resp.Kvs[0].Value, nil
}
func (b *Backend) fetchTree(ctx context.Context) error {
resp, err := b.client.KV.Get(ctx, b.prefix, clientv3.WithPrefix())
if err != nil {
return err
}
b.cache = make(map[string][]byte)
for _, kv := range resp.Kvs {
b.cache[strings.TrimLeft(string(kv.Key), b.prefix+"/")] = kv.Value
}
return nil
}
func (b *Backend) fromCache(ctx context.Context, key string) ([]byte, error) {
v, ok := b.cache[key]
if !ok {
return nil, backend.ErrNotFound
}
return v, nil
}
// Name returns the name of the backend.
func (b *Backend) Name() string {
return "etcd"
}
// Option is used to configure the Consul backend.
type Option func(*Backend)
// WithPrefix is used to specify the prefix to prepend on every keys.
func WithPrefix(prefix string) Option {
return func(b *Backend) {
b.prefix = prefix
}
}
// WithPrefetch is used to prefetch the entire tree and cache it to
// avoid further round trips. If the WithPrefix option is used, will fetch
// the tree under the specified prefix.
func WithPrefetch() Option {
return func(b *Backend) {
b.prefetch = true
}
}