Skip to content

Commit

Permalink
feat!: update SQS receiveMessage to return no messages error when no …
Browse files Browse the repository at this point in the history
…messages received from the queue
  • Loading branch information
bpeng committed Nov 12, 2024
1 parent c609cb0 commit 8cd43a0
Showing 1 changed file with 26 additions and 20 deletions.
46 changes: 26 additions & 20 deletions aws/sqs/sqs.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ type SQS struct {
client *sqs.Client
}

// specific error to return when no messages are received from the queue
var ErrNoMessages = errors.New("no messages received from queue")

// New returns an SQS struct which wraps an SQS client using the default AWS credentials chain.
// This consults (in order) environment vars, config files, EC2 and ECS roles.
// It is an error if the AWS_REGION environment variable is not set.
Expand Down Expand Up @@ -125,29 +128,28 @@ func (s *SQS) ReceiveWithContextAttributes(ctx context.Context, queueURL string,
// receiveMessage is the common code used internally to receive an SQS message based
// on the provided input.
func (s *SQS) receiveMessage(ctx context.Context, input *sqs.ReceiveMessageInput) (Raw, error) {
r, err := s.client.ReceiveMessage(ctx, input)
if err != nil {
return Raw{}, err
}

for {
r, err := s.client.ReceiveMessage(ctx, input)
if err != nil {
return Raw{}, err
}
switch {
case r == nil || len(r.Messages) == 0:
// no message received
return Raw{}, ErrNoMessages

switch {
case r == nil || len(r.Messages) == 0:
// no message received
continue
case len(r.Messages) == 1:
raw := r.Messages[0]

m := Raw{
Body: aws.ToString(raw.Body),
ReceiptHandle: aws.ToString(raw.ReceiptHandle),
Attributes: raw.Attributes,
}
return m, nil
case len(r.Messages) > 1:
return Raw{}, fmt.Errorf("received more than 1 message: %d", len(r.Messages))
case len(r.Messages) == 1:
raw := r.Messages[0]

m := Raw{
Body: aws.ToString(raw.Body),
ReceiptHandle: aws.ToString(raw.ReceiptHandle),
Attributes: raw.Attributes,
}
return m, nil

default:
return Raw{}, fmt.Errorf("received unexpected messages: %d", len(r.Messages))
}
}

Expand Down Expand Up @@ -333,3 +335,7 @@ func Cancelled(err error) bool {
}
return false
}

func IsNoMessagesError(err error) bool {
return errors.Is(err, ErrNoMessages)
}

0 comments on commit 8cd43a0

Please sign in to comment.