From aa17113abc43a510abb80697fd54c319f4993679 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Edu=20G=C3=B3mez=20Escandell?= Date: Tue, 14 Nov 2023 11:24:05 +0100 Subject: [PATCH] Improve error check in asyncRecv We used to check that the message was not nill, but forgot to check the error. This double-check (is err nil? + is message nil?) would cause a bit of ugly nesting so I moved it into newHostInfo so we can return instead of nest. This required a renaming of newHostInfo to receiveHostInfo to keep the naming accurate. --- .../landscape_mock_service.go | 25 +++++++++++-------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/mocks/landscape/landscapemockservice/landscape_mock_service.go b/mocks/landscape/landscapemockservice/landscape_mock_service.go index 6d863dc9e..dbb3cca9c 100644 --- a/mocks/landscape/landscapemockservice/landscape_mock_service.go +++ b/mocks/landscape/landscapemockservice/landscape_mock_service.go @@ -4,6 +4,7 @@ package landscapemockservice import ( "context" + "errors" "fmt" "log/slog" "math/rand" @@ -30,8 +31,17 @@ type HostInfo struct { Instances []InstanceInfo } -// newHostInfo recursively copies the info in a landscapeapi.HostAgentInfo to a HostInfo. -func newHostInfo(src *landscapeapi.HostAgentInfo) HostInfo { +// receiveHostInfo receives a landscapeapi.HostAgentInfo and converts it to a HostInfo. +func receiveHostInfo(stream landscapeapi.LandscapeHostAgent_ConnectServer) (HostInfo, error) { + src, err := stream.Recv() + if err != nil { + return HostInfo{}, err + } + + if src == nil { + return HostInfo{}, errors.New("nil HostAgentInfo") + } + h := HostInfo{ UID: src.GetUid(), Hostname: src.GetHostname(), @@ -48,7 +58,7 @@ func newHostInfo(src *landscapeapi.HostAgentInfo) HostInfo { }) } - return h + return h, nil } type host struct { @@ -150,17 +160,12 @@ func asyncRecv(ctx context.Context, stream landscapeapi.LandscapeHostAgent_Conne defer close(ch) for { - var msg recvMsg - recv, err := stream.Recv() - msg.err = err - if recv != nil { - msg.info = newHostInfo(recv) - } + info, err := receiveHostInfo(stream) select { case <-ctx.Done(): return - case ch <- msg: + case ch <- recvMsg{info, err}: } } }()