Skip to content

Commit

Permalink
Improve error check in asyncRecv
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
EduardGomezEscandell committed Nov 14, 2023
1 parent afd2927 commit aa17113
Showing 1 changed file with 15 additions and 10 deletions.
25 changes: 15 additions & 10 deletions mocks/landscape/landscapemockservice/landscape_mock_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package landscapemockservice

import (
"context"
"errors"
"fmt"
"log/slog"
"math/rand"
Expand All @@ -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(),
Expand All @@ -48,7 +58,7 @@ func newHostInfo(src *landscapeapi.HostAgentInfo) HostInfo {
})
}

return h
return h, nil
}

type host struct {
Expand Down Expand Up @@ -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}:
}
}
}()
Expand Down

0 comments on commit aa17113

Please sign in to comment.