Skip to content

Commit

Permalink
Convert NextMessage.nextMessage to a pointer (#89)
Browse files Browse the repository at this point in the history
ProtoBuf messages are non-copy (see https://golang.org/issues/8005),
so instead of storing by value we store a pointer.

Resolves #86
  • Loading branch information
tigrannajaryan committed May 31, 2022
1 parent 0403a82 commit 3f2eab4
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
14 changes: 10 additions & 4 deletions client/internal/nextmessage.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,24 @@ import (
// concurrency-safe interface to work with the message.
type NextMessage struct {
// The next message to send.
nextMessage protobufs.AgentToServer
nextMessage *protobufs.AgentToServer
// Indicates that nextMessage is pending to be sent.
messagePending bool
// Mutex to protect the above 2 fields.
messageMutex sync.Mutex
}

func NewNextMessage() NextMessage {
return NextMessage{
nextMessage: &protobufs.AgentToServer{},
}
}

// Update applies the specified modifier function to the next message that
// will be sent and marks the message as pending to be sent.
func (s *NextMessage) Update(modifier func(msg *protobufs.AgentToServer)) {
s.messageMutex.Lock()
modifier(&s.nextMessage)
modifier(s.nextMessage)
s.messagePending = true
s.messageMutex.Unlock()
}
Expand All @@ -35,12 +41,12 @@ func (s *NextMessage) PopPending() *protobufs.AgentToServer {
if s.messagePending {
// Clone the message to have a copy for sending and avoid blocking
// future updates to s.NextMessage field.
msgToSend = proto.Clone(&s.nextMessage).(*protobufs.AgentToServer)
msgToSend = proto.Clone(s.nextMessage).(*protobufs.AgentToServer)
s.messagePending = false

// Reset fields that we do not have to send unless they change before the
// next report after this one. Keep the "hash" fields.
msg := protobufs.AgentToServer{
msg := &protobufs.AgentToServer{
InstanceUid: s.nextMessage.InstanceUid,
AgentDescription: &protobufs.AgentDescription{
Hash: s.nextMessage.AgentDescription.Hash,
Expand Down
5 changes: 4 additions & 1 deletion client/internal/sender.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,10 @@ type SenderCommon struct {
}

func NewSenderCommon() SenderCommon {
return SenderCommon{hasPendingMessage: make(chan struct{}, 1)}
return SenderCommon{
hasPendingMessage: make(chan struct{}, 1),
nextMessage: NewNextMessage(),
}
}

// ScheduleSend signals to HTTPSender that the message in NextMessage struct
Expand Down

0 comments on commit 3f2eab4

Please sign in to comment.