fix: 7 performance/correctness fixes — v0.1.20
1. Убрано логирование тела сообщения (256KB I/O на каждый send — perf+security) 2. SentTimestamp исправлен: m.SentTime вместо time.Now() (баг) 3. MD5 не пересчитывается на ReceiveMessage — используется кэш из SendMessage 4. ChangeMessageVisibility/batch теперь персистит в Redis (баг — потеря данных) 5. MessageDoesNotExist error code: QueueExists → ReceiptHandleIsInvalid (copy-paste баг) 6. copystructure убран из GetQueueAttributes — простой map lookup 7. SNS dead code удалён (SnsErrors, SnsErrorType — не используется в SQS сервисе) Tested: quick_test 31/31 PASS, deployed v0.1.20
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
// Изменено: 2026-04-09
|
||||
// Изменено: 2026-04-11 — добавлена Redis persistence
|
||||
// ChangeMessageVisibilityV1 — меняет visibility timeout сообщения в очереди тенанта.
|
||||
package gosqs
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
"shared-sqs/app/interfaces"
|
||||
"shared-sqs/app/models"
|
||||
"shared-sqs/app/persistence"
|
||||
"shared-sqs/app/utils"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
@@ -75,6 +76,10 @@ func ChangeMessageVisibilityV1(req *http.Request) (int, interfaces.AbstractRespo
|
||||
break
|
||||
}
|
||||
}
|
||||
// Персистим изменение в Redis под Lock
|
||||
if messageFound {
|
||||
persistence.SaveQueue(key, models.SyncQueues.Queues[key])
|
||||
}
|
||||
models.SyncQueues.Unlock()
|
||||
if !messageFound {
|
||||
return utils.CreateErrorResponseV1("MessageNotInFlight", true)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Создано: 2026-04-11
|
||||
// Создано: 2026-04-11, Изменено: 2026-04-11 — добавлена Redis persistence
|
||||
// ChangeMessageVisibilityBatchV1 — пакетная смена таймаута видимости (до 10 сообщений).
|
||||
// Паттерн аналогичен DeleteMessageBatchV1: валидация Id, цикл по записям, partial success.
|
||||
package gosqs
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
|
||||
"shared-sqs/app/interfaces"
|
||||
"shared-sqs/app/models"
|
||||
"shared-sqs/app/persistence"
|
||||
"shared-sqs/app/utils"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
@@ -109,6 +110,11 @@ func ChangeMessageVisibilityBatchV1(req *http.Request) (int, interfaces.Abstract
|
||||
}
|
||||
}
|
||||
|
||||
// Персистим изменения в Redis под Lock
|
||||
if len(successEntries) > 0 {
|
||||
persistence.SaveQueue(key, models.SyncQueues.Queues[key])
|
||||
}
|
||||
|
||||
respStruct := models.ChangeMessageVisibilityBatchResponse{
|
||||
Xmlns: models.BaseXmlns,
|
||||
Result: models.ChangeMessageVisibilityBatchResult{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Изменено: 2026-04-09
|
||||
// Изменено: 2026-04-11 — убрана зависимость от copystructure (лишняя аллокация)
|
||||
// GetQueueAttributesV1 — возвращает атрибуты очереди тенанта.
|
||||
package gosqs
|
||||
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
"shared-sqs/app/interfaces"
|
||||
"shared-sqs/app/models"
|
||||
"shared-sqs/app/utils"
|
||||
"github.com/mitchellh/copystructure"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
@@ -32,29 +31,29 @@ if t == nil {
|
||||
return utils.CreateErrorResponseV1("InvalidClientTokenId", true)
|
||||
}
|
||||
|
||||
requestedAttributes := func() map[string]bool {
|
||||
attrs := map[string]bool{}
|
||||
if len(requestBody.AttributeNames) == 0 {
|
||||
return map[string]bool{"All": true}
|
||||
}
|
||||
for _, attr := range requestBody.AttributeNames {
|
||||
if "All" == attr {
|
||||
return map[string]bool{"All": true}
|
||||
}
|
||||
attrs[attr] = true
|
||||
}
|
||||
return attrs
|
||||
}()
|
||||
// Определяем набор запрошенных атрибутов (или All)
|
||||
requestedAttributes := func() map[string]bool {
|
||||
attrs := map[string]bool{}
|
||||
if len(requestBody.AttributeNames) == 0 {
|
||||
return map[string]bool{"All": true}
|
||||
}
|
||||
for _, attr := range requestBody.AttributeNames {
|
||||
if "All" == attr {
|
||||
return map[string]bool{"All": true}
|
||||
}
|
||||
attrs[attr] = true
|
||||
}
|
||||
return attrs
|
||||
}()
|
||||
|
||||
dupe, _ := copystructure.Copy(models.AvailableQueueAttributes)
|
||||
includedAttributes, _ := dupe.(map[string]bool)
|
||||
_, ok = requestedAttributes["All"]
|
||||
if !ok {
|
||||
for attr := range includedAttributes {
|
||||
if _, ok := requestedAttributes[attr]; !ok {
|
||||
delete(includedAttributes, attr)
|
||||
}
|
||||
}
|
||||
// Фильтруем атрибуты без deep copy — простая проверка через map lookup
|
||||
_, wantAll := requestedAttributes["All"]
|
||||
shouldInclude := func(attr string) bool {
|
||||
if wantAll {
|
||||
return true
|
||||
}
|
||||
_, ok := requestedAttributes[attr]
|
||||
return ok
|
||||
}
|
||||
|
||||
uriSegments := strings.Split(requestBody.QueueUrl, "/")
|
||||
@@ -72,37 +71,37 @@ log.Errorf("Get Queue Attributes: %s queue does not exist for tenant %s", queueN
|
||||
return utils.CreateErrorResponseV1("QueueNotFound", true)
|
||||
}
|
||||
|
||||
if _, ok := includedAttributes["DelaySeconds"]; ok {
|
||||
if shouldInclude("DelaySeconds") {
|
||||
queueAttributes = append(queueAttributes, models.Attribute{Name: "DelaySeconds", Value: strconv.Itoa(queue.DelaySeconds)})
|
||||
}
|
||||
if _, ok := includedAttributes["MaximumMessageSize"]; ok {
|
||||
if shouldInclude("MaximumMessageSize") {
|
||||
queueAttributes = append(queueAttributes, models.Attribute{Name: "MaximumMessageSize", Value: strconv.Itoa(queue.MaximumMessageSize)})
|
||||
}
|
||||
if _, ok := includedAttributes["MessageRetentionPeriod"]; ok {
|
||||
if shouldInclude("MessageRetentionPeriod") {
|
||||
queueAttributes = append(queueAttributes, models.Attribute{Name: "MessageRetentionPeriod", Value: strconv.Itoa(queue.MessageRetentionPeriod)})
|
||||
}
|
||||
if _, ok := includedAttributes["ReceiveMessageWaitTimeSeconds"]; ok {
|
||||
if shouldInclude("ReceiveMessageWaitTimeSeconds") {
|
||||
queueAttributes = append(queueAttributes, models.Attribute{Name: "ReceiveMessageWaitTimeSeconds", Value: strconv.Itoa(queue.ReceiveMessageWaitTimeSeconds)})
|
||||
}
|
||||
if _, ok := includedAttributes["VisibilityTimeout"]; ok {
|
||||
if shouldInclude("VisibilityTimeout") {
|
||||
queueAttributes = append(queueAttributes, models.Attribute{Name: "VisibilityTimeout", Value: strconv.Itoa(queue.VisibilityTimeout)})
|
||||
}
|
||||
if _, ok := includedAttributes["ApproximateNumberOfMessages"]; ok {
|
||||
if shouldInclude("ApproximateNumberOfMessages") {
|
||||
queueAttributes = append(queueAttributes, models.Attribute{Name: "ApproximateNumberOfMessages", Value: strconv.Itoa(len(queue.Messages))})
|
||||
}
|
||||
if _, ok := includedAttributes["ApproximateNumberOfMessagesNotVisible"]; ok {
|
||||
if shouldInclude("ApproximateNumberOfMessagesNotVisible") {
|
||||
queueAttributes = append(queueAttributes, models.Attribute{Name: "ApproximateNumberOfMessagesNotVisible", Value: strconv.Itoa(numberOfHiddenMessagesInQueue(*queue))})
|
||||
}
|
||||
if _, ok := includedAttributes["CreatedTimestamp"]; ok {
|
||||
if shouldInclude("CreatedTimestamp") {
|
||||
queueAttributes = append(queueAttributes, models.Attribute{Name: "CreatedTimestamp", Value: "0000000000"})
|
||||
}
|
||||
if _, ok := includedAttributes["LastModifiedTimestamp"]; ok {
|
||||
if shouldInclude("LastModifiedTimestamp") {
|
||||
queueAttributes = append(queueAttributes, models.Attribute{Name: "LastModifiedTimestamp", Value: "0000000000"})
|
||||
}
|
||||
if _, ok := includedAttributes["QueueArn"]; ok {
|
||||
if shouldInclude("QueueArn") {
|
||||
queueAttributes = append(queueAttributes, models.Attribute{Name: "QueueArn", Value: queue.Arn})
|
||||
}
|
||||
if _, ok := includedAttributes["RedrivePolicy"]; ok && queue.DeadLetterQueue != nil {
|
||||
if shouldInclude("RedrivePolicy") && queue.DeadLetterQueue != nil {
|
||||
queueAttributes = append(queueAttributes, models.Attribute{
|
||||
Name: "RedrivePolicy",
|
||||
Value: fmt.Sprintf(`{"maxReceiveCount":"%d", "deadLetterTargetArn":"%s"}`, queue.MaxReceiveCount, queue.DeadLetterQueue.Arn),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Изменено: 2026-04-09
|
||||
// Изменено: 2026-04-11 — фикс: SentTimestamp из m.SentTime, MD5 из кэша
|
||||
// ReceiveMessageV1 — получает сообщения из очереди тенанта с поддержкой long polling.
|
||||
// Ловушка #4: long polling держит соединение до 20 сек — не прерываем принудительно.
|
||||
package gosqs
|
||||
@@ -167,14 +167,14 @@ func buildResultMessage(m *models.SqsMessage) *models.ResultMessage {
|
||||
MessageId: m.Uuid,
|
||||
Body: m.MessageBody,
|
||||
ReceiptHandle: m.ReceiptHandle,
|
||||
MD5OfBody: utils.GetMD5Hash(m.MessageBody),
|
||||
MD5OfBody: m.MD5OfMessageBody, // Используем кэшированный MD5 вместо пересчёта
|
||||
MD5OfMessageAttributes: m.MD5OfMessageAttributes,
|
||||
MessageAttributes: m.MessageAttributes,
|
||||
Attributes: map[string]string{
|
||||
"ApproximateFirstReceiveTimestamp": fmt.Sprintf("%d", m.ReceiptTime.UnixNano()/int64(time.Millisecond)),
|
||||
"SenderId": models.CurrentEnvironment.AccountID,
|
||||
"ApproximateReceiveCount": fmt.Sprintf("%d", m.NumberOfReceives+1),
|
||||
"SentTimestamp": fmt.Sprintf("%d", time.Now().UTC().UnixNano()/int64(time.Millisecond)),
|
||||
"SentTimestamp": fmt.Sprintf("%d", m.SentTime.UnixNano()/int64(time.Millisecond)), // Фикс: реальное время отправки
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Изменено: 2026-04-10 — добавлена Redis persistence
|
||||
// Изменено: 2026-04-11 — убрано логирование тела сообщения (perf + security)
|
||||
// SendMessageV1 — добавляет сообщение в очередь тенанта.
|
||||
// Ловушка #6: queueName извлекается как ПОСЛЕДНИЙ сегмент URL — при URL вида
|
||||
// http://host/tenantID/queueName последний сегмент = queueName (правильно).
|
||||
@@ -120,7 +120,8 @@ func SendMessageV1(req *http.Request) (int, interfaces.AbstractResponseBody) {
|
||||
// Сохраняем очередь в Redis пока держим Lock
|
||||
persistence.SaveQueue(key, models.SyncQueues.Queues[key])
|
||||
models.SyncQueues.Unlock()
|
||||
log.Infof("%s: Queue: %s, Message: %s\n", time.Now().Format("2006-01-02 15:04:05"), queueName, msg.MessageBody)
|
||||
// Логируем только метаданные — тело сообщения не логируется (perf + security)
|
||||
log.Infof("Queue: %s, MessageId: %s, Size: %d bytes", queueName, msg.Uuid, len(messageBody))
|
||||
|
||||
respStruct := models.SendMessageResponse{
|
||||
Xmlns: models.BaseXmlns,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Изменено: 2026-04-09
|
||||
// Изменено: 2026-04-11 — убрано логирование тела сообщения (perf + security)
|
||||
// SendMessageBatchV1 — пакетная отправка сообщений в очередь тенанта.
|
||||
package gosqs
|
||||
|
||||
@@ -136,7 +136,8 @@ func SendMessageBatchV1(req *http.Request) (int, interfaces.AbstractResponseBody
|
||||
MD5OfMessageAttributes: msg.MD5OfMessageAttributes,
|
||||
SequenceNumber: fifoSeqNumber,
|
||||
})
|
||||
log.Infof("%s: Queue: %s, Message: %s", time.Now().Format("2006-01-02 15:04:05"), queueName, msg.MessageBody)
|
||||
// Логируем только метаданные — тело сообщения не логируется (perf + security)
|
||||
log.Debugf("Queue: %s, MessageId: %s, Size: %d bytes", queueName, msg.Uuid, len(sendEntry.MessageBody))
|
||||
}
|
||||
// Персистим батч-изменение одним снапшотом под lock.
|
||||
persistence.SaveQueue(key, queue)
|
||||
|
||||
Reference in New Issue
Block a user