From 1b5e701cfbd8e8feea80105e04f9656d2ea67179 Mon Sep 17 00:00:00 2001 From: jkoberg Date: Tue, 9 Apr 2024 12:36:24 +0200 Subject: [PATCH] fix(store/nats-js-kv): Unset conn when connection is closed Signed-off-by: jkoberg --- v4/store/nats-js-kv/nats.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/v4/store/nats-js-kv/nats.go b/v4/store/nats-js-kv/nats.go index 13ae81d2..c1f7908f 100644 --- a/v4/store/nats-js-kv/nats.go +++ b/v4/store/nats-js-kv/nats.go @@ -69,6 +69,18 @@ func NewStore(opts ...store.Option) store.Store { n.setOption(opts...) + // register unset connection callback + f := n.nopts.ClosedCB + n.nopts.ClosedCB = func(c *nats.Conn) { + // reset connection + n.resetConn() + + // execute the original callback if set + if f != nil { + f(c) + } + } + return n } @@ -360,6 +372,14 @@ func (n *natsStore) hasConn() bool { return n.conn != nil } +// thread safe way to reset the connection. +func (n *natsStore) resetConn() { + n.Lock() + defer n.Unlock() + + n.conn = nil +} + // mustGetDefaultBucket returns the bucket with the given name creating it with default configuration if needed. func (n *natsStore) mustGetBucketByName(name string) (nats.KeyValue, error) { return n.mustGetBucket(&nats.KeyValueConfig{