Debian Codegraph @

providers/nats/nats.go

raw
1 package nats
2
3 import (
4 "errors"
5 "fmt"
6 "strings"
7 "time"
8
9 "github.com/knadh/koanf/maps"
10 "github.com/nats-io/nats.go"
11 )
12
13 type Config struct {
14 // nats endpoint (comma separated urls are possible, eg "nats://one, nats://two").
15 URL string
16
17 // Optional NATS options: nats.Connect(url, ...options)
18 Options []nats.Option
19
20 // Optional JetStream options: nc.JetStream(...options)
21 JetStreamOptions []nats.JSOpt
22
23 // Bucket is the Nats KV bucket.
24 Bucket string
25
26 // Prefix (optional).
27 Prefix string
28
29 // If true, keys will be unflattened by delimiter "." into a nested map
30 // So, "a.b.c" results in {"a": {"b": {"c": "value" }}}
31 // Prefix will be included
32 Unflatten bool
33 }
34
35 // Nats implements the nats config provider.
36 type Nats struct {
37 kv nats.KeyValue
38 cfg Config
39 }
40
41 // Provider returns a provider that takes nats config.
42 func Provider(cfg Config) (*Nats, error) {
43 nc, err := nats.Connect(cfg.URL, cfg.Options...)
44 if err != nil {
45 return nil, err
46 }
47
48 js, err := nc.JetStream(cfg.JetStreamOptions...)
49 if err != nil {
50 return nil, err
51 }
52
53 kv, err := js.KeyValue(cfg.Bucket)
54 if err != nil {
55 return nil, err
56 }
57
58 return &Nats{kv: kv, cfg: cfg}, nil
59 }
60
61 // ReadBytes is not supported by nats provider.
62 func (n *Nats) ReadBytes() ([]byte, error) {
63 return nil, errors.New("nats provider does not support this method")
64 }
65
66 // Read returns a nested config map.
67 func (n *Nats) Read() (map[string]any, error) {
68 keys, err := n.kv.Keys()
69 if err != nil {
70 return nil, err
71 }
72
73 mp := make(map[string]any)
74 for _, key := range keys {
75 if !strings.HasPrefix(key, n.cfg.Prefix) {
76 continue
77 }
78 res, err := n.kv.Get(key)
79 if err != nil {
80 return nil, err
81 }
82 mp[res.Key()] = string(res.Value())
83 }
84 if n.cfg.Unflatten {
85 return maps.Unflatten(mp, "."), nil
86 }
87
88 return mp, nil
89 }
90
91 func (n *Nats) Watch(cb func(event any, err error)) error {
92 w, err := n.kv.Watch(fmt.Sprintf("%s.*", n.cfg.Prefix))
93 if err != nil {
94 return err
95 }
96
97 start := time.Now()
98 go func(watcher nats.KeyWatcher) {
99 for update := range watcher.Updates() {
100 // ignore nil events and only callback when the event is new (nats always sends one "old" event)
101 if update != nil && update.Created().After(start) {
102 cb(update, nil)
103 }
104 }
105 }(w)
106
107 return nil
108 }