Skip to content

Commit

Permalink
Fix config being overwritten by olric init when manually embedding an…
Browse files Browse the repository at this point in the history
…d defining Config
  • Loading branch information
justinfx committed Jun 19, 2020
1 parent f6880dc commit 9c775bc
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 11 deletions.
38 changes: 27 additions & 11 deletions lib/nats.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,9 +154,24 @@ func (n *NatsDiscovery) Initialize() error {
opts.ReconnectWait = 2 * time.Second
opts.MaxReconnect = -1 // Keep trying forever

conn, err := opts.Connect()
if err != nil {
return fmt.Errorf("nats server connection failure: %w", err)
var (
conn *nats.Conn
err error
)
const N = 3
for i := 1;;i++ {
conn, err = opts.Connect()
if err != nil {
if i <= N {
n.log.Printf("[WARN] nats server connection failure %d/%d; " +
"retrying in %s", i, N, opts.ReconnectWait)
time.Sleep(opts.ReconnectWait)
continue
}
return fmt.Errorf("nats server connection failure: %w", err)
}
break

}

enc, err := nats.NewEncodedConn(conn, nats.JSON_ENCODER)
Expand All @@ -170,7 +185,13 @@ func (n *NatsDiscovery) Initialize() error {

// SetConfig registers plugin configuration
func (n *NatsDiscovery) SetConfig(c MapConfig) error {
var cfg Config
if n.Config == nil {
n.Config = &Config{}
}

if len(c) == 0 {
return nil
}

dec, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
DecodeHook: func(src, tgt reflect.Type, val interface{}) (interface{}, error) {
Expand All @@ -182,17 +203,12 @@ func (n *NatsDiscovery) SetConfig(c MapConfig) error {
}
return time.ParseDuration(val.(string))
},
Result: &cfg,
Result: n.Config,
})
if err != nil {
return err
}

if err = dec.Decode(c); err != nil {
return err
}
n.Config = &cfg
return nil
return dec.Decode(c)
}

// SetLogger sets a custom logger instance
Expand Down
22 changes: 22 additions & 0 deletions lib/nats_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,28 @@ func TestInitialize(t *testing.T) {
expectTimeout, sd.Config.DiscoveryTimeout)
}
})

t.Run("config reset", func(t *testing.T) {
expect := "addr:1234"
sd := NatsDiscovery{Config: &Config{Url: expect}}
if err := sd.SetConfig(MapConfig{}); err != nil {
t.Fatal(err)
}
if sd.Config.Url != expect {
t.Fatalf("expected %q, got %q", expect, sd.Config.Url)
}

if err := sd.SetConfig(MapConfig{"subject": "foo"}); err != nil {
t.Fatal(err)
}
if sd.Config.Url != expect {
t.Fatalf("expected %q, got %q", expect, sd.Config.Url)
}
expect = "foo"
if sd.Config.Subject != expect {
t.Fatalf("expectec %q, got %q", expect, sd.Config.Subject)
}
})
}

func TestDiscover(t *testing.T) {
Expand Down

0 comments on commit 9c775bc

Please sign in to comment.