refactor(sqs): move library usages to imports (#3896)

* refactor(sqs): move library usages to imports

* refactor(sqs): replace inline FQCNs and var declarations across sqs package

* refactor(sqs): eliminate test var usages and revert attribute order in json handler
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-09-19 15:07:19 -04:00
1 parent 3f9ebd5cfa
commit 709214557c
9 files changed
+207 -161

No files matched your search

@@ -5,7 +5,12 @@ import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.services.sqs.model.Message;
import java.time.Instant;
import java.util.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@@ -48,7 +53,7 @@ class GuardedMessageQueue {
}
void addMessage(Message message) {
try (var _ = hold()) {
try (Guard _ = hold()) {
messages.add(message);
persist();
}
@@ -57,7 +62,7 @@ class GuardedMessageQueue {
/** If persisting fails the in-memory add is rolled back and the exception propagates, so a
* caller that compensates on the source side does not leave a duplicate here. */
void addAll(List<Message> toAdd) {
try (var _ = hold()) {
try (Guard _ = hold()) {
int mark = messages.size();
messages.addAll(toAdd);
try {
@@ -72,7 +77,7 @@ class GuardedMessageQueue {
ClaimResult claimVisibleMessages(int maxMessages, int effectiveTimeout,
boolean fifo, int maxReceiveCount,
String deadLetterTargetArn) {
try (var _ = hold()) {
try (Guard _ = hold()) {
List<Message> claimed = new ArrayList<>();
List<Message> dlqCandidates = new ArrayList<>();
@@ -150,7 +155,7 @@ class GuardedMessageQueue {
}
Optional<Message> removeByReceiptHandle(String receiptHandle) {
try (var _ = hold()) {
try (Guard _ = hold()) {
Message removed = null;
for (Iterator<Message> it = messages.iterator(); it.hasNext(); ) {
Message m = it.next();
@@ -168,7 +173,7 @@ class GuardedMessageQueue {
}
boolean changeVisibility(String receiptHandle, int visibilityTimeout) {
try (var _ = hold()) {
try (Guard _ = hold()) {
for (Message msg : messages) {
if (receiptHandle.equals(msg.getReceiptHandle())) {
msg.setVisibleAt(Instant.now().plusSeconds(visibilityTimeout));
@@ -181,21 +186,21 @@ class GuardedMessageQueue {
}
void removeMessages(List<Message> toRemove) {
try (var _ = hold()) {
try (Guard _ = hold()) {
messages.removeAll(toRemove);
persist();
}
}
void purge() {
try (var _ = hold()) {
try (Guard _ = hold()) {
messages.clear();
persist();
}
}
List<Message> drainAll() {
try (var _ = hold()) {
try (Guard _ = hold()) {
List<Message> drained = new ArrayList<>(messages);
messages.clear();
persist();
@@ -208,7 +213,7 @@ class GuardedMessageQueue {
* hold so nothing can slip in between. Used by the message-move-task worker so the source
* queue stays observably populated for the duration of a rate-limited move. */
Message drainFirstIf(Predicate<Message> eligible) {
try (var _ = hold()) {
try (Guard _ = hold()) {
if (messages.isEmpty() || !eligible.test(messages.getFirst())) {
return null;
}
@@ -220,7 +225,7 @@ class GuardedMessageQueue {
/** Put a message that could not be delivered back at the head, preserving queue order. */
void restoreFirst(Message message) {
try (var _ = hold()) {
try (Guard _ = hold()) {
messages.addFirst(message);
persist();
}
@@ -238,7 +243,7 @@ class GuardedMessageQueue {
* DelaySeconds, so it counts as delayed rather than in flight.
*/
MessageCounts messageCounts() {
try (var _ = hold()) {
try (Guard _ = hold()) {
long visible = 0;
long inFlight = 0;
long delayed = 0;
@@ -256,13 +261,13 @@ class GuardedMessageQueue {
}
List<Message> peekAll() {
try (var _ = hold()) {
try (Guard _ = hold()) {
return new ArrayList<>(messages);
}
}
boolean isEmpty() {
try (var _ = hold()) {
try (Guard _ = hold()) {
return messages.isEmpty();
}
}
@@ -272,7 +277,7 @@ class GuardedMessageQueue {
}
Message findByDeduplicationId(String dedupId, String messageGroupId) {
try (var _ = hold()) {
try (Guard _ = hold()) {
return messages.stream()
.filter(msg -> dedupId.equals(msg.getMessageDeduplicationId()))
.filter(msg -> messageGroupId == null
@@ -1,14 +1,14 @@
package io.github.hectorvent.floci.services.sqs;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.sqs.model.Message;
import io.github.hectorvent.floci.services.sqs.model.MessageAttributeValue;
import io.github.hectorvent.floci.services.sqs.model.Queue;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
@@ -16,8 +16,10 @@ import jakarta.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* SQS JSON protocol handler (application/x-amz-json-1.0).
@@ -83,7 +85,7 @@ public class SqsJsonHandler {
}
private void writeSystemAttributesJson(ObjectNode msgNode, Message msg,
java.util.Set<String> requested, String senderId) {
Set<String> requested, String senderId) {
if (requested.isEmpty()) {
return;
}
@@ -136,7 +138,6 @@ public class SqsJsonHandler {
Map<String, String> attributes = jsonNodeToMap(request.path("Attributes"));
Map<String, String> tags = jsonNodeToMap(request.path("tags"));
Queue queue = sqsService.createQueue(queueName, attributes, tags, region);
ObjectNode response = objectMapper.createObjectNode();
response.put("QueueUrl", queue.getQueueUrl());
return Response.ok(response).build();
@@ -151,11 +152,10 @@ public class SqsJsonHandler {
private Response handleListQueues(JsonNode request, String region) {
String prefix = request.path("QueueNamePrefix").asText(null);
List<Queue> queues = sqsService.listQueues(prefix, region);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode urls = response.putArray("QueueUrls");
ArrayNode queueUrls = response.putArray("QueueUrls");
for (Queue q : queues) {
urls.add(q.getQueueUrl());
queueUrls.add(q.getQueueUrl());
}
return Response.ok(response).build();
}
@@ -163,7 +163,6 @@ public class SqsJsonHandler {
private Response handleGetQueueUrl(JsonNode request, String region) {
String queueName = request.path("QueueName").asText(null);
String queueUrl = sqsService.getQueueUrl(queueName, region);
ObjectNode response = objectMapper.createObjectNode();
response.put("QueueUrl", queueUrl);
return Response.ok(response).build();
@@ -174,8 +173,8 @@ public class SqsJsonHandler {
List<String> attributeNames = new ArrayList<>();
JsonNode namesNode = request.path("AttributeNames");
if (namesNode.isArray()) {
for (JsonNode n : namesNode) {
attributeNames.add(n.asText());
for (JsonNode name : namesNode) {
attributeNames.add(name.asText());
}
}
if (attributeNames.isEmpty()) {
@@ -186,7 +185,7 @@ public class SqsJsonHandler {
ObjectNode response = objectMapper.createObjectNode();
ObjectNode attrsNode = response.putObject("Attributes");
for (var entry : attributes.entrySet()) {
for (Map.Entry<String, String> entry : attributes.entrySet()) {
attrsNode.put(entry.getKey(), entry.getValue());
}
return Response.ok(response).build();
@@ -257,7 +256,7 @@ public class SqsJsonHandler {
int visibilityTimeout = request.path("VisibilityTimeout").asInt(-1);
Integer waitTimeSeconds = getOptionalIntField(request, "WaitTimeSeconds");
java.util.Set<String> requestedAttrs = new java.util.LinkedHashSet<>();
Set<String> requestedAttrs = new LinkedHashSet<>();
requestedAttrs.addAll(jsonNodeToList(request.path("AttributeNames")));
requestedAttrs.addAll(jsonNodeToList(request.path("MessageSystemAttributeNames")));
@@ -287,7 +286,7 @@ public class SqsJsonHandler {
if (msg.getMessageAttributes() != null && !msg.getMessageAttributes().isEmpty()) {
ObjectNode msgAttrs = msgNode.putObject("MessageAttributes");
for (var entry : msg.getMessageAttributes().entrySet()) {
for (Map.Entry<String, MessageAttributeValue> entry : msg.getMessageAttributes().entrySet()) {
ObjectNode valNode = msgAttrs.putObject(entry.getKey());
valNode.put("DataType", entry.getValue().getDataType());
if (entry.getValue().getBinaryValue() != null) {
@@ -522,7 +521,7 @@ public class SqsJsonHandler {
ArrayNode successful = objectMapper.createArrayNode();
ArrayNode failed = objectMapper.createArrayNode();
for (var result : results) {
for (SqsService.BatchResultEntry result : results) {
if (result.success()) {
ObjectNode success = objectMapper.createObjectNode();
success.put("Id", result.id());
@@ -571,7 +570,7 @@ public class SqsJsonHandler {
ObjectNode response = objectMapper.createObjectNode();
ObjectNode tagsNode = response.putObject("Tags");
for (var entry : tags.entrySet()) {
for (Map.Entry<String, String> entry : tags.entrySet()) {
tagsNode.put(entry.getKey(), entry.getValue());
}
return Response.ok(response).build();
@@ -1,9 +1,13 @@
package io.github.hectorvent.floci.services.sqs;
import io.github.hectorvent.floci.core.common.*;
import io.github.hectorvent.floci.core.common.AwsErrorMessages;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsNamespaces;
import io.github.hectorvent.floci.core.common.AwsQueryResponse;
import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.services.sqs.model.Message;
import io.github.hectorvent.floci.services.sqs.model.Queue;
import io.github.hectorvent.floci.services.sqs.model.MessageAttributeValue;
import io.github.hectorvent.floci.services.sqs.model.Queue;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.MultivaluedMap;
@@ -13,8 +17,10 @@ import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Query-protocol handler for SQS actions.
@@ -95,7 +101,7 @@ public class SqsQueryHandler {
}
private static void writeSystemAttributesXml(XmlBuilder xml, Message msg,
java.util.Set<String> requested, String senderId) {
Set<String> requested, String senderId) {
if (requested.isEmpty()) {
return;
}
@@ -168,7 +174,7 @@ public class SqsQueryHandler {
String prefix = getParam(params, "QueueNamePrefix");
List<Queue> queues = sqsService.listQueues(prefix, region);
var xml = new XmlBuilder();
XmlBuilder xml = new XmlBuilder();
for (Queue q : queues) {
xml.elem("QueueUrl", q.getQueueUrl());
}
@@ -197,8 +203,8 @@ public class SqsQueryHandler {
Map<String, String> attributes = sqsService.getQueueAttributes(queueUrl, attributeNames, region);
var xml = new XmlBuilder();
for (var entry : attributes.entrySet()) {
XmlBuilder xml = new XmlBuilder();
for (Map.Entry<String, String> entry : attributes.entrySet()) {
xml.start("Attribute")
.elem("Name", entry.getKey())
.elem("Value", entry.getValue())
@@ -246,7 +252,7 @@ public class SqsQueryHandler {
Message msg = sqsService.sendMessage(queueUrl, body, delaySeconds, messageGroupId,
messageDeduplicationId, messageAttributes, awsTraceHeader, region);
var xml = new XmlBuilder()
XmlBuilder xml = new XmlBuilder()
.elem("MessageId", msg.getMessageId())
.elem("MD5OfMessageBody", msg.getMd5OfBody());
if (msg.getMd5OfMessageAttributes() != null) {
@@ -264,14 +270,14 @@ public class SqsQueryHandler {
int visibilityTimeout = getIntParam(params, "VisibilityTimeout", -1);
Integer waitTimeSeconds = getOptionalIntParam(params, "WaitTimeSeconds");
java.util.Set<String> requestedAttrs = new java.util.LinkedHashSet<>();
Set<String> requestedAttrs = new LinkedHashSet<>();
requestedAttrs.addAll(collectIndexed(params, "AttributeName."));
requestedAttrs.addAll(collectIndexed(params, "MessageSystemAttributeName."));
List<Message> messages = sqsService.receiveMessage(queueUrl, maxMessages, visibilityTimeout, waitTimeSeconds, region);
String senderId = sqsService.senderIdFor(queueUrl);
var xml = new XmlBuilder();
XmlBuilder xml = new XmlBuilder();
for (Message msg : messages) {
xml.start("Message")
.elem("MessageId", msg.getMessageId())
@@ -283,7 +289,7 @@ public class SqsQueryHandler {
xml.elem("Body", msg.getBody());
writeSystemAttributesXml(xml, msg, requestedAttrs, senderId);
if (msg.getMessageAttributes() != null && !msg.getMessageAttributes().isEmpty()) {
for (var entry : msg.getMessageAttributes().entrySet()) {
for (Map.Entry<String, MessageAttributeValue> entry : msg.getMessageAttributes().entrySet()) {
xml.start("MessageAttribute")
.elem("Name", entry.getKey())
.start("Value")
@@ -319,7 +325,7 @@ public class SqsQueryHandler {
private Response handleDeleteMessageBatch(MultivaluedMap<String, String> params, String region) {
String queueUrl = getParam(params, "QueueUrl");
var xml = new XmlBuilder();
XmlBuilder xml = new XmlBuilder();
for (int i = 1; ; i++) {
String id = getParam(params, "DeleteMessageBatchRequestEntry." + i + ".Id");
@@ -343,7 +349,7 @@ public class SqsQueryHandler {
private Response handleSendMessageBatch(MultivaluedMap<String, String> params, String region) {
String queueUrl = getParam(params, "QueueUrl");
var xml = new XmlBuilder();
XmlBuilder xml = new XmlBuilder();
record ParsedEntry(String id, String body, Integer delay, String groupId, String dedupId,
Map<String, MessageAttributeValue> attributes, String awsTraceHeader) {}
@@ -396,7 +402,7 @@ public class SqsQueryHandler {
for (ParsedEntry parsed : parsedEntries) {
String id = parsed.id();
try {
var msg = sqsService.sendMessage(queueUrl, parsed.body(), parsed.delay(),
Message msg = sqsService.sendMessage(queueUrl, parsed.body(), parsed.delay(),
parsed.groupId(), parsed.dedupId(), parsed.attributes(),
parsed.awsTraceHeader(), region);
xml.start("SendMessageBatchResultEntry")
@@ -426,7 +432,7 @@ public class SqsQueryHandler {
private Response handleListDeadLetterSourceQueues(MultivaluedMap<String, String> params, String region) {
String queueUrl = getParam(params, "QueueUrl");
List<String> queues = sqsService.listDeadLetterSourceQueues(queueUrl, region);
var xml = new XmlBuilder();
XmlBuilder xml = new XmlBuilder();
for (String q : queues) {
xml.elem("QueueUrl", q);
}
@@ -438,7 +444,7 @@ public class SqsQueryHandler {
String destinationArn = getParam(params, "DestinationArn");
int maxRate = getIntParam(params, "MaxNumberOfMessagesPerSecond", 0);
String taskHandle = sqsService.startMessageMoveTask(sourceArn, destinationArn, maxRate, region);
var xml = new XmlBuilder().elem("TaskHandle", taskHandle);
XmlBuilder xml = new XmlBuilder().elem("TaskHandle", taskHandle);
return Response.ok(AwsQueryResponse.envelope("StartMessageMoveTask", null, xml.build())).build();
}
@@ -446,7 +452,7 @@ public class SqsQueryHandler {
String sourceArn = getParam(params, "SourceArn");
int maxResults = getIntParam(params, "MaxResults", 10);
List<SqsService.MoveTask> tasks = sqsService.listMessageMoveTasks(sourceArn, region);
var xml = new XmlBuilder();
XmlBuilder xml = new XmlBuilder();
int count = 0;
for (SqsService.MoveTask t : tasks) {
if (count++ >= maxResults) break;
@@ -472,7 +478,7 @@ public class SqsQueryHandler {
private Response handleCancelMessageMoveTask(MultivaluedMap<String, String> params, String region) {
String taskHandle = getParam(params, "TaskHandle");
long moved = sqsService.cancelMessageMoveTask(taskHandle, region);
var xml = new XmlBuilder().elem("ApproximateNumberOfMessagesMoved", moved);
XmlBuilder xml = new XmlBuilder().elem("ApproximateNumberOfMessagesMoved", moved);
return Response.ok(AwsQueryResponse.envelope("CancelMessageMoveTask", null, xml.build())).build();
}
@@ -491,7 +497,7 @@ public class SqsQueryHandler {
private Response handleChangeMessageVisibilityBatch(MultivaluedMap<String, String> params, String region) {
String queueUrl = getParam(params, "QueueUrl");
var entries = new ArrayList<SqsService.ChangeVisibilityBatchEntry>();
List<SqsService.ChangeVisibilityBatchEntry> entries = new ArrayList<>();
for (int i = 1; ; i++) {
String id = getParam(params, "ChangeMessageVisibilityBatchRequestEntry." + i + ".Id");
if (id == null) break;
@@ -500,9 +506,9 @@ public class SqsQueryHandler {
entries.add(new SqsService.ChangeVisibilityBatchEntry(id, receiptHandle, visibilityTimeout));
}
var results = sqsService.changeMessageVisibilityBatch(queueUrl, entries, region);
var xml = new XmlBuilder();
for (var result : results) {
List<SqsService.BatchResultEntry> results = sqsService.changeMessageVisibilityBatch(queueUrl, entries, region);
XmlBuilder xml = new XmlBuilder();
for (SqsService.BatchResultEntry result : results) {
if (result.success()) {
xml.start("ChangeMessageVisibilityBatchResultEntry")
.elem("Id", result.id())
@@ -548,8 +554,8 @@ public class SqsQueryHandler {
String queueUrl = getParam(params, "QueueUrl");
Map<String, String> tags = sqsService.listQueueTags(queueUrl, region);
var xml = new XmlBuilder();
for (var entry : tags.entrySet()) {
XmlBuilder xml = new XmlBuilder();
for (Map.Entry<String, String> entry : tags.entrySet()) {
xml.start("Tag")
.elem("Key", entry.getKey())
.elem("Value", entry.getValue())
@@ -1,5 +1,10 @@
package io.github.hectorvent.floci.services.sqs;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
@@ -13,26 +18,39 @@ import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.sns.SnsService;
import io.github.hectorvent.floci.services.sqs.model.Message;
import io.github.hectorvent.floci.services.sqs.model.Queue;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.services.sqs.model.MessageAttributeValue;
import io.github.hectorvent.floci.services.sqs.model.Queue;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
@ApplicationScoped
public class SqsService implements Resettable, ResourceProvider {
@@ -62,8 +80,8 @@ public class SqsService implements Resettable, ResourceProvider {
new ConcurrentHashMap<>();
/** Move tasks execute on a background thread so MaxNumberOfMessagesPerSecond can throttle
* and CancelMessageMoveTask has something to interrupt. One thread per task is sufficient. */
private final java.util.concurrent.ExecutorService moveTaskExecutor =
java.util.concurrent.Executors.newCachedThreadPool(r -> {
private final ExecutorService moveTaskExecutor =
Executors.newCachedThreadPool(r -> {
Thread t = new Thread(r, "sqs-move-task");
t.setDaemon(true);
return t;
@@ -156,7 +174,7 @@ public class SqsService implements Resettable, ResourceProvider {
Set<String> sourceArns = entries.values().stream()
.filter(Entry::terminal)
.map(entry -> entry.task().sourceArn())
.collect(java.util.stream.Collectors.toSet());
.collect(Collectors.toSet());
for (String sourceArn : sourceArns) {
List<Map.Entry<String, Entry>> terminalEntries = entries.entrySet().stream()
.filter(entry -> entry.getValue().terminal()
@@ -390,7 +408,7 @@ public class SqsService implements Resettable, ResourceProvider {
if (dedupStore == null) {
return;
}
var dedupMap = deduplicationCache.get(storageKey);
ConcurrentHashMap<String, Instant> dedupMap = deduplicationCache.get(storageKey);
if (dedupMap != null && !dedupMap.isEmpty()) {
Map<String, Long> serializable = new HashMap<>();
dedupMap.forEach((id, expiry) -> serializable.put(id, expiry.toEpochMilli()));
@@ -509,7 +527,7 @@ public class SqsService implements Resettable, ResourceProvider {
"The specified queue does not exist.", 400);
}
queueStore.delete(storageKey);
var removed = messagesByQueue.remove(storageKey);
GuardedMessageQueue removed = messagesByQueue.remove(storageKey);
if (removed != null) {
removed.close();
}
@@ -560,13 +578,13 @@ public class SqsService implements Resettable, ResourceProvider {
.orElseThrow(() -> new AwsException("AWS.SimpleQueueService.NonExistentQueue",
"The specified queue does not exist.", 400));
Map<String, String> attrs = new java.util.LinkedHashMap<>(queue.getAttributes());
Map<String, String> attrs = new LinkedHashMap<>(queue.getAttributes());
// Add computed attributes
attrs.put("QueueArn", regionResolver.buildArn("sqs", region, queue.getQueueName()));
attrs.put("CreatedTimestamp", String.valueOf(queue.getCreatedTimestamp().getEpochSecond()));
attrs.put("LastModifiedTimestamp", String.valueOf(queue.getLastModifiedTimestamp().getEpochSecond()));
var counts = getOrCreateQueue(storageKey).messageCounts();
GuardedMessageQueue.MessageCounts counts = getOrCreateQueue(storageKey).messageCounts();
attrs.put("ApproximateNumberOfMessages", String.valueOf(counts.visible()));
attrs.put("ApproximateNumberOfMessagesNotVisible", String.valueOf(counts.inFlight()));
attrs.put("ApproximateNumberOfMessagesDelayed", String.valueOf(counts.delayed()));
@@ -594,7 +612,7 @@ public class SqsService implements Resettable, ResourceProvider {
if (attributeNames == null || attributeNames.contains("All")) {
return attrs;
}
var filtered = new java.util.LinkedHashMap<String, String>();
Map<String, String> filtered = new LinkedHashMap<>();
for (String name : attributeNames) {
if (attrs.containsKey(name)) {
filtered.put(name, attrs.get(name));
@@ -683,7 +701,7 @@ public class SqsService implements Resettable, ResourceProvider {
// MessageGroupId/MessageDeduplicationId, so the composite key is unambiguous.
String dedupCacheKey = groupScoped ? messageGroupId + "\0" + dedupId : dedupId;
cleanupDeduplicationCache(storageKey);
var dedupMap = deduplicationCache.computeIfAbsent(storageKey, k -> new ConcurrentHashMap<>());
ConcurrentHashMap<String, Instant> dedupMap = deduplicationCache.computeIfAbsent(storageKey, k -> new ConcurrentHashMap<>());
Instant expiry = Instant.now().plusSeconds(DEDUP_WINDOW_SECONDS);
Instant previous = dedupMap.putIfAbsent(dedupCacheKey, expiry);
persistDedup(storageKey);
@@ -821,20 +839,20 @@ public class SqsService implements Resettable, ResourceProvider {
* UTF-8 body bytes + per-attribute (name UTF-8 + type UTF-8 + value bytes).
*/
public static int computeMessageSize(String body, Map<String, MessageAttributeValue> attributes) {
int total = body == null ? 0 : body.getBytes(java.nio.charset.StandardCharsets.UTF_8).length;
int total = body == null ? 0 : body.getBytes(StandardCharsets.UTF_8).length;
if (attributes == null || attributes.isEmpty()) {
return total;
}
for (Map.Entry<String, MessageAttributeValue> entry : attributes.entrySet()) {
total += entry.getKey().getBytes(java.nio.charset.StandardCharsets.UTF_8).length;
total += entry.getKey().getBytes(StandardCharsets.UTF_8).length;
MessageAttributeValue value = entry.getValue();
if (value.getDataType() != null) {
total += value.getDataType().getBytes(java.nio.charset.StandardCharsets.UTF_8).length;
total += value.getDataType().getBytes(StandardCharsets.UTF_8).length;
}
if (value.getBinaryValue() != null) {
total += value.getBinaryValue().length;
} else if (value.getStringValue() != null) {
total += value.getStringValue().getBytes(java.nio.charset.StandardCharsets.UTF_8).length;
total += value.getStringValue().getBytes(StandardCharsets.UTF_8).length;
}
}
return total;
@@ -862,7 +880,7 @@ public class SqsService implements Resettable, ResourceProvider {
}
private void cleanupDeduplicationCache(String queueUrl) {
var dedupMap = deduplicationCache.get(queueUrl);
ConcurrentHashMap<String, Instant> dedupMap = deduplicationCache.get(queueUrl);
if (dedupMap != null) {
Instant now = Instant.now();
dedupMap.entrySet().removeIf(e -> now.isAfter(e.getValue()));
@@ -871,10 +889,11 @@ public class SqsService implements Resettable, ResourceProvider {
private static String computeMd5(String input) {
try {
var md = java.security.MessageDigest.getInstance("MD5");
byte[] digest = md.digest(input.getBytes(java.nio.charset.StandardCharsets.UTF_8));
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(input.getBytes(StandardCharsets.UTF_8));
return HEX.formatHex(digest);
} catch (java.security.NoSuchAlgorithmException e) {
} catch (NoSuchAlgorithmException ignored) {
// MD5 is guaranteed to be available in the standard JDK runtime
return "";
}
}
@@ -955,7 +974,7 @@ public class SqsService implements Resettable, ResourceProvider {
return redrivePolicyCache.computeIfAbsent(storageKey, k -> {
try {
var rp = new com.fasterxml.jackson.databind.ObjectMapper().readTree(rawPolicy);
JsonNode rp = new ObjectMapper().readTree(rawPolicy);
return new RedrivePolicy(
rp.has("maxReceiveCount") ? rp.get("maxReceiveCount").asInt() : -1,
rp.has("deadLetterTargetArn") ? rp.get("deadLetterTargetArn").asText() : null
@@ -985,15 +1004,15 @@ public class SqsService implements Resettable, ResourceProvider {
int maxReceiveCount = rp != null ? rp.maxReceiveCount() : -1;
String deadLetterTargetArn = rp != null ? rp.deadLetterTargetArn() : null;
var guardedQueue = getOrCreateQueue(storageKey);
var claimResult = guardedQueue.claimVisibleMessages(
GuardedMessageQueue guardedQueue = getOrCreateQueue(storageKey);
GuardedMessageQueue.ClaimResult claimResult = guardedQueue.claimVisibleMessages(
maxMessages, effectiveTimeout, queue.isFifo(), maxReceiveCount, deadLetterTargetArn);
// Route DLQ candidates to the dead-letter queue only if the destination resolves
if (!claimResult.dlqCandidates().isEmpty() && deadLetterTargetArn != null) {
String dlqUrl = queueUrlFromArn(deadLetterTargetArn, region);
if (dlqUrl != null) {
var dlqCandidates = claimResult.dlqCandidates();
List<Message> dlqCandidates = claimResult.dlqCandidates();
guardedQueue.removeMessages(dlqCandidates);
for (Message msg : dlqCandidates) {
msg.setVisibleAt(null);
@@ -1167,8 +1186,8 @@ public class SqsService implements Resettable, ResourceProvider {
}
}
var srcQueueInitial = getOrCreateQueue(srcKey);
var srcCounts = srcQueueInitial.messageCounts();
GuardedMessageQueue srcQueueInitial = getOrCreateQueue(srcKey);
GuardedMessageQueue.MessageCounts srcCounts = srcQueueInitial.messageCounts();
long toMove = srcCounts.visible() + srcCounts.inFlight() + srcCounts.delayed();
String taskHandle = "task-" + UUID.randomUUID();
@@ -1263,7 +1282,7 @@ public class SqsService implements Resettable, ResourceProvider {
long intervalMillis = maxRate > 0 ? Math.max(1L, 1000L / maxRate) : 0L;
long moved = initialMoved;
try {
var srcQueue = getOrCreateQueue(srcKey);
GuardedMessageQueue srcQueue = getOrCreateQueue(srcKey);
while (!cancelled.isRequested()) {
if (intervalMillis > 0) {
try {
@@ -1354,7 +1373,7 @@ public class SqsService implements Resettable, ResourceProvider {
return null;
}
try {
JsonNode policy = new com.fasterxml.jackson.databind.ObjectMapper().readTree(raw);
JsonNode policy = new ObjectMapper().readTree(raw);
JsonNode dlqArn = policy.get("deadLetterTargetArn");
return dlqArn != null && !dlqArn.isNull() ? dlqArn.asText() : null;
} catch (Exception e) {
@@ -1372,7 +1391,7 @@ public class SqsService implements Resettable, ResourceProvider {
List<ChangeVisibilityBatchEntry> entries, String region) {
ensureQueueExists(regionKey(region, queueUrl));
List<BatchResultEntry> results = new ArrayList<>();
for (var entry : entries) {
for (ChangeVisibilityBatchEntry entry : entries) {
try {
changeMessageVisibility(queueUrl, entry.receiptHandle(), entry.visibilityTimeout(), region);
results.add(new BatchResultEntry(entry.id(), true, null, null));
@@ -1540,7 +1559,7 @@ public class SqsService implements Resettable, ResourceProvider {
Queue queue = queueStore.get(storageKey)
.orElseThrow(() -> new AwsException("AWS.SimpleQueueService.NonExistentQueue",
"The specified queue does not exist.", 400));
return new java.util.LinkedHashMap<>(queue.getTags());
return new LinkedHashMap<>(queue.getTags());
}
/**
@@ -4,8 +4,16 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@@ -133,20 +141,20 @@ public class Message {
return;
}
try {
var md = java.security.MessageDigest.getInstance("MD5");
java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
java.io.DataOutputStream dos = new java.io.DataOutputStream(bos);
MessageDigest md = MessageDigest.getInstance("MD5");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
java.util.List<String> keys = new java.util.ArrayList<>(messageAttributes.keySet());
java.util.Collections.sort(keys);
List<String> keys = new ArrayList<>(messageAttributes.keySet());
Collections.sort(keys);
for (String key : keys) {
MessageAttributeValue val = messageAttributes.get(key);
byte[] nameBytes = key.getBytes(java.nio.charset.StandardCharsets.UTF_8);
byte[] nameBytes = key.getBytes(StandardCharsets.UTF_8);
dos.writeInt(nameBytes.length);
dos.write(nameBytes);
byte[] typeBytes = val.getDataType().getBytes(java.nio.charset.StandardCharsets.UTF_8);
byte[] typeBytes = val.getDataType().getBytes(StandardCharsets.UTF_8);
dos.writeInt(typeBytes.length);
dos.write(typeBytes);
@@ -156,33 +164,35 @@ public class Message {
dos.write(val.getBinaryValue());
} else {
dos.write(1); // String or Number
byte[] valBytes = val.getStringValue().getBytes(java.nio.charset.StandardCharsets.UTF_8);
byte[] valBytes = val.getStringValue().getBytes(StandardCharsets.UTF_8);
dos.writeInt(valBytes.length);
dos.write(valBytes);
}
}
byte[] digest = md.digest(bos.toByteArray());
var sb = new StringBuilder();
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b));
}
this.md5OfMessageAttributes = sb.toString();
} catch (Exception e) {
} catch (Exception ignored) {
// Attribute serialization failure falls back to null MD5
this.md5OfMessageAttributes = null;
}
}
private static String computeMd5(String input) {
try {
var md = java.security.MessageDigest.getInstance("MD5");
byte[] digest = md.digest(input.getBytes(java.nio.charset.StandardCharsets.UTF_8));
var sb = new StringBuilder();
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(input.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b));
}
return sb.toString();
} catch (java.security.NoSuchAlgorithmException e) {
} catch (NoSuchAlgorithmException ignored) {
// MD5 is always available in the standard JDK runtime
return "";
}
}