From b00167520caef47d1f7b2ca334753a92fc95992c Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Wed, 19 Feb 2020 02:05:38 +0300 Subject: [PATCH] fixes for safe conversation and avoid panics (#1213) * fixes for safe convertation Signed-off-by: Vasiliy Tolstov * fix client publish panic If broker connect returns error we dont check it status and use it later to publish message, mostly this is unexpected because broker connection failed and we cant use it. Also proposed solution have benefit - we flag connection status only when we have succeseful broker connection Signed-off-by: Vasiliy Tolstov * api/handler/broker: fix possible broker publish panic Signed-off-by: Vasiliy Tolstov --- grpc.go | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/grpc.go b/grpc.go index 1c7f351..7c5a008 100644 --- a/grpc.go +++ b/grpc.go @@ -6,7 +6,7 @@ import ( "crypto/tls" "fmt" "os" - "sync" + "sync/atomic" "time" "github.com/micro/go-micro/v2/broker" @@ -24,9 +24,9 @@ import ( ) type grpcClient struct { - once sync.Once opts client.Options pool *pool + once atomic.Value } func init() { @@ -570,9 +570,12 @@ func (g *grpcClient) Publish(ctx context.Context, p client.Message, opts ...clie body = b } - g.once.Do(func() { - g.opts.Broker.Connect() - }) + if !g.once.Load().(bool) { + if err = g.opts.Broker.Connect(); err != nil { + return errors.InternalServerError("go.micro.client", err.Error()) + } + g.once.Store(true) + } topic := p.Topic() @@ -641,9 +644,9 @@ func newClient(opts ...client.Option) client.Client { } rc := &grpcClient{ - once: sync.Once{}, opts: options, } + rc.once.Store(false) rc.pool = newPool(options.PoolSize, options.PoolTTL, rc.poolMaxIdle(), rc.poolMaxStreams())