Skip to content

Commit

Permalink
fix: apollo yaml watch (#3021)
Browse files Browse the repository at this point in the history
Co-authored-by: shuai_yang <[email protected]>
  • Loading branch information
hoslo and shuai_yang authored Nov 22, 2023
1 parent ff105d5 commit e84cdde
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 11 deletions.
19 changes: 8 additions & 11 deletions contrib/config/apollo/watcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,18 +27,15 @@ func (c *customChangeListener) onChange(namespace string, changes map[string]*st
kv := make([]*config.KeyValue, 0, 2)
if strings.Contains(namespace, ".") && !strings.HasSuffix(namespace, "."+properties) &&
(format(namespace) == yaml || format(namespace) == yml || format(namespace) == json) {
value, err := c.apollo.client.GetConfigCache(namespace).Get("content")
if err != nil {
log.Warnw("apollo get config failed", "err", err)
return nil
if value, ok := changes["content"]; ok {
kv = append(kv, &config.KeyValue{
Key: namespace,
Value: []byte(value.NewValue.(string)),
Format: format(namespace),
})

return kv
}
kv = append(kv, &config.KeyValue{
Key: namespace,
Value: []byte(value.(string)),
Format: format(namespace),
})

return kv
}

next := make(map[string]interface{})
Expand Down
79 changes: 79 additions & 0 deletions contrib/config/apollo/watcher_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package apollo

import (
"testing"

"github.com/apolloconfig/agollo/v4/storage"

"github.com/go-kratos/kratos/v2/config"
"github.com/go-kratos/kratos/v2/encoding"
)

func Test_onChange(t *testing.T) {
s := map[string]struct {
Name string `yaml:"name"`
}{
"app": {
Name: "new",
},
}
codec := encoding.GetCodec(yaml)
val, _ := codec.Marshal(s)
c := customChangeListener{}
tests := []struct {
name string
namespace string
changes map[string]*storage.ConfigChange
kvs []*config.KeyValue
}{
{
"test yaml onChange",
"app.yaml",
map[string]*storage.ConfigChange{
"name": {
OldValue: "old",
NewValue: "new",
ChangeType: storage.MODIFIED,
},
},
[]*config.KeyValue{
{
Key: "app.yaml",
Value: val,
Format: yaml,
},
},
},
{
"test json onChange",
"app.json",
map[string]*storage.ConfigChange{
"content": {
OldValue: `{"name":"old"}`,
NewValue: `{"name":"new"}`,
ChangeType: storage.MODIFIED,
},
},
[]*config.KeyValue{
{
Key: "app.json",
Value: []byte(`{"name":"new"}`),
Format: json,
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
kvs := c.onChange(tt.namespace, tt.changes)
if len(kvs) != len(tt.kvs) {
t.Errorf("len(kvs) = %v, want %v", len(kvs), len(tt.kvs))
}
for i := range kvs {
if kvs[i].Format != tt.kvs[i].Format || kvs[i].Key != tt.kvs[i].Key || string(kvs[i].Value) != string(tt.kvs[i].Value) {
t.Errorf("got %v, want %v", kvs[i], tt.kvs[i])
}
}
})
}
}

0 comments on commit e84cdde

Please sign in to comment.