shared-sqs: Этап 1 — клон GoAWS, удаление SNS, go build OK

This commit is contained in:
Naeel
2026-04-09 12:25:02 +03:00
parent d1d1bffd7c
commit f4352a17b1
58 changed files with 9688 additions and 0 deletions
+37
View File
@@ -0,0 +1,37 @@
package models
/*** config ***/
type EnvQueue struct {
Name string
ReceiveMessageWaitTimeSeconds int
RedrivePolicy string
MaximumMessageSize int
VisibilityTimeout int
MessageRetentionPeriod int
}
type EnvQueueAttributes struct {
VisibilityTimeout int
ReceiveMessageWaitTimeSeconds int
MaximumMessageSize int
MessageRetentionPeriod int // seconds
}
type Environment struct {
Host string
Port string
SqsPort string
Region string
AccountID string
LogToFile bool
LogFile string
EnableDuplicates bool
Queues []EnvQueue
QueueAttributeDefaults EnvQueueAttributes
RandomLatency RandomLatency
}
type RandomLatency struct {
Min int
Max int
}
+38
View File
@@ -0,0 +1,38 @@
package models
import (
"time"
)
var BaseXmlns = "http://queue.amazonaws.com/doc/2012-11-05/"
var BaseResponseMetadata = ResponseMetadata{RequestId: "00000000-0000-0000-0000-000000000000"}
var DeduplicationPeriod = 5 * time.Minute
var AvailableQueueAttributes = map[string]bool{
"DelaySeconds": true,
"MaximumMessageSize": true,
"MessageRetentionPeriod": true,
"Policy": true,
"ReceiveMessageWaitTimeSeconds": true,
"VisibilityTimeout": true,
"RedrivePolicy": true,
"RedriveAllowPolicy": true,
"ApproximateNumberOfMessages": true,
"ApproximateNumberOfMessagesDelayed": true,
"ApproximateNumberOfMessagesNotVisible": true,
"CreatedTimestamp": true,
"LastModifiedTimestamp": true,
"QueueArn": true,
}
const (
ProtocolSQS Protocol = "sqs"
ProtocolHTTP Protocol = "http"
ProtocolHTTPS Protocol = "https"
ProtocolDefault Protocol = "default"
)
const (
MessageStructureJSON MessageStructure = "json"
)
+36
View File
@@ -0,0 +1,36 @@
package models
import (
"encoding/json"
"strconv"
)
// StringToInt this is a custom type that will allow our request bodies to support either a string OR an int.
// It has its own UnmarshalJSON method to handle both types automatically and it can return an `int`
// from the `Int` method.
type StringToInt int
func (s *StringToInt) UnmarshalJSON(data []byte) error {
var i int
err := json.Unmarshal(data, &i)
if err == nil {
*s = StringToInt(i)
return nil
}
var str string
err = json.Unmarshal(data, &str)
if err != nil {
return err
}
tmp, err := strconv.Atoi(str)
if err != nil {
return err
}
*s = StringToInt(tmp)
return nil
}
func (s *StringToInt) Int() int {
return int(*s)
}
+75
View File
@@ -0,0 +1,75 @@
package models
import (
"encoding/json"
"testing"
"shared-sqs/app/test"
"github.com/stretchr/testify/assert"
)
type StringToIntStruct struct {
Field1 StringToInt `json:"Field1"`
Field2 StringToInt `json:"Field2"`
}
func TestStringToInt_unmarshalJSON_int(t *testing.T) {
body := struct {
Field1 int `json:"Field1"`
Field2 int `json:"Field2"`
}{
Field1: 1,
Field2: 2,
}
_, r := test.GenerateRequestInfo("POST", "/", body, true)
result := &StringToIntStruct{}
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(result)
assert.Nil(t, err)
assert.Equal(t, StringToInt(1), result.Field1)
assert.Equal(t, StringToInt(2), result.Field2)
}
func TestStringToInt_unmarshalJSON_string(t *testing.T) {
body := struct {
Field1 string `json:"Field1"`
Field2 string `json:"Field2"`
}{
Field1: "1",
Field2: "2",
}
_, r := test.GenerateRequestInfo("POST", "/", body, true)
result := &StringToIntStruct{}
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(result)
assert.Nil(t, err)
assert.Equal(t, StringToInt(1), result.Field1)
assert.Equal(t, StringToInt(2), result.Field2)
}
func TestStringToInt_unmarshalJSON_invalid_type_returns_error(t *testing.T) {
body := struct {
Field1 bool `json:"Field1"`
Field2 bool `json:"Field2"`
}{
Field1: true,
Field2: false,
}
_, r := test.GenerateRequestInfo("POST", "/", body, true)
result := &StringToIntStruct{}
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(result)
assert.Error(t, err)
}
func TestStringToInt_int_returns_int_type(t *testing.T) {
s := StringToInt(1)
assert.Equal(t, int(1), s.Int())
}
+65
View File
@@ -0,0 +1,65 @@
package models
import "net/http"
func init() {
SqsErrors = map[string]SqsErrorType{
"QueueNotFound": {HttpError: http.StatusBadRequest, Type: "Not Found", Code: "AWS.SimpleQueueService.NonExistentQueue", Message: "The specified queue does not exist for this wsdl version."},
"QueueExists": {HttpError: http.StatusBadRequest, Type: "Duplicate", Code: "AWS.SimpleQueueService.QueueExists", Message: "The specified queue already exists."},
"MessageDoesNotExist": {HttpError: http.StatusNotFound, Type: "Not Found", Code: "AWS.SimpleQueueService.QueueExists", Message: "The specified queue does not contain the message specified."},
"GeneralError": {HttpError: http.StatusBadRequest, Type: "GeneralError", Code: "AWS.SimpleQueueService.GeneralError", Message: "General Error."},
"TooManyEntriesInBatchRequest": {HttpError: http.StatusBadRequest, Type: "TooManyEntriesInBatchRequest", Code: "AWS.SimpleQueueService.TooManyEntriesInBatchRequest", Message: "Maximum number of entries per request are 10."},
"BatchEntryIdsNotDistinct": {HttpError: http.StatusBadRequest, Type: "BatchEntryIdsNotDistinct", Code: "AWS.SimpleQueueService.BatchEntryIdsNotDistinct", Message: "Two or more batch entries in the request have the same Id."},
"EmptyBatchRequest": {HttpError: http.StatusBadRequest, Type: "EmptyBatchRequest", Code: "AWS.SimpleQueueService.EmptyBatchRequest", Message: "The batch request doesn't contain any entries."},
"InvalidVisibilityTimeout": {HttpError: http.StatusBadRequest, Type: "ValidationError", Code: "AWS.SimpleQueueService.ValidationError", Message: "The visibility timeout is incorrect"},
"MessageNotInFlight": {HttpError: http.StatusBadRequest, Type: "MessageNotInFlight", Code: "AWS.SimpleQueueService.MessageNotInFlight", Message: "The message referred to isn't in flight."},
"MessageTooBig": {HttpError: http.StatusBadRequest, Type: "MessageTooBig", Code: "InvalidParameterValue", Message: "The message size exceeds the limit."},
"InvalidParameterValue": {HttpError: http.StatusBadRequest, Type: "InvalidParameterValue", Code: "AWS.SimpleQueueService.InvalidParameterValue", Message: "An invalid or out-of-range value was supplied for the input parameter."},
"InvalidAttributeValue": {HttpError: http.StatusBadRequest, Type: "InvalidAttributeValue", Code: "AWS.SimpleQueueService.InvalidAttributeValue", Message: "Invalid Value for the parameter RedrivePolicy."},
}
SnsErrors = map[string]SnsErrorType{
"InvalidParameterValue": {HttpError: http.StatusBadRequest, Type: "InvalidParameterValue", Code: "AWS.SimpleNotificationService.InvalidParameterValue", Message: "An invalid or out-of-range value was supplied for the input parameter."},
"TopicNotFound": {HttpError: http.StatusBadRequest, Type: "Not Found", Code: "AWS.SimpleNotificationService.NonExistentTopic", Message: "The specified topic does not exist for this wsdl version."},
"SubscriptionNotFound": {HttpError: http.StatusNotFound, Type: "Not Found", Code: "AWS.SimpleNotificationService.NonExistentSubscription", Message: "The specified subscription does not exist for this wsdl version."},
"TopicExists": {HttpError: http.StatusBadRequest, Type: "Duplicate", Code: "AWS.SimpleNotificationService.TopicAlreadyExists", Message: "The specified topic already exists."},
"ValidationError": {HttpError: http.StatusBadRequest, Type: "InvalidParameter", Code: "AWS.SimpleNotificationService.ValidationError", Message: "The input fails to satisfy the constraints specified by an AWS service."},
"BatchEntryIdsNotDistinct": {HttpError: http.StatusBadRequest, Type: "BatchEntryIdsNotDistinct", Code: "AWS.SimpleNotificationService.BatchEntryIdsNotDistinct", Message: "Two or more batch entries in the request have the same Id."},
"EmptyBatchRequest": {HttpError: http.StatusBadRequest, Type: "EmptyBatchRequest", Code: "AWS.SimpleNotificationService.EmptyBatchRequest", Message: "The batch request doesn't contain any entries."},
"TooManyEntriesInBatchRequest": {HttpError: http.StatusBadRequest, Type: "TooManyEntriesInBatchRequest", Code: "AWS.SimpleNotificationService.TooManyEntriesInBatchRequest", Message: "Maximum number of entries per request are 10."},
"MalformedInput": {HttpError: http.StatusBadRequest, Type: "Sender", Code: "AWS.SimpleNotificationService.MalformedInput", Message: "Invalid Base64 encoding"},
}
}
type SqsErrorType struct {
HttpError int
Type string
Code string
Message string
}
func (s SqsErrorType) StatusCode() int {
return s.HttpError
}
func (s SqsErrorType) Response() ErrorResult {
return ErrorResult{Type: s.Type, Code: s.Code, Message: s.Message}
}
var SqsErrors map[string]SqsErrorType
type SnsErrorType struct {
HttpError int
Type string
Code string
Message string
}
func (s SnsErrorType) StatusCode() int {
return s.HttpError
}
func (s SnsErrorType) Response() ErrorResult {
return ErrorResult{Type: s.Type, Code: s.Code, Message: s.Message}
}
var SnsErrors map[string]SnsErrorType
+23
View File
@@ -0,0 +1,23 @@
package models
import (
"sync"
)
// CurrentEnvironment should get overwritten when the app starts up and loads the config. For the
// sake of generating "partial" apps piece-meal during test automation we'll slap these placeholder
// values in here so the resource URLs aren't wonky like `http://://new-queue`.
var CurrentEnvironment = Environment{
Host: "host",
Port: "port",
Region: "region",
AccountID: "accountID",
}
var LogMessages bool
var LogFile string
var SyncQueues = struct {
sync.RWMutex
Queues map[string]*Queue
}{Queues: make(map[string]*Queue)}
+48
View File
@@ -0,0 +1,48 @@
package models
import (
"errors"
"fmt"
"math/rand"
"time"
)
// ---- Unit Tests ----
func ResetApp() {
CurrentEnvironment = Environment{}
ResetResources()
}
func ResetResources() {
SyncQueues.Lock()
SyncQueues.Queues = make(map[string]*Queue)
SyncQueues.Unlock()
}
func stringInSlice(a string, list []string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
func generateRandomLatency() (time.Duration, error) {
min := CurrentEnvironment.RandomLatency.Min
max := CurrentEnvironment.RandomLatency.Max
if min == 0 && max == 0 {
return time.Duration(0), nil
}
var randomLatencyValue int
if max == min {
randomLatencyValue = max
} else {
randomLatencyValue = rand.Intn(max-min) + min
}
randomDuration, err := time.ParseDuration(fmt.Sprintf("%dms", randomLatencyValue))
if err != nil {
return time.Duration(0), errors.New(fmt.Sprintf("Error parsing random latency value: %dms", randomLatencyValue))
}
return randomDuration, nil
}
+116
View File
@@ -0,0 +1,116 @@
package models
import (
"strconv"
"time"
log "github.com/sirupsen/logrus"
)
type MessageStructure string
type Protocol string
type MessageAttribute struct {
BinaryListValues []string `json:"BinaryListValues,omitempty" xml:"BinaryListValues,omitempty"` // currently unsupported by AWS
BinaryValue string `json:"BinaryValue,omitempty" xml:"BinaryValue,omitempty"`
DataType string `json:"DataType,omitempty" xml:"DataType,omitempty"`
StringListValues []string `json:"StringListValues,omitempty" xml:"StringListValues,omitempty"` // currently unsupported by AWS
StringValue string `json:"StringValue,omitempty" xml:"StringValue,omitempty"`
}
type SqsMessage struct {
MessageBody string
Uuid string
MD5OfMessageAttributes string
MD5OfMessageBody string
ReceiptHandle string
ReceiptTime time.Time
VisibilityTimeout time.Time
NumberOfReceives int
Retry int
MessageAttributes map[string]MessageAttribute
GroupID string
DeduplicationID string
SentTime time.Time
DelaySecs int
}
func (m *SqsMessage) IsReadyForReceipt() bool {
randomLatency, err := generateRandomLatency()
if err != nil {
log.Error(err)
return true
}
showAt := m.SentTime.Add(randomLatency).Add(time.Duration(m.DelaySecs) * time.Second)
return showAt.Before(time.Now())
}
type Queue struct {
Name string
URL string
Arn string
VisibilityTimeout int // seconds
ReceiveMessageWaitTimeSeconds int
DelaySeconds int
MaximumMessageSize int
MessageRetentionPeriod int // seconds // TODO - not used in the code yet
Messages []SqsMessage
DeadLetterQueue *Queue
MaxReceiveCount int
IsFIFO bool
FIFOMessages map[string]int
FIFOSequenceNumbers map[string]int
EnableDuplicates bool
Duplicates map[string]time.Time
}
func (q *Queue) NextSequenceNumber(groupId string) string {
if _, ok := q.FIFOSequenceNumbers[groupId]; !ok {
q.FIFOSequenceNumbers = map[string]int{
groupId: 0,
}
}
q.FIFOSequenceNumbers[groupId]++
return strconv.Itoa(q.FIFOSequenceNumbers[groupId])
}
func (q *Queue) IsLocked(groupId string) bool {
_, ok := q.FIFOMessages[groupId]
return ok
}
func (q *Queue) LockGroup(groupId string) {
if _, ok := q.FIFOMessages[groupId]; !ok {
q.FIFOMessages = map[string]int{
groupId: 0,
}
}
}
func (q *Queue) UnlockGroup(groupId string) {
if _, ok := q.FIFOMessages[groupId]; ok {
delete(q.FIFOMessages, groupId)
}
}
func (q *Queue) IsDuplicate(deduplicationId string) bool {
if !q.EnableDuplicates || !q.IsFIFO || deduplicationId == "" {
return false
}
_, ok := q.Duplicates[deduplicationId]
return ok
}
func (q *Queue) InitDuplicatation(deduplicationId string) {
if !q.EnableDuplicates || !q.IsFIFO || deduplicationId == "" {
return
}
if _, ok := q.Duplicates[deduplicationId]; !ok {
q.Duplicates[deduplicationId] = time.Now()
}
}
+73
View File
@@ -0,0 +1,73 @@
package models
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestFilterPolicy_IsSatisfiedBy(t *testing.T) {
var tests = []struct {
filterPolicy *FilterPolicy
messageAttributes map[string]MessageAttribute
expected bool
}{
{
&FilterPolicy{"foo": {"bar"}},
map[string]MessageAttribute{"foo": {DataType: "String", StringValue: "bar"}},
true,
},
{
&FilterPolicy{"foo": {"bar", "xyz"}},
map[string]MessageAttribute{"foo": {DataType: "String", StringValue: "xyz"}},
true,
},
{
&FilterPolicy{"foo": {"bar", "xyz"}, "abc": {"def"}},
map[string]MessageAttribute{"foo": {DataType: "String", StringValue: "xyz"},
"abc": {DataType: "String", StringValue: "def"}},
true,
},
{
&FilterPolicy{"foo": {"bar"}},
map[string]MessageAttribute{"foo": {DataType: "String", StringValue: "baz"}},
false,
},
{
&FilterPolicy{"foo": {"bar"}},
map[string]MessageAttribute{},
false,
},
{
&FilterPolicy{"foo": {"bar"}, "abc": {"def"}},
map[string]MessageAttribute{"foo": {DataType: "String", StringValue: "bar"}},
false,
},
{
&FilterPolicy{"foo": {"bar"}},
map[string]MessageAttribute{"foo": {DataType: "Binary", BinaryValue: "bar"}},
false,
},
}
for i, tt := range tests {
actual := tt.filterPolicy.IsSatisfiedBy(tt.messageAttributes)
if tt.filterPolicy.IsSatisfiedBy(tt.messageAttributes) != tt.expected {
t.Errorf("#%d FilterPolicy: expected %t, actual %t", i, tt.expected, actual)
}
}
}
func TestMessage_IsReadyForReceipt(t *testing.T) {
CurrentEnvironment.RandomLatency.Min = 100
CurrentEnvironment.RandomLatency.Max = 100
msg := SqsMessage{
SentTime: time.Now(),
}
assert.False(t, msg.IsReadyForReceipt())
duration, _ := time.ParseDuration("105ms")
time.Sleep(duration)
assert.True(t, msg.IsReadyForReceipt())
}
+515
View File
@@ -0,0 +1,515 @@
package models
import (
"encoding/json"
"fmt"
"net/url"
"strconv"
log "github.com/sirupsen/logrus"
)
type CreateQueueRequest struct {
QueueName string `json:"QueueName" schema:"QueueName"`
Attributes QueueAttributes `json:"Attributes" schema:"Attribute"`
Tags map[string]string `json:"Tags" schema:"Tags"`
Version string `json:"Version" schema:"Version"`
}
// TODO - is there an easier way to do this? Similar to the StringToInt type?
func (r *CreateQueueRequest) SetAttributesFromForm(values url.Values) {
for i := 1; true; i++ {
nameKey := fmt.Sprintf("Attribute.%d.Name", i)
attrName := values.Get(nameKey)
if attrName == "" {
break
}
valueKey := fmt.Sprintf("Attribute.%d.Value", i)
attrValue := values.Get(valueKey)
if attrValue == "" {
continue
}
switch attrName {
case "DelaySeconds":
tmp, err := strconv.Atoi(attrValue)
if err != nil {
log.Debugf("Failed to parse form attribute - %s: %s", attrName, attrValue)
continue
}
r.Attributes.DelaySeconds = StringToInt(tmp)
case "MaximumMessageSize":
tmp, err := strconv.Atoi(attrValue)
if err != nil {
log.Debugf("Failed to parse form attribute - %s: %s", attrName, attrValue)
continue
}
r.Attributes.MaximumMessageSize = StringToInt(tmp)
case "MessageRetentionPeriod":
tmp, err := strconv.Atoi(attrValue)
if err != nil {
log.Debugf("Failed to parse form attribute - %s: %s", attrName, attrValue)
continue
}
r.Attributes.MessageRetentionPeriod = StringToInt(tmp)
case "Policy":
var tmp map[string]interface{}
err := json.Unmarshal([]byte(attrValue), &tmp)
if err != nil {
log.Debugf("Failed to parse form attribute - %s: %s", attrName, attrValue)
continue
}
r.Attributes.Policy = tmp
case "ReceiveMessageWaitTimeSeconds":
tmp, err := strconv.Atoi(attrValue)
if err != nil {
log.Debugf("Failed to parse form attribute - %s: %s", attrName, attrValue)
continue
}
r.Attributes.ReceiveMessageWaitTimeSeconds = StringToInt(tmp)
case "VisibilityTimeout":
tmp, err := strconv.Atoi(attrValue)
if err != nil {
log.Debugf("Failed to parse form attribute - %s: %s", attrName, attrValue)
continue
}
r.Attributes.VisibilityTimeout = StringToInt(tmp)
case "RedrivePolicy":
tmp := RedrivePolicy{}
var decodedPolicy struct {
MaxReceiveCount interface{} `json:"maxReceiveCount"`
DeadLetterTargetArn string `json:"deadLetterTargetArn"`
}
err := json.Unmarshal([]byte(attrValue), &decodedPolicy)
if err != nil || decodedPolicy.DeadLetterTargetArn == "" {
log.Debugf("Failed to parse form attribute - %s: %s", attrName, attrValue)
continue
}
// Support both int and string types (historic processing), set a default of 10 if not provided.
// Go will default into float64 for interface{} types when parsing numbers
receiveCount, ok := decodedPolicy.MaxReceiveCount.(float64)
if !ok {
receiveCount = 10
t, ok := decodedPolicy.MaxReceiveCount.(string)
if ok {
r, err := strconv.ParseFloat(t, 64)
if err == nil {
receiveCount = r
} else {
log.Debugf("Failed to parse form attribute (maxReceiveCount) - %s: %s", attrName, attrValue)
}
} else {
log.Debugf("Failed to parse form attribute (maxReceiveCount) - %s: %s", attrName, attrValue)
}
}
tmp.MaxReceiveCount = StringToInt(receiveCount)
tmp.DeadLetterTargetArn = decodedPolicy.DeadLetterTargetArn
r.Attributes.RedrivePolicy = tmp
case "RedriveAllowPolicy":
var tmp map[string]interface{}
err := json.Unmarshal([]byte(attrValue), &tmp)
if err != nil {
log.Debugf("Failed to parse form attribute - %s: %s", attrName, attrValue)
continue
}
r.Attributes.RedriveAllowPolicy = tmp
}
}
return
}
func NewListQueuesRequest() *ListQueueRequest {
return &ListQueueRequest{}
}
type ListQueueRequest struct {
MaxResults int `json:"MaxResults" schema:"MaxResults"`
NextToken string `json:"NextToken" schema:"NextToken"`
QueueNamePrefix string `json:"QueueNamePrefix" schema:"QueueNamePrefix"`
}
func (r *ListQueueRequest) SetAttributesFromForm(values url.Values) {
maxResults, err := strconv.Atoi(values.Get("MaxResults"))
if err == nil {
r.MaxResults = maxResults
}
r.NextToken = values.Get("NextToken")
r.QueueNamePrefix = values.Get("QueueNamePrefix")
}
func NewGetQueueAttributesRequest() *GetQueueAttributesRequest {
return &GetQueueAttributesRequest{}
}
type GetQueueAttributesRequest struct {
QueueUrl string `json:"QueueUrl"`
AttributeNames []string `json:"AttributeNames"`
}
func (r *GetQueueAttributesRequest) SetAttributesFromForm(values url.Values) {
r.QueueUrl = values.Get("QueueUrl")
for i := 1; true; i++ {
attrKey := fmt.Sprintf("AttributeName.%d", i)
attrValue := values.Get(attrKey)
if attrValue == "" {
break
}
r.AttributeNames = append(r.AttributeNames, attrValue)
}
}
/*** Send Message Request */
func NewSendMessageRequest() *SendMessageRequest {
return &SendMessageRequest{
MessageAttributes: make(map[string]MessageAttribute),
MessageSystemAttributes: make(map[string]MessageAttribute),
}
}
type SendMessageRequest struct {
DelaySeconds int `json:"DelaySeconds" schema:"DelaySeconds"`
// MessageAttributes is custom attributes that users can add on the message as they like.
// Please see: https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessage.html#SQS-SendMessage-request-MessageAttributes
MessageAttributes map[string]MessageAttribute `json:"MessageAttributes" schema:"MessageAttributes"`
MessageBody string `json:"MessageBody" schema:"MessageBody"`
MessageDeduplicationId string `json:"MessageDeduplicationId" schema:"MessageDeduplicationId"`
MessageGroupId string `json:"MessageGroupId" schema:"MessageGroupId"`
// MessageSystemAttributes is custom attributes for AWS services.
// Please see: https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessage.html#SQS-SendMessage-request-MessageSystemAttributes
// On AWS, the only supported attribute is "AWSTraceHeader" that is for AWS X-Ray.
// Goaws does not contains X-Ray emulation, so currently MessageSystemAttributes is unsupported.
// TODO: Replace with a struct with known attributes "AWSTraceHeader".
MessageSystemAttributes map[string]MessageAttribute `json:"MessageSystemAttributes" schema:"MessageSystemAttributes"`
QueueUrl string `json:"QueueUrl" schema:"QueueUrl"`
}
func parseMessageAttributes(values url.Values, keyPrefix string) map[string]MessageAttribute {
result := map[string]MessageAttribute{}
for i := 1; true; i++ {
nameKey := fmt.Sprintf("%s.%d.Name", keyPrefix, i)
name := values.Get(nameKey)
if name == "" {
break
}
dataTypeKey := fmt.Sprintf("%s.%d.Value.DataType", keyPrefix, i)
dataType := values.Get(dataTypeKey)
if dataType == "" {
log.Warnf("DataType of message attribute %s is missing, MD5 checksum will most probably be wrong!\n", name)
continue
}
stringValue := values.Get(fmt.Sprintf("%s.%d.Value.StringValue", keyPrefix, i))
binaryValue := values.Get(fmt.Sprintf("%s.%d.Value.BinaryValue", keyPrefix, i))
result[name] = MessageAttribute{
DataType: dataType,
StringValue: stringValue,
BinaryValue: binaryValue,
}
}
if len(result) > 0 {
return result
}
return nil
}
func (r *SendMessageRequest) SetAttributesFromForm(values url.Values) {
r.MessageAttributes = parseMessageAttributes(values, "MessageAttribute")
}
func NewSendMessageBatchRequest() *SendMessageBatchRequest {
return &SendMessageBatchRequest{}
}
type SendMessageBatchRequest struct {
Entries []SendMessageBatchRequestEntry
QueueUrl string
}
func (r *SendMessageBatchRequest) SetAttributesFromForm(values url.Values) {
for entryIndex := range r.Entries {
r.Entries[entryIndex].MessageAttributes = parseMessageAttributes(values, fmt.Sprintf("Entries.%d.MessageAttributes", entryIndex))
}
}
type SendMessageBatchRequestEntry struct {
Id string `json:"Id" schema:"Id"`
MessageBody string `json:"MessageBody" schema:"MessageBody"`
DelaySeconds int `json:"DelaySeconds" schema:"DelaySeconds"` // NOTE: not implemented
MessageAttributes map[string]MessageAttribute `json:"MessageAttributes" schema:"MessageAttributes"`
MessageDeduplicationId string `json:"MessageDeduplicationId" schema:"MessageDeduplicationId"`
MessageGroupId string `json:"MessageGroupId" schema:"MessageGroupId"`
MessageSystemAttributes map[string]MessageAttribute `json:"MessageSystemAttributes" schema:"MessageSystemAttributes"` // NOTE: not implemented
}
// Get Queue Url Request
func NewGetQueueUrlRequest() *GetQueueUrlRequest {
return &GetQueueUrlRequest{}
}
type GetQueueUrlRequest struct {
QueueName string `json:"QueueName"`
QueueOwnerAWSAccountId string `json:"QueueOwnerAWSAccountId"` // NOTE: not implemented
}
func (r *GetQueueUrlRequest) SetAttributesFromForm(values url.Values) {}
func NewSetQueueAttributesRequest() *SetQueueAttributesRequest {
return &SetQueueAttributesRequest{}
}
type SetQueueAttributesRequest struct {
QueueUrl string `json:"QueueUrl"`
Attributes QueueAttributes `json:"Attributes"`
}
func (r *SetQueueAttributesRequest) SetAttributesFromForm(values url.Values) {
r.QueueUrl = values.Get("QueueUrl")
// TODO - could we share with CreateQueueRequest?
for i := 1; true; i++ {
nameKey := fmt.Sprintf("Attribute.%d.Name", i)
attrName := values.Get(nameKey)
if attrName == "" {
break
}
valueKey := fmt.Sprintf("Attribute.%d.Value", i)
attrValue := values.Get(valueKey)
if attrValue == "" {
continue
}
switch attrName {
case "DelaySeconds":
tmp, err := strconv.Atoi(attrValue)
if err != nil {
log.Debugf("Failed to parse form attribute - %s: %s", attrName, attrValue)
continue
}
r.Attributes.DelaySeconds = StringToInt(tmp)
case "MaximumMessageSize":
tmp, err := strconv.Atoi(attrValue)
if err != nil {
log.Debugf("Failed to parse form attribute - %s: %s", attrName, attrValue)
continue
}
r.Attributes.MaximumMessageSize = StringToInt(tmp)
case "MessageRetentionPeriod":
tmp, err := strconv.Atoi(attrValue)
if err != nil {
log.Debugf("Failed to parse form attribute - %s: %s", attrName, attrValue)
continue
}
r.Attributes.MessageRetentionPeriod = StringToInt(tmp)
case "Policy":
var tmp map[string]interface{}
err := json.Unmarshal([]byte(attrValue), &tmp)
if err != nil {
log.Debugf("Failed to parse form attribute - %s: %s", attrName, attrValue)
continue
}
r.Attributes.Policy = tmp
case "ReceiveMessageWaitTimeSeconds":
tmp, err := strconv.Atoi(attrValue)
if err != nil {
log.Debugf("Failed to parse form attribute - %s: %s", attrName, attrValue)
continue
}
r.Attributes.ReceiveMessageWaitTimeSeconds = StringToInt(tmp)
case "VisibilityTimeout":
tmp, err := strconv.Atoi(attrValue)
if err != nil {
log.Debugf("Failed to parse form attribute - %s: %s", attrName, attrValue)
continue
}
r.Attributes.VisibilityTimeout = StringToInt(tmp)
case "RedrivePolicy":
tmp := RedrivePolicy{}
var decodedPolicy struct {
MaxReceiveCount interface{} `json:"maxReceiveCount"`
DeadLetterTargetArn string `json:"deadLetterTargetArn"`
}
err := json.Unmarshal([]byte(attrValue), &decodedPolicy)
if err != nil || decodedPolicy.DeadLetterTargetArn == "" {
log.Debugf("Failed to parse form attribute - %s: %s", attrName, attrValue)
continue
}
// Support both int and string types (historic processing), set a default of 10 if not provided.
// Go will default into float64 for interface{} types when parsing numbers
receiveCount, ok := decodedPolicy.MaxReceiveCount.(float64)
if !ok {
receiveCount = 10
t, ok := decodedPolicy.MaxReceiveCount.(string)
if ok {
r, err := strconv.ParseFloat(t, 64)
if err == nil {
receiveCount = r
} else {
log.Debugf("Failed to parse form attribute (maxReceiveCount) - %s: %s", attrName, attrValue)
}
} else {
log.Debugf("Failed to parse form attribute (maxReceiveCount) - %s: %s", attrName, attrValue)
}
}
tmp.MaxReceiveCount = StringToInt(receiveCount)
tmp.DeadLetterTargetArn = decodedPolicy.DeadLetterTargetArn
r.Attributes.RedrivePolicy = tmp
case "RedriveAllowPolicy":
var tmp map[string]interface{}
err := json.Unmarshal([]byte(attrValue), &tmp)
if err != nil {
log.Debugf("Failed to parse form attribute - %s: %s", attrName, attrValue)
continue
}
r.Attributes.RedriveAllowPolicy = tmp
}
}
return
}
// TODO - there are FIFO attributes and things too
// QueueAttributes - SQS QueueAttributes Available in create/set attributes requests.
// https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_CreateQueue.html#SQS-CreateQueue-request-attributes
type QueueAttributes struct {
DelaySeconds StringToInt `json:"DelaySeconds"`
MaximumMessageSize StringToInt `json:"MaximumMessageSize"`
MessageRetentionPeriod StringToInt `json:"MessageRetentionPeriod"` // NOTE: not implemented
Policy map[string]interface{} `json:"Policy"` // NOTE: not implemented
ReceiveMessageWaitTimeSeconds StringToInt `json:"ReceiveMessageWaitTimeSeconds"`
VisibilityTimeout StringToInt `json:"VisibilityTimeout"`
// Dead Letter Queues Only
RedrivePolicy RedrivePolicy `json:"RedrivePolicy"`
RedriveAllowPolicy map[string]interface{} `json:"RedriveAllowPolicy"` // NOTE: not implemented
}
type RedrivePolicy struct {
MaxReceiveCount StringToInt `json:"maxReceiveCount"`
DeadLetterTargetArn string `json:"deadLetterTargetArn"`
}
// UnmarshalJSON this will convert a JSON string of a Redrive Policy sub-doc (escaped characters and all) or
// a regular json document into the appropriate resulting struct.
func (r *RedrivePolicy) UnmarshalJSON(data []byte) error {
type basicRequest RedrivePolicy
err := json.Unmarshal(data, (*basicRequest)(r))
if err == nil {
return nil
}
tmp, _ := strconv.Unquote(string(data))
err = json.Unmarshal([]byte(tmp), (*basicRequest)(r))
if err != nil {
return err
}
return nil
}
func NewReceiveMessageRequest() *ReceiveMessageRequest {
return &ReceiveMessageRequest{}
}
type ReceiveMessageRequest struct {
QueueUrl string `json:"QueueUrl" schema:"QueueUrl"`
AttributeNames []string `json:"AttributeNames" schema:"AttributeNames"`
MessageSystemAttributeNames []string `json:"MessageSystemAttributeNames" schema:"MessageSystemAttributeNames"`
MessageAttributeNames []string `json:"MessageAttributeNames" schema:"MessageAttributeNames"`
MaxNumberOfMessages int `json:"MaxNumberOfMessages" schema:"MaxNumberOfMessages"`
VisibilityTimeout int `json:"VisibilityTimeout" schema:"VisibilityTimeout"`
WaitTimeSeconds int `json:"WaitTimeSeconds" schema:"WaitTimeSeconds"`
ReceiveRequestAttemptId string `json:"ReceiveRequestAttemptId" schema:"ReceiveRequestAttemptId"`
}
func (r *ReceiveMessageRequest) SetAttributesFromForm(values url.Values) {}
func NewCreateQueueRequest() *CreateQueueRequest {
return &CreateQueueRequest{
Attributes: QueueAttributes{
DelaySeconds: 0,
MaximumMessageSize: StringToInt(CurrentEnvironment.QueueAttributeDefaults.MaximumMessageSize),
MessageRetentionPeriod: StringToInt(CurrentEnvironment.QueueAttributeDefaults.MessageRetentionPeriod),
ReceiveMessageWaitTimeSeconds: StringToInt(CurrentEnvironment.QueueAttributeDefaults.ReceiveMessageWaitTimeSeconds),
VisibilityTimeout: StringToInt(CurrentEnvironment.QueueAttributeDefaults.VisibilityTimeout),
},
}
}
func NewChangeMessageVisibilityRequest() *ChangeMessageVisibilityRequest {
return &ChangeMessageVisibilityRequest{}
}
type ChangeMessageVisibilityRequest struct {
QueueUrl string `json:"QueueUrl" schema:"QueueUrl"`
ReceiptHandle string `json:"ReceiptHandle" schema:"ReceiptHandle"`
VisibilityTimeout int `json:"VisibilityTimeout" schema:"VisibilityTimeout"`
}
func (r *ChangeMessageVisibilityRequest) SetAttributesFromForm(values url.Values) {}
func NewDeleteMessageRequest() *DeleteMessageRequest {
return &DeleteMessageRequest{}
}
type DeleteMessageRequest struct {
QueueUrl string `json:"QueueUrl" schema:"QueueUrl"`
ReceiptHandle string `json:"ReceiptHandle" schema:"ReceiptHandle"`
}
func (r *DeleteMessageRequest) SetAttributesFromForm(values url.Values) {}
func NewPurgeQueueRequest() *PurgeQueueRequest {
return &PurgeQueueRequest{}
}
type PurgeQueueRequest struct {
QueueUrl string `json:"QueueUrl" schema:"QueueUrl"`
}
func (r *PurgeQueueRequest) SetAttributesFromForm(values url.Values) {}
func NewDeleteQueueRequest() *DeleteQueueRequest {
return &DeleteQueueRequest{}
}
type DeleteQueueRequest struct {
QueueUrl string `json:"QueueUrl" schema:"QueueUrl"`
}
func (r *DeleteQueueRequest) SetAttributesFromForm(values url.Values) {}
type DeleteMessageBatchRequestEntry struct {
Id string `json:"Id" schema:"Id"`
ReceiptHandle string `json:"ReceiptHandle" schema:"ReceiptHandle"`
}
type DeleteMessageBatchRequest struct {
Entries []DeleteMessageBatchRequestEntry `json:"Entries"`
QueueUrl string `json:"QueueUrl" schema:"QueueUrl"`
}
func NewDeleteMessageBatchRequest() *DeleteMessageBatchRequest {
return &DeleteMessageBatchRequest{}
}
func (r *DeleteMessageBatchRequest) SetAttributesFromForm(values url.Values) {
entries := []DeleteMessageBatchRequestEntry{}
for i := 1; true; i++ {
msgIdKey := fmt.Sprintf("DeleteMessageBatchRequestEntry.%d.Id", i)
receiptHandleKey := fmt.Sprintf("DeleteMessageBatchRequestEntry.%d.ReceiptHandle", i)
msgId := values.Get(msgIdKey)
receiptHandle := values.Get(receiptHandleKey)
if msgId == "" || receiptHandle == "" {
break
}
entries = append(entries, DeleteMessageBatchRequestEntry{
Id: msgId,
ReceiptHandle: receiptHandle,
})
}
if len(entries) > 0 {
r.Entries = entries
}
}
+739
View File
@@ -0,0 +1,739 @@
package models
import (
"encoding/json"
"fmt"
"math/rand"
"net/url"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestNewCreateQueueRequest(t *testing.T) {
CurrentEnvironment.QueueAttributeDefaults.MaximumMessageSize = 262144
CurrentEnvironment.QueueAttributeDefaults.MessageRetentionPeriod = 345600
CurrentEnvironment.QueueAttributeDefaults.ReceiveMessageWaitTimeSeconds = 10
CurrentEnvironment.QueueAttributeDefaults.VisibilityTimeout = 30
defer func() {
ResetApp()
}()
expectedCreateQueueRequest := &CreateQueueRequest{
Attributes: QueueAttributes{
DelaySeconds: 0,
MaximumMessageSize: 262144,
MessageRetentionPeriod: 345600,
ReceiveMessageWaitTimeSeconds: 10,
VisibilityTimeout: 30,
},
}
result := NewCreateQueueRequest()
assert.Equal(t, expectedCreateQueueRequest, result)
}
func TestCreateQueueRequest_SetAttributesFromForm_success(t *testing.T) {
expectedRedrivePolicy := RedrivePolicy{
MaxReceiveCount: 100,
DeadLetterTargetArn: "dead-letter-queue-arn",
}
form := url.Values{}
form.Add("Action", "CreateQueue")
form.Add("QueueName", "new-queue")
form.Add("Version", "2012-11-05")
form.Add("Attribute.1.Name", "DelaySeconds")
form.Add("Attribute.1.Value", "1")
form.Add("Attribute.2.Name", "MaximumMessageSize")
form.Add("Attribute.2.Value", "2")
form.Add("Attribute.3.Name", "MessageRetentionPeriod")
form.Add("Attribute.3.Value", "3")
form.Add("Attribute.4.Name", "Policy")
form.Add("Attribute.4.Value", "{\"i-am\":\"the-policy\"}")
form.Add("Attribute.5.Name", "ReceiveMessageWaitTimeSeconds")
form.Add("Attribute.5.Value", "4")
form.Add("Attribute.6.Name", "VisibilityTimeout")
form.Add("Attribute.6.Value", "5")
form.Add("Attribute.7.Name", "RedrivePolicy")
form.Add("Attribute.7.Value", "{\"maxReceiveCount\": 100, \"deadLetterTargetArn\":\"dead-letter-queue-arn\"}")
form.Add("Attribute.8.Name", "RedriveAllowPolicy")
form.Add("Attribute.8.Value", "{\"i-am\":\"the-redrive-allow-policy\"}")
cqr := &CreateQueueRequest{
Attributes: QueueAttributes{
DelaySeconds: 1,
MaximumMessageSize: 262144,
MessageRetentionPeriod: 345600,
ReceiveMessageWaitTimeSeconds: 10,
VisibilityTimeout: 30,
},
}
cqr.SetAttributesFromForm(form)
assert.Equal(t, StringToInt(1), cqr.Attributes.DelaySeconds)
assert.Equal(t, StringToInt(2), cqr.Attributes.MaximumMessageSize)
assert.Equal(t, StringToInt(3), cqr.Attributes.MessageRetentionPeriod)
assert.Equal(t, map[string]interface{}{"i-am": "the-policy"}, cqr.Attributes.Policy)
assert.Equal(t, StringToInt(4), cqr.Attributes.ReceiveMessageWaitTimeSeconds)
assert.Equal(t, StringToInt(5), cqr.Attributes.VisibilityTimeout)
assert.Equal(t, expectedRedrivePolicy, cqr.Attributes.RedrivePolicy)
assert.Equal(t, map[string]interface{}{"i-am": "the-redrive-allow-policy"}, cqr.Attributes.RedriveAllowPolicy)
}
func TestCreateQueueRequest_SetAttributesFromForm_success_handles_redrive_recieve_count_int(t *testing.T) {
expectedRedrivePolicy := RedrivePolicy{
MaxReceiveCount: 100,
DeadLetterTargetArn: "dead-letter-queue-arn",
}
form := url.Values{}
form.Add("Attribute.1.Name", "RedrivePolicy")
form.Add("Attribute.1.Value", "{\"maxReceiveCount\": 100, \"deadLetterTargetArn\":\"dead-letter-queue-arn\"}")
cqr := &CreateQueueRequest{
Attributes: QueueAttributes{},
}
cqr.SetAttributesFromForm(form)
assert.Equal(t, expectedRedrivePolicy, cqr.Attributes.RedrivePolicy)
}
func TestCreateQueueRequest_SetAttributesFromForm_success_handles_redrive_recieve_count_string(t *testing.T) {
expectedRedrivePolicy := RedrivePolicy{
MaxReceiveCount: 100,
DeadLetterTargetArn: "dead-letter-queue-arn",
}
form := url.Values{}
form.Add("Attribute.1.Name", "RedrivePolicy")
form.Add("Attribute.1.Value", "{\"maxReceiveCount\": \"100\", \"deadLetterTargetArn\":\"dead-letter-queue-arn\"}")
cqr := &CreateQueueRequest{
Attributes: QueueAttributes{},
}
cqr.SetAttributesFromForm(form)
assert.Equal(t, expectedRedrivePolicy, cqr.Attributes.RedrivePolicy)
}
func TestCreateQueueRequest_SetAttributesFromForm_success_default_unparsable_redrive_recieve_count(t *testing.T) {
defaultRedrivePolicy := RedrivePolicy{
MaxReceiveCount: 10,
DeadLetterTargetArn: "dead-letter-queue-arn",
}
form := url.Values{}
form.Add("Attribute.1.Name", "RedrivePolicy")
form.Add("Attribute.1.Value", "{\"maxReceiveCount\": null, \"deadLetterTargetArn\":\"dead-letter-queue-arn\"}")
cqr := &CreateQueueRequest{
Attributes: QueueAttributes{},
}
cqr.SetAttributesFromForm(form)
assert.Equal(t, defaultRedrivePolicy, cqr.Attributes.RedrivePolicy)
}
func TestCreateQueueRequest_SetAttributesFromForm_success_skips_invalid_values(t *testing.T) {
form := url.Values{}
form.Add("Attribute.1.Name", "DelaySeconds")
form.Add("Attribute.1.Value", "garbage")
form.Add("Attribute.2.Name", "MaximumMessageSize")
form.Add("Attribute.2.Value", "garbage")
form.Add("Attribute.3.Name", "MessageRetentionPeriod")
form.Add("Attribute.3.Value", "garbage")
form.Add("Attribute.4.Name", "Policy")
form.Add("Attribute.4.Value", "garbage")
form.Add("Attribute.5.Name", "ReceiveMessageWaitTimeSeconds")
form.Add("Attribute.5.Value", "garbage")
form.Add("Attribute.6.Name", "VisibilityTimeout")
form.Add("Attribute.6.Value", "garbage")
form.Add("Attribute.7.Name", "RedrivePolicy")
form.Add("Attribute.7.Value", "garbage")
form.Add("Attribute.8.Name", "RedriveAllowPolicy")
form.Add("Attribute.8.Value", "garbage")
cqr := &CreateQueueRequest{
Attributes: QueueAttributes{
DelaySeconds: 1,
MaximumMessageSize: 262144,
MessageRetentionPeriod: 345600,
ReceiveMessageWaitTimeSeconds: 10,
VisibilityTimeout: 30,
},
}
cqr.SetAttributesFromForm(form)
assert.Equal(t, StringToInt(1), cqr.Attributes.DelaySeconds)
assert.Equal(t, StringToInt(262144), cqr.Attributes.MaximumMessageSize)
assert.Equal(t, StringToInt(345600), cqr.Attributes.MessageRetentionPeriod)
assert.Equal(t, map[string]interface{}(nil), cqr.Attributes.Policy)
assert.Equal(t, StringToInt(10), cqr.Attributes.ReceiveMessageWaitTimeSeconds)
assert.Equal(t, StringToInt(30), cqr.Attributes.VisibilityTimeout)
assert.Equal(t, RedrivePolicy{}, cqr.Attributes.RedrivePolicy)
assert.Equal(t, map[string]interface{}(nil), cqr.Attributes.RedriveAllowPolicy)
}
func TestRedrivePolicy_UnmarshalJSON_handles_nested_json(t *testing.T) {
request := struct {
MaxReceiveCount int `json:"maxReceiveCount"`
DeadLetterTargetArn string `json:"deadLetterTargetArn"`
}{
MaxReceiveCount: 100,
DeadLetterTargetArn: "arn:redrive-queue",
}
b, _ := json.Marshal(request)
var r = RedrivePolicy{}
err := r.UnmarshalJSON(b)
assert.Nil(t, err)
assert.Equal(t, StringToInt(100), r.MaxReceiveCount)
assert.Equal(t, fmt.Sprintf("%s:%s", "arn", "redrive-queue"), r.DeadLetterTargetArn)
}
func TestRedrivePolicy_UnmarshalJSON_handles_escaped_string(t *testing.T) {
request := `{"maxReceiveCount":"100","deadLetterTargetArn":"arn:redrive-queue"}`
b, _ := json.Marshal(request)
var r = RedrivePolicy{}
err := r.UnmarshalJSON(b)
assert.Nil(t, err)
assert.Equal(t, StringToInt(100), r.MaxReceiveCount)
assert.Equal(t, fmt.Sprintf("%s:%s", "arn", "redrive-queue"), r.DeadLetterTargetArn)
}
func TestRedrivePolicy_UnmarshalJSON_invalid_json_request_returns_error(t *testing.T) {
request := fmt.Sprintf(`{\"maxReceiveCount\":\"100\",\"deadLetterTargetArn\":\"arn:redrive-queue\"}`)
var r = RedrivePolicy{}
err := r.UnmarshalJSON([]byte(request))
assert.Error(t, err)
assert.Equal(t, StringToInt(0), r.MaxReceiveCount)
assert.Equal(t, "", r.DeadLetterTargetArn)
}
func TestRedrivePolicy_UnmarshalJSON_invalid_type_returns_error(t *testing.T) {
request := `{"maxReceiveCount":true,"deadLetterTargetArn":"arn:redrive-queue"}`
b, _ := json.Marshal(request)
var r = RedrivePolicy{}
err := r.UnmarshalJSON(b)
assert.Error(t, err)
assert.Equal(t, StringToInt(0), r.MaxReceiveCount)
assert.Equal(t, "", r.DeadLetterTargetArn)
}
func TestNewListQueuesRequest_SetAttributesFromForm(t *testing.T) {
form := url.Values{}
form.Add("MaxResults", "1")
form.Add("NextToken", "next-token")
form.Add("QueueNamePrefix", "queue-name-prefix")
lqr := &ListQueueRequest{}
lqr.SetAttributesFromForm(form)
assert.Equal(t, 1, lqr.MaxResults)
assert.Equal(t, "next-token", lqr.NextToken)
assert.Equal(t, "queue-name-prefix", lqr.QueueNamePrefix)
}
func TestListQueuesRequest_SetAttributesFromForm_invalid_max_results(t *testing.T) {
form := url.Values{}
form.Add("MaxResults", "1.0")
form.Add("NextToken", "next-token")
form.Add("QueueNamePrefix", "queue-name-prefix")
lqr := &ListQueueRequest{}
lqr.SetAttributesFromForm(form)
assert.Equal(t, 0, lqr.MaxResults)
assert.Equal(t, "next-token", lqr.NextToken)
assert.Equal(t, "queue-name-prefix", lqr.QueueNamePrefix)
}
func TestGetQueueAttributesRequest_SetAttributesFromForm(t *testing.T) {
form := url.Values{}
form.Add("QueueUrl", "queue-url")
form.Add("AttributeName.1", "attribute-1")
form.Add("AttributeName.2", "attribute-2")
lqr := &GetQueueAttributesRequest{}
lqr.SetAttributesFromForm(form)
assert.Equal(t, "queue-url", lqr.QueueUrl)
assert.Equal(t, 2, len(lqr.AttributeNames))
assert.Contains(t, lqr.AttributeNames, "attribute-1")
assert.Contains(t, lqr.AttributeNames, "attribute-2")
}
func TestGetQueueAttributesRequest_SetAttributesFromForm_skips_invalid_key_sequence(t *testing.T) {
form := url.Values{}
form.Add("QueueUrl", "queue-url")
form.Add("AttributeName.1", "attribute-1")
form.Add("AttributeName.3", "attribute-3")
lqr := &GetQueueAttributesRequest{}
lqr.SetAttributesFromForm(form)
assert.Equal(t, "queue-url", lqr.QueueUrl)
assert.Equal(t, 1, len(lqr.AttributeNames))
assert.Contains(t, lqr.AttributeNames, "attribute-1")
}
func TestSendMessageRequest_SetAttributesFromForm_success(t *testing.T) {
form := url.Values{}
form.Add("MessageAttribute.1.Name", "Attr1")
form.Add("MessageAttribute.1.Value.DataType", "String")
form.Add("MessageAttribute.1.Value.StringValue", "Value1")
form.Add("MessageAttribute.2.Name", "Attr2")
form.Add("MessageAttribute.2.Value.DataType", "Binary")
form.Add("MessageAttribute.2.Value.BinaryValue", "VmFsdWUy")
form.Add("MessageAttribute.3.Name", "")
form.Add("MessageAttribute.3.Value.DataType", "String")
form.Add("MessageAttribute.3.Value.StringValue", "Value")
form.Add("MessageAttribute.4.Name", "Attr4")
form.Add("MessageAttribute.4.Value.DataType", "")
form.Add("MessageAttribute.4.Value.StringValue", "Value4")
r := &SendMessageRequest{
MessageAttributes: make(map[string]MessageAttribute),
MessageSystemAttributes: make(map[string]MessageAttribute),
}
r.SetAttributesFromForm(form)
assert.Equal(t, 2, len(r.MessageAttributes))
assert.NotNil(t, r.MessageAttributes["Attr1"])
attr1 := r.MessageAttributes["Attr1"]
assert.Equal(t, "String", attr1.DataType)
assert.Equal(t, "Value1", attr1.StringValue)
assert.Empty(t, attr1.BinaryValue)
assert.NotNil(t, r.MessageAttributes["Attr2"])
attr2 := r.MessageAttributes["Attr2"]
assert.Equal(t, "Binary", attr2.DataType)
assert.Empty(t, attr2.StringValue)
assert.Equal(t, "VmFsdWUy", attr2.BinaryValue)
}
func TestSetQueueAttributesRequest_SetAttributesFromForm_success(t *testing.T) {
expectedRedrivePolicy := RedrivePolicy{
MaxReceiveCount: 100,
DeadLetterTargetArn: "dead-letter-queue-arn",
}
form := url.Values{}
form.Add("Action", "CreateQueue")
form.Add("QueueName", "new-queue")
form.Add("Version", "2012-11-05")
form.Add("Attribute.1.Name", "DelaySeconds")
form.Add("Attribute.1.Value", "1")
form.Add("Attribute.2.Name", "MaximumMessageSize")
form.Add("Attribute.2.Value", "2")
form.Add("Attribute.3.Name", "MessageRetentionPeriod")
form.Add("Attribute.3.Value", "3")
form.Add("Attribute.4.Name", "Policy")
form.Add("Attribute.4.Value", "{\"i-am\":\"the-policy\"}")
form.Add("Attribute.5.Name", "ReceiveMessageWaitTimeSeconds")
form.Add("Attribute.5.Value", "4")
form.Add("Attribute.6.Name", "VisibilityTimeout")
form.Add("Attribute.6.Value", "5")
form.Add("Attribute.7.Name", "RedrivePolicy")
form.Add("Attribute.7.Value", "{\"maxReceiveCount\": 100, \"deadLetterTargetArn\":\"dead-letter-queue-arn\"}")
form.Add("Attribute.8.Name", "RedriveAllowPolicy")
form.Add("Attribute.8.Value", "{\"i-am\":\"the-redrive-allow-policy\"}")
cqr := &SetQueueAttributesRequest{
Attributes: QueueAttributes{
DelaySeconds: 1,
MaximumMessageSize: 262144,
MessageRetentionPeriod: 345600,
ReceiveMessageWaitTimeSeconds: 10,
VisibilityTimeout: 30,
},
}
cqr.SetAttributesFromForm(form)
assert.Equal(t, StringToInt(1), cqr.Attributes.DelaySeconds)
assert.Equal(t, StringToInt(2), cqr.Attributes.MaximumMessageSize)
assert.Equal(t, StringToInt(3), cqr.Attributes.MessageRetentionPeriod)
assert.Equal(t, map[string]interface{}{"i-am": "the-policy"}, cqr.Attributes.Policy)
assert.Equal(t, StringToInt(4), cqr.Attributes.ReceiveMessageWaitTimeSeconds)
assert.Equal(t, StringToInt(5), cqr.Attributes.VisibilityTimeout)
assert.Equal(t, expectedRedrivePolicy, cqr.Attributes.RedrivePolicy)
assert.Equal(t, map[string]interface{}{"i-am": "the-redrive-allow-policy"}, cqr.Attributes.RedriveAllowPolicy)
}
func TestSetQueueAttributesRequest_SetAttributesFromForm_success_handles_redrive_recieve_count_int(t *testing.T) {
expectedRedrivePolicy := RedrivePolicy{
MaxReceiveCount: 100,
DeadLetterTargetArn: "dead-letter-queue-arn",
}
form := url.Values{}
form.Add("Attribute.1.Name", "RedrivePolicy")
form.Add("Attribute.1.Value", "{\"maxReceiveCount\": 100, \"deadLetterTargetArn\":\"dead-letter-queue-arn\"}")
cqr := &SetQueueAttributesRequest{
Attributes: QueueAttributes{},
}
cqr.SetAttributesFromForm(form)
assert.Equal(t, expectedRedrivePolicy, cqr.Attributes.RedrivePolicy)
}
func TestSetQueueAttributesRequest_SetAttributesFromForm_success_handles_redrive_recieve_count_string(t *testing.T) {
expectedRedrivePolicy := RedrivePolicy{
MaxReceiveCount: 100,
DeadLetterTargetArn: "dead-letter-queue-arn",
}
form := url.Values{}
form.Add("Attribute.1.Name", "RedrivePolicy")
form.Add("Attribute.1.Value", "{\"maxReceiveCount\": \"100\", \"deadLetterTargetArn\":\"dead-letter-queue-arn\"}")
cqr := &SetQueueAttributesRequest{
Attributes: QueueAttributes{},
}
cqr.SetAttributesFromForm(form)
assert.Equal(t, expectedRedrivePolicy, cqr.Attributes.RedrivePolicy)
}
func TestSetQueueAttributesRequest_SetAttributesFromForm_success_default_unparsable_redrive_recieve_count(t *testing.T) {
defaultRedrivePolicy := RedrivePolicy{
MaxReceiveCount: 10,
DeadLetterTargetArn: "dead-letter-queue-arn",
}
form := url.Values{}
form.Add("Attribute.1.Name", "RedrivePolicy")
form.Add("Attribute.1.Value", "{\"maxReceiveCount\": null, \"deadLetterTargetArn\":\"dead-letter-queue-arn\"}")
cqr := &SetQueueAttributesRequest{
Attributes: QueueAttributes{},
}
cqr.SetAttributesFromForm(form)
assert.Equal(t, defaultRedrivePolicy, cqr.Attributes.RedrivePolicy)
}
func TestSetQueueAttributesRequest_SetAttributesFromForm_success_skips_invalid_values(t *testing.T) {
form := url.Values{}
form.Add("Attribute.1.Name", "DelaySeconds")
form.Add("Attribute.1.Value", "garbage")
form.Add("Attribute.2.Name", "MaximumMessageSize")
form.Add("Attribute.2.Value", "garbage")
form.Add("Attribute.3.Name", "MessageRetentionPeriod")
form.Add("Attribute.3.Value", "garbage")
form.Add("Attribute.4.Name", "Policy")
form.Add("Attribute.4.Value", "garbage")
form.Add("Attribute.5.Name", "ReceiveMessageWaitTimeSeconds")
form.Add("Attribute.5.Value", "garbage")
form.Add("Attribute.6.Name", "VisibilityTimeout")
form.Add("Attribute.6.Value", "garbage")
form.Add("Attribute.7.Name", "RedrivePolicy")
form.Add("Attribute.7.Value", "garbage")
form.Add("Attribute.8.Name", "RedriveAllowPolicy")
form.Add("Attribute.8.Value", "garbage")
cqr := &SetQueueAttributesRequest{
Attributes: QueueAttributes{
DelaySeconds: 1,
MaximumMessageSize: 262144,
MessageRetentionPeriod: 345600,
ReceiveMessageWaitTimeSeconds: 10,
VisibilityTimeout: 30,
},
}
cqr.SetAttributesFromForm(form)
assert.Equal(t, StringToInt(1), cqr.Attributes.DelaySeconds)
assert.Equal(t, StringToInt(262144), cqr.Attributes.MaximumMessageSize)
assert.Equal(t, StringToInt(345600), cqr.Attributes.MessageRetentionPeriod)
assert.Equal(t, map[string]interface{}(nil), cqr.Attributes.Policy)
assert.Equal(t, StringToInt(10), cqr.Attributes.ReceiveMessageWaitTimeSeconds)
assert.Equal(t, StringToInt(30), cqr.Attributes.VisibilityTimeout)
assert.Equal(t, RedrivePolicy{}, cqr.Attributes.RedrivePolicy)
assert.Equal(t, map[string]interface{}(nil), cqr.Attributes.RedriveAllowPolicy)
}
func TestNewCreateTopicRequest(t *testing.T) {
defer func() {
ResetApp()
}()
result := NewCreateTopicRequest()
assert.Equal(t, false, result.Attributes.FifoTopic)
assert.Equal(t, StringToInt(1), result.Attributes.SignatureVersion)
assert.Equal(t, "Active", result.Attributes.TracingConfig)
assert.Equal(t, false, result.Attributes.ContentBasedDeduplication)
}
func TestCreateTopicRequest_SetAttributesFromForm_success(t *testing.T) {
form := url.Values{}
form.Add("Action", "CreateQueue")
form.Add("QueueName", "new-queue")
form.Add("Version", "2012-11-05")
form.Add("Attribute.1.Name", "DeliveryPolicy")
form.Add("Attribute.1.Value", "{\"i-am\":\"the-policy\", \"name\":\"delivery-policy\"}")
form.Add("Attribute.2.Name", "DisplayName")
form.Add("Attribute.2.Value", "Foo")
form.Add("Attribute.3.Name", "FifoTopic")
form.Add("Attribute.3.Value", "true")
form.Add("Attribute.4.Name", "Policy")
form.Add("Attribute.4.Value", "{\"i-am\":\"the-policy\", \"name\":\"policy\"}")
form.Add("Attribute.5.Name", "SignatureVersion")
form.Add("Attribute.5.Value", "99")
form.Add("Attribute.6.Name", "TracingConfig")
form.Add("Attribute.6.Value", "PassThrough")
form.Add("Attribute.7.Name", "KmsMasterKeyId")
form.Add("Attribute.7.Value", "1234abcd-12ab-34cd-56ef-1234567890ab")
form.Add("Attribute.8.Name", "ArchivePolicy")
form.Add("Attribute.8.Value", "{\"i-am\":\"the-policy\", \"name\":\"archive-policy\"}")
form.Add("Attribute.9.Name", "BeginningArchiveTime")
form.Add("Attribute.9.Value", "2024-07-01T23:59:59+09:00")
form.Add("Attribute.10.Name", "ContentBasedDeduplication")
form.Add("Attribute.10.Value", "true")
ctr := &CreateTopicRequest{}
ctr.SetAttributesFromForm(form)
assert.Equal(t, 2, len(ctr.Attributes.DeliveryPolicy))
assert.Equal(t, "the-policy", ctr.Attributes.DeliveryPolicy["i-am"])
assert.Equal(t, "delivery-policy", ctr.Attributes.DeliveryPolicy["name"])
assert.Equal(t, "Foo", ctr.Attributes.DisplayName)
assert.Equal(t, true, ctr.Attributes.FifoTopic)
assert.Equal(t, 2, len(ctr.Attributes.Policy))
assert.Equal(t, "the-policy", ctr.Attributes.Policy["i-am"])
assert.Equal(t, "policy", ctr.Attributes.Policy["name"])
assert.Equal(t, StringToInt(99), ctr.Attributes.SignatureVersion)
assert.Equal(t, "PassThrough", ctr.Attributes.TracingConfig)
assert.Equal(t, "1234abcd-12ab-34cd-56ef-1234567890ab", ctr.Attributes.KmsMasterKeyId)
assert.Equal(t, 2, len(ctr.Attributes.ArchivePolicy))
assert.Equal(t, "the-policy", ctr.Attributes.ArchivePolicy["i-am"])
assert.Equal(t, "archive-policy", ctr.Attributes.ArchivePolicy["name"])
assert.Equal(t, "2024-07-01T23:59:59+09:00", ctr.Attributes.BeginningArchiveTime)
assert.Equal(t, true, ctr.Attributes.ContentBasedDeduplication)
}
func TestSubscribeRequest_SetAttributesFromForm_success(t *testing.T) {
form := url.Values{}
form.Add("Attributes.entry.1.key", "RawMessageDelivery")
form.Add("Attributes.entry.1.value", "true")
form.Add("Attributes.entry.2.key", "FilterPolicy")
form.Add("Attributes.entry.2.value", "{\"filter\": [\"policy\"]}")
cqr := &SubscribeRequest{
Attributes: SubscriptionAttributes{},
}
cqr.SetAttributesFromForm(form)
assert.True(t, cqr.Attributes.RawMessageDelivery)
assert.Equal(t, FilterPolicy{"filter": []string{"policy"}}, cqr.Attributes.FilterPolicy)
}
func TestSubscribeRequest_SetAttributesFromForm_skips_invalid_values(t *testing.T) {
form := url.Values{}
form.Add("Attributes.entry.1.key", "RawMessageDelivery")
form.Add("Attributes.entry.1.value", "garbage")
form.Add("Attributes.entry.2.key", "FilterPolicy")
form.Add("Attributes.entry.2.value", "also-garbage")
cqr := &SubscribeRequest{
Attributes: SubscriptionAttributes{},
}
cqr.SetAttributesFromForm(form)
assert.False(t, cqr.Attributes.RawMessageDelivery)
assert.Equal(t, FilterPolicy(nil), cqr.Attributes.FilterPolicy)
}
func TestSubscribeRequest_SetAttributesFromForm_stops_if_attributes_not_numbered_sequentially(t *testing.T) {
form := url.Values{}
form.Add("Attributes.entry.2.key", "RawMessageDelivery")
form.Add("Attributes.entry.2.value", "garbage")
form.Add("Attributes.entry.3.key", "FilterPolicy")
form.Add("Attributes.entry.3.value", "also-garbage")
cqr := &SubscribeRequest{
Attributes: SubscriptionAttributes{},
}
cqr.SetAttributesFromForm(form)
assert.False(t, cqr.Attributes.RawMessageDelivery)
assert.Equal(t, FilterPolicy(nil), cqr.Attributes.FilterPolicy)
}
func Test_DeleteMessageBatchRequest_SetAttributesFromForm_success(t *testing.T) {
form := url.Values{}
form.Add("DeleteMessageBatchRequestEntry.1.Id", "message-id-1")
form.Add("DeleteMessageBatchRequestEntry.1.ReceiptHandle", "receipt-handle-1")
form.Add("DeleteMessageBatchRequestEntry.2.Id", "message-id-2")
form.Add("DeleteMessageBatchRequestEntry.2.ReceiptHandle", "receipt-handle-2")
form.Add("DeleteMessageBatchRequestEntry.3.Id", "message-id-3")
form.Add("DeleteMessageBatchRequestEntry.3.ReceiptHandle", "receipt-handle-3")
dmbr := &DeleteMessageBatchRequest{}
dmbr.SetAttributesFromForm(form)
assert.Len(t, dmbr.Entries, 3)
assert.Equal(t, "message-id-1", dmbr.Entries[0].Id)
assert.Equal(t, "receipt-handle-1", dmbr.Entries[0].ReceiptHandle)
assert.Equal(t, "message-id-2", dmbr.Entries[1].Id)
assert.Equal(t, "receipt-handle-2", dmbr.Entries[1].ReceiptHandle)
assert.Equal(t, "message-id-3", dmbr.Entries[2].Id)
assert.Equal(t, "receipt-handle-3", dmbr.Entries[2].ReceiptHandle)
}
func Test_DeleteMessageBatchRequest_SetAttributesFromForm_stops_at_non_sequential_keys(t *testing.T) {
form := url.Values{}
form.Add("DeleteMessageBatchRequestEntry.1.Id", "message-id-1")
form.Add("DeleteMessageBatchRequestEntry.1.ReceiptHandle", "receipt-handle-1")
form.Add("DeleteMessageBatchRequestEntry.4.Id", "message-id-2")
form.Add("DeleteMessageBatchRequestEntry.4.ReceiptHandle", "receipt-handle-2")
form.Add("DeleteMessageBatchRequestEntry.3.Id", "message-id-3")
form.Add("DeleteMessageBatchRequestEntry.3.ReceiptHandle", "receipt-handle-3")
dmbr := &DeleteMessageBatchRequest{}
dmbr.SetAttributesFromForm(form)
assert.Len(t, dmbr.Entries, 1)
assert.Equal(t, "message-id-1", dmbr.Entries[0].Id)
assert.Equal(t, "receipt-handle-1", dmbr.Entries[0].ReceiptHandle)
}
func Test_DeleteMessageBatchRequest_SetAttributesFromForm_stops_at_invalid_keys(t *testing.T) {
form := url.Values{}
form.Add("DeleteMessageBatchRequestEntry.1.Id", "message-id-1")
form.Add("DeleteMessageBatchRequestEntry.1.ReceiptHandle", "receipt-handle-1")
form.Add("INVALID_DeleteMessageBatchRequestEntry.2.Id", "message-id-2")
form.Add("DeleteMessageBatchRequestEntry.2.ReceiptHandle", "receipt-handle-2")
form.Add("DeleteMessageBatchRequestEntry.3.Id", "message-id-3")
form.Add("DeleteMessageBatchRequestEntry.3.ReceiptHandle", "receipt-handle-3")
dmbr := &DeleteMessageBatchRequest{}
dmbr.SetAttributesFromForm(form)
assert.Len(t, dmbr.Entries, 1)
assert.Equal(t, "message-id-1", dmbr.Entries[0].Id)
assert.Equal(t, "receipt-handle-1", dmbr.Entries[0].ReceiptHandle)
}
func TestPublishRequest_SetAttributesFromForm_success_concurrent(t *testing.T) {
form := url.Values{}
form.Add("MessageAttributes.entry.1.Name", "test1")
form.Add("MessageAttributes.entry.1.Value.DataType", "String")
form.Add("MessageAttributes.entry.1.Value.StringValue", "sample-string")
form.Add("MessageAttributes.entry.2.Name", "test2")
form.Add("MessageAttributes.entry.2.Value.DataType", "Binary")
form.Add("MessageAttributes.entry.2.Value.BinaryValue", "YmluYXJ5LXZhbHVl")
// if the code is not thread-safe, repeated runs increase the chance of detecting a race.
for r := 0; r < 10; r++ {
var wg sync.WaitGroup
goroutineCount := 40
// launch goroutines in parallel to simulate concurrent access.
for g := 0; g < goroutineCount; g++ {
wg.Add(1)
go func() {
defer wg.Done()
// introduce a random delay to encourage goroutine interleaving
time.Sleep(time.Duration(rand.Intn(5)) * time.Millisecond)
cqr := &PublishRequest{
MessageAttributes: make(map[string]MessageAttribute),
}
cqr.SetAttributesFromForm(form)
// validate the expected DataType values
assert.Equal(t, "String", cqr.MessageAttributes["test1"].DataType)
assert.Equal(t, "Binary", cqr.MessageAttributes["test2"].DataType)
}()
}
wg.Wait()
}
}
func TestParseMessageAttributes(t *testing.T) {
for _, tc := range []struct {
description string
values url.Values
keyPrefix string
want map[string]MessageAttribute
}{
{
description: "empty",
values: url.Values{},
keyPrefix: "foo",
want: nil,
},
{
description: "simple",
values: url.Values{
"MessageAttribute.1.Name": []string{"Attr1"},
"MessageAttribute.1.Value.DataType": []string{"String"},
"MessageAttribute.1.Value.StringValue": []string{"Value1"},
"MessageAttribute.2.Name": []string{"Attr2"},
"MessageAttribute.2.Value.DataType": []string{"Binary"},
"MessageAttribute.2.Value.BinaryValue": []string{"VmFsdWUy"},
},
keyPrefix: "MessageAttribute",
want: map[string]MessageAttribute{
"Attr1": {
DataType: "String",
StringValue: "Value1",
BinaryValue: "",
},
"Attr2": {
DataType: "Binary",
BinaryValue: "VmFsdWUy",
},
},
},
{
description: "attributes after empty name ignored",
values: url.Values{
"MessageAttribute.1.Name": []string{""},
"MessageAttribute.1.Value.DataType": []string{"String"},
"MessageAttribute.1.Value.StringValue": []string{"Value4"},
"MessageAttribute.2.Name": []string{"Attr2"},
"MessageAttribute.2.Value.DataType": []string{"Binary"},
"MessageAttribute.2.Value.BinaryValue": []string{"VmFsdWUy"},
},
keyPrefix: "MessageAttribute",
want: nil,
},
{
description: "attributes after missing number ignored",
values: url.Values{
// Note starting from 2
"MessageAttribute.2.Name": []string{"Attr2"},
"MessageAttribute.2.Value.DataType": []string{"Binary"},
"MessageAttribute.2.Value.BinaryValue": []string{"VmFsdWUy"},
},
keyPrefix: "MessageAttribute",
want: nil,
},
{
description: "empty DataType ignored",
values: url.Values{
"MessageAttribute.1.Name": []string{"Attr4"},
"MessageAttribute.1.Value.DataType": []string{""},
"MessageAttribute.1.Value.StringValue": []string{"Value4"},
},
keyPrefix: "MessageAttribute",
want: nil,
},
} {
t.Run(tc.description, func(t *testing.T) {
got := parseMessageAttributes(tc.values, tc.keyPrefix)
assert.Equal(t, tc.want, got)
})
}
}
+340
View File
@@ -0,0 +1,340 @@
package models
import (
"encoding/xml"
)
type ResponseMetadata struct {
RequestId string `xml:"RequestId"`
}
// NOTE: Every response in here MUST implement the `AbstractResponseBody` interface in order to be used
// in `encodeResponse`
/*** Error Responses ***/
type ErrorResult struct {
Type string `json:"Type,omitempty" xml:"Type,omitempty"`
Code string `json:"Code,omitempty" xml:"Code,omitempty"`
Message string `json:"Message,omitempty" xml:"Message,omitempty"`
}
type ErrorResponse struct {
Result ErrorResult `json:"Error" xml:"Error"`
RequestId string `json:"RequestId" xml:"RequestId"`
}
func (r ErrorResponse) GetResult() interface{} {
return r.Result
}
func (r ErrorResponse) GetRequestId() string {
return r.RequestId
}
/*** Receive Message Response */
type ReceiveMessageResult struct {
Messages []*ResultMessage `json:"Messages" xml:"Message,omitempty"`
}
type ReceiveMessageResponse struct {
Xmlns string `json:"Xmlns" xml:"xmlns,attr"`
Result ReceiveMessageResult `json:"ReceiveMessageResult" xml:"ReceiveMessageResult"`
Metadata ResponseMetadata `json:"ResponseMetadata" xml:"ResponseMetadata"`
}
func (r ReceiveMessageResponse) GetResult() interface{} {
return r.Result
}
func (r ReceiveMessageResponse) GetRequestId() string {
return r.Metadata.RequestId
}
type ResultMessage struct {
MessageId string `json:"MessageId,omitempty" xml:"MessageId,omitempty"`
ReceiptHandle string `json:"ReceiptHandle,omitempty" xml:"ReceiptHandle,omitempty"`
MD5OfBody string `json:"MD5OfBody,omitempty" xml:"MD5OfBody,omitempty"`
Body string `json:"Body,omitempty" xml:"Body,omitempty"`
MD5OfMessageAttributes string `json:"MD5OfMessageAttributes,omitempty" xml:"MD5OfMessageAttributes,omitempty"`
MessageAttributes map[string]MessageAttribute `json:"MessageAttributes,omitempty" xml:"MessageAttribute,omitempty,attr"`
Attributes map[string]string `json:"Attributes,omitempty" xml:"Attribute,omitempty,attr"`
}
// MarshalXML is a custom marshaler for the ResultMessage struct. We need it because we need to convert the
// maps into something that can be shown as XML. If we ever get rid of the XML response parsing this can go,
// and that would be glorious.
func (r *ResultMessage) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
type Attributes struct {
Name string `xml:"Name,omitempty"`
Value string `xml:"Value,omitempty"`
}
var attrs []Attributes
for key, value := range r.Attributes {
attribute := Attributes{
Name: key,
Value: value,
}
attrs = append(attrs, attribute)
}
type MessageAttributes struct {
Name string `xml:"Name,omitempty"`
Value MessageAttribute `xml:"Value,omitempty"`
}
var messageAttrs []MessageAttributes
for key, value := range r.MessageAttributes {
attribute := MessageAttributes{
Name: key,
Value: value,
}
messageAttrs = append(messageAttrs, attribute)
}
e.EncodeToken(start)
// Encode the fields
e.EncodeElement(r.MessageId, xml.StartElement{Name: xml.Name{Local: "MessageId"}})
e.EncodeElement(r.ReceiptHandle, xml.StartElement{Name: xml.Name{Local: "ReceiptHandle"}})
e.EncodeElement(r.MD5OfBody, xml.StartElement{Name: xml.Name{Local: "MD5OfBody"}})
e.EncodeElement(r.Body, xml.StartElement{Name: xml.Name{Local: "Body"}})
e.EncodeElement(attrs, xml.StartElement{Name: xml.Name{Local: "Attribute"}})
e.EncodeElement(messageAttrs, xml.StartElement{Name: xml.Name{Local: "MessageAttribute"}})
e.EncodeToken(xml.EndElement{Name: start.Name})
return nil
}
type ChangeMessageVisibilityResult struct {
Xmlns string `json:"Xmlns" xml:"xmlns,attr"`
Metadata ResponseMetadata `json:"ResponseMetadata" xml:"ResponseMetadata"`
}
func (r ChangeMessageVisibilityResult) GetResult() interface{} {
return nil
}
func (r ChangeMessageVisibilityResult) GetRequestId() string {
return r.Metadata.RequestId
}
/*** Create Queue Response */
type CreateQueueResult struct {
QueueUrl string `json:"QueueUrl" xml:"QueueUrl"`
}
type CreateQueueResponse struct {
Xmlns string `json:"Xmlns" xml:"xmlns,attr"`
Result CreateQueueResult `json:"CreateQueueResult" xml:"CreateQueueResult"`
Metadata ResponseMetadata `json:"ResponseMetadata" xml:"ResponseMetadata"`
}
func (r CreateQueueResponse) GetResult() interface{} {
return r.Result
}
func (r CreateQueueResponse) GetRequestId() string {
return r.Metadata.RequestId
}
/*** List Queues Response */
type ListQueuesResult struct {
// NOTE: the old XML sdks depend on QueueUrl, and the new JSON ones need QueueUrls
QueueUrls []string `json:"QueueUrls" xml:"QueueUrl"`
}
type ListQueuesResponse struct {
Xmlns string `json:"Xmlns" xml:"xmlns,attr"`
Result ListQueuesResult `json:"ListQueuesResult" xml:"ListQueuesResult"`
Metadata ResponseMetadata `json:"ResponseMetadata" xml:"ResponseMetadata"`
}
func (r ListQueuesResponse) GetResult() interface{} {
return r.Result
}
func (r ListQueuesResponse) GetRequestId() string {
return r.Metadata.RequestId
}
/*** Get Queue QueueAttributes ***/
type Attribute struct {
Name string `json:"Name,omitempty" xml:"Name,omitempty"`
Value string `json:"Value,omitempty" xml:"Value,omitempty"`
}
type GetQueueAttributesResult struct {
/* VisibilityTimeout, DelaySeconds, ReceiveMessageWaitTimeSeconds, ApproximateNumberOfMessages
ApproximateNumberOfMessagesNotVisible, CreatedTimestamp, LastModifiedTimestamp, QueueArn */
Attrs []Attribute `json:"Attributes,omitempty" xml:"Attribute,omitempty"`
}
type GetQueueAttributesResponse struct {
Xmlns string `json:"Xmlns" xml:"xmlns,attr"`
Result GetQueueAttributesResult `json:"GetQueueAttributesResult" xml:"GetQueueAttributesResult"`
Metadata ResponseMetadata `json:"ResponseMetadata" xml:"ResponseMetadata"`
}
func (r GetQueueAttributesResponse) GetResult() interface{} {
result := map[string]string{}
for _, attr := range r.Result.Attrs {
result[attr.Name] = attr.Value
}
return map[string]map[string]string{"Attributes": result}
}
func (r GetQueueAttributesResponse) GetRequestId() string {
return r.Metadata.RequestId
}
/*** Send Message Response */
type SendMessageResult struct {
MD5OfMessageAttributes string `json:"MD5OfMessageAttributes,omitempty" xml:"MD5OfMessageAttributes,omitempty"`
MD5OfMessageBody string `json:"MD5OfMessageBody" xml:"MD5OfMessageBody"`
MessageId string `json:"MessageId" xml:"MessageId"`
SequenceNumber string `json:"SequenceNumber,omitempty" xml:"SequenceNumber,omitempty"`
}
type SendMessageResponse struct {
Xmlns string `json:"Xmlns" xml:"xmlns,attr"`
Result SendMessageResult `json:"SendMessageResult" xml:"SendMessageResult"`
Metadata ResponseMetadata `json:"ResponseMetadata" xml:"ResponseMetadata"`
}
func (r SendMessageResponse) GetResult() interface{} {
return r.Result
}
func (r SendMessageResponse) GetRequestId() string {
return r.Metadata.RequestId
}
/*** Delete Message Response */
type DeleteMessageResponse struct {
Xmlns string `json:"Xmlns" xml:"xmlns,attr"`
Metadata ResponseMetadata `json:"ResponseMetadata" xml:"ResponseMetadata"`
}
func (r DeleteMessageResponse) GetResult() interface{} {
return nil
}
func (r DeleteMessageResponse) GetRequestId() string {
return r.Metadata.RequestId
}
/*** Get Queue Url Response */
type GetQueueUrlResult struct {
QueueUrl string `json:"QueueUrl,omitempty" xml:"QueueUrl,omitempty"`
}
type GetQueueUrlResponse struct {
Xmlns string `json:"Xmlns" xml:"xmlns,attr"`
Result GetQueueUrlResult `json:"GetQueueUrlResult" xml:"GetQueueUrlResult"`
Metadata ResponseMetadata `json:"ResponseMetadata" xml:"ResponseMetadata"`
}
func (r GetQueueUrlResponse) GetResult() interface{} {
return r.Result
}
func (r GetQueueUrlResponse) GetRequestId() string {
return r.Metadata.RequestId
}
type SendMessageBatchResultEntry struct {
Id string `json:"Id" xml:"Id"`
MessageId string `json:"MessageId" xml:"MessageId"`
MD5OfMessageBody string `json:"MD5OfMessageBody,omitempty" xml:"MD5OfMessageBody,omitempty"`
MD5OfMessageAttributes string `json:"MD5OfMessageAttributes,omitempty" xml:"MD5OfMessageAttributes,omitempty"`
SequenceNumber string `json:"SequenceNumber" xml:"SequenceNumber"`
}
/*** Send Message Batch Response */
type SendMessageBatchResponse struct {
Xmlns string `json:"Xmlns" xml:"xmlns,attr"`
Result SendMessageBatchResult `json:"SendMessageBatchResult" xml:"SendMessageBatchResult"`
Metadata ResponseMetadata `json:"ResponseMetadata" xml:"ResponseMetadata"`
}
type SendMessageBatchResult struct {
Entry []SendMessageBatchResultEntry `json:"SendMessageBatchResultEntry" xml:"SendMessageBatchResultEntry"`
Error []BatchResultErrorEntry `json:"BatchResultErrorEntry,omitempty" xml:"BatchResultErrorEntry,omitempty"`
}
func (r SendMessageBatchResponse) GetResult() interface{} {
return r.Result
}
func (r SendMessageBatchResponse) GetRequestId() string {
return r.Metadata.RequestId
}
type BatchResultErrorEntry struct {
Code string `json:"Code" xml:"Code"`
Id string `json:"Id" xml:"Id"`
Message string `json:"Message,omitempty" xml:"Message,omitempty"`
SenderFault bool `json:"SenderFault" xml:"SenderFault"`
}
type SetQueueAttributesResponse struct {
Xmlns string `json:"Xmlns" xml:"xmlns,attr"`
Metadata ResponseMetadata `json:"ResponseMetadata" xml:"ResponseMetadata"`
}
func (r SetQueueAttributesResponse) GetResult() interface{} {
return nil
}
func (r SetQueueAttributesResponse) GetRequestId() string {
return r.Metadata.RequestId
}
/*** Purge Queue Response */
type PurgeQueueResponse struct {
Xmlns string `json:"Xmlns" xml:"xmlns,attr"`
Metadata ResponseMetadata `json:"ResponseMetadata" xml:"ResponseMetadata"`
}
func (r PurgeQueueResponse) GetResult() interface{} {
return nil
}
func (r PurgeQueueResponse) GetRequestId() string {
return r.Metadata.RequestId
}
/*** Delete Queue Response */
type DeleteQueueResponse struct {
Xmlns string `json:"Xmlns" xml:"xmlns,attr"`
Metadata ResponseMetadata `json:"ResponseMetadata" xml:"ResponseMetadata"`
}
func (r DeleteQueueResponse) GetResult() interface{} {
return nil
}
func (r DeleteQueueResponse) GetRequestId() string {
return r.Metadata.RequestId
}
/*** Delete Message Batch Response ***/
type DeleteMessageBatchResultEntry struct {
Id string `json:"Id" xml:"Id"`
}
type DeleteMessageBatchResult struct {
Successful []DeleteMessageBatchResultEntry `json:"DeleteMessageBatchResultEntry" xml:"DeleteMessageBatchResultEntry"`
Failed []BatchResultErrorEntry `json:"BatchResultErrorEntry,omitempty" xml:"BatchResultErrorEntry,omitempty"`
}
type DeleteMessageBatchResponse struct {
Xmlns string `json:"Xmlns" xml:"xmlns,attr"`
Result DeleteMessageBatchResult `json:"DeleteMessageBatchResult" xml:"DeleteMessageBatchResult"`
Metadata ResponseMetadata `json:"ResponseMetadata" xml:"ResponseMetadata"`
}
func (r DeleteMessageBatchResponse) GetResult() interface{} {
return r.Result
}
func (r DeleteMessageBatchResponse) GetRequestId() string {
return r.Metadata.RequestId
}
+110
View File
@@ -0,0 +1,110 @@
package models
import (
"encoding/xml"
"testing"
"github.com/stretchr/testify/assert"
)
// NOTE: For now, we're only going to test those methods that do something other than just return a field
func TestGetQueueAttributesResponse_GetResult(t *testing.T) {
gqa := GetQueueAttributesResponse{
Result: GetQueueAttributesResult{Attrs: []Attribute{
{Name: "attribute-name1", Value: "attribute-value1"},
{Name: "attribute-name2", Value: "attribute-value2"},
}},
}
expectedAttributes := map[string]map[string]string{
"Attributes": {
"attribute-name1": "attribute-value1",
"attribute-name2": "attribute-value2",
},
}
result := gqa.GetResult()
assert.Equal(t, expectedAttributes, result)
}
func Test_ResultMessage_MarshalXML_success_with_attributes(t *testing.T) {
input := &ResultMessage{
MessageId: "message-id",
ReceiptHandle: "receipt-handle",
MD5OfBody: "body-md5",
Body: "message-body",
MD5OfMessageAttributes: "message-attrs-md5",
MessageAttributes: map[string]MessageAttribute{
"attr1": {
DataType: "String",
StringValue: "string-value",
},
"attr2": {
DataType: "Binary",
BinaryValue: "binary-value",
},
"attr3": {
DataType: "Number",
StringValue: "number-value",
},
},
Attributes: map[string]string{
"ApproximateFirstReceiveTimestamp": "1",
"SenderId": "2",
"ApproximateReceiveCount": "3",
"SentTimestamp": "4",
},
}
result, err := xml.Marshal(input)
assert.Nil(t, err)
resultString := string(result)
// We have to assert piecemeal like this, the maps go into their lists unordered, which will randomly break this.
entry := "<ResultMessage><MessageId>message-id</MessageId><ReceiptHandle>receipt-handle</ReceiptHandle><MD5OfBody>body-md5</MD5OfBody><Body>message-body</Body>"
assert.Contains(t, resultString, entry)
entry = "<Attribute><Name>ApproximateFirstReceiveTimestamp</Name><Value>1</Value></Attribute>"
assert.Contains(t, resultString, entry)
entry = "<Attribute><Name>SenderId</Name><Value>2</Value></Attribute>"
assert.Contains(t, resultString, entry)
entry = "<Attribute><Name>ApproximateReceiveCount</Name><Value>3</Value></Attribute>"
assert.Contains(t, resultString, entry)
entry = "<Attribute><Name>SentTimestamp</Name><Value>4</Value></Attribute>"
assert.Contains(t, resultString, entry)
entry = "<MessageAttribute><Name>attr1</Name><Value><DataType>String</DataType><StringValue>string-value</StringValue></Value></MessageAttribute>"
assert.Contains(t, resultString, entry)
entry = "<MessageAttribute><Name>attr2</Name><Value><BinaryValue>binary-value</BinaryValue><DataType>Binary</DataType></Value></MessageAttribute>"
assert.Contains(t, resultString, entry)
entry = "<MessageAttribute><Name>attr3</Name><Value><DataType>Number</DataType><StringValue>number-value</StringValue></Value></MessageAttribute>"
assert.Contains(t, resultString, entry)
entry = "</ResultMessage>"
assert.Contains(t, resultString, entry)
}
func Test_ResultMessage_MarshalXML_success_no_attributes(t *testing.T) {
input := &ResultMessage{
MessageId: "message-id",
ReceiptHandle: "receipt-handle",
MD5OfBody: "body-md5",
Body: "message-body",
MD5OfMessageAttributes: "message-attrs-md5",
}
expectedOutput := "<ResultMessage><MessageId>message-id</MessageId><ReceiptHandle>receipt-handle</ReceiptHandle><MD5OfBody>body-md5</MD5OfBody><Body>message-body</Body></ResultMessage>"
result, err := xml.Marshal(input)
assert.Nil(t, err)
resultString := string(result)
assert.Equal(t, resultString, expectedOutput)
}