fix(sqs): roll back failed queue saves and detach stored snapshots (#7008)

* fix(sqs): roll back failed queue saves and detach stored snapshots

Persist candidate lists before publication and restore failed receive or visibility mutations. Share deep Message.copy snapshots with copyForRedrive and extend the existing GuardedMessageQueueTest fixture. Extracted from PR #6533 as requested; independent of WAL write policy.

* perf(sqs): avoid detached message copies for memory backends

Reuse existing memory backend detection for shallow list snapshots. Retain deep loaded and saved snapshots for persistent, hybrid, WAL and unknown backends. Preserve candidate publication and rollback semantics; add zero-copy and backend-specific regression coverage in GuardedMessageQueueTest.
This commit is contained in:
Daniel Adler authored and GitHub committed 2026-10-30 11:19:06 -04:00
1 parent 045c65ec49
commit 29e44332f2
4 files changed
+758 -86

No files matched your search

@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.sqs;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.services.sqs.model.Message;
@@ -26,6 +27,7 @@ class GuardedMessageQueue {
private final StorageBackend<String, List<Message>> messageStore;
private final String storageKey;
private final String receiptHandleSecret;
private final boolean detachedSnapshots;
private final SqsQueueActivity activity = new SqsQueueActivity();
private volatile boolean closed;
@@ -50,7 +52,10 @@ class GuardedMessageQueue {
GuardedMessageQueue(List<Message> initial, StorageBackend<String, List<Message>> messageStore, String storageKey,
String receiptHandleSecret) {
this.messages = new ArrayList<>(initial);
this.detachedSnapshots = messageStore != null
&& !(messageStore instanceof InMemoryStorage<?, ?>
|| messageStore instanceof AccountAwareStorageBackend<?> aware && aware.isInMemory());
this.messages = snapshot(initial);
this.messageStore = messageStore;
this.storageKey = storageKey;
this.receiptHandleSecret = receiptHandleSecret;
@@ -61,29 +66,17 @@ class GuardedMessageQueue {
void addMessage(Message message) {
try (Guard _ = hold()) {
int mark = messages.size();
messages.add(message);
try {
persist();
} catch (RuntimeException e) {
messages.remove(mark);
throw e;
}
List<Message> candidate = new ArrayList<>(messages);
candidate.add(message);
commit(candidate);
}
}
/** 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 (Guard _ = hold()) {
int mark = messages.size();
messages.addAll(toAdd);
try {
persist();
} catch (RuntimeException e) {
messages.subList(mark, messages.size()).clear();
throw e;
}
List<Message> candidate = new ArrayList<>(messages);
candidate.addAll(toAdd);
commit(candidate);
}
}
@@ -94,25 +87,45 @@ class GuardedMessageQueue {
List<Message> claimed = new ArrayList<>();
List<Message> dlqCandidates = new ArrayList<>();
if (fifo) {
claimFifo(maxMessages, effectiveTimeout, maxReceiveCount, deadLetterTargetArn,
claimed, dlqCandidates);
} else {
claimStandard(maxMessages, effectiveTimeout, maxReceiveCount, deadLetterTargetArn,
claimed, dlqCandidates);
List<DeliveryState> previous = new ArrayList<>();
try {
if (fifo) {
claimFifo(maxMessages, effectiveTimeout, maxReceiveCount, deadLetterTargetArn,
claimed, dlqCandidates, previous);
} else {
claimStandard(maxMessages, effectiveTimeout, maxReceiveCount, deadLetterTargetArn,
claimed, dlqCandidates, previous);
}
if (!claimed.isEmpty() || !dlqCandidates.isEmpty()) {
persist(messages);
}
} catch (RuntimeException exception) {
previous.forEach(DeliveryState::restore);
throw exception;
}
if (!claimed.isEmpty() || !dlqCandidates.isEmpty()) {
persist();
}
return new ClaimResult(claimed, dlqCandidates);
}
}
private record DeliveryState(Message message, int receiveCount, Instant firstReceiveTimestamp,
String receiptHandle, Instant visibleAt) {
DeliveryState(Message message) {
this(message, message.getReceiveCount(), message.getFirstReceiveTimestamp(),
message.getReceiptHandle(), message.getVisibleAt());
}
void restore() {
message.setReceiveCount(receiveCount);
message.setFirstReceiveTimestamp(firstReceiveTimestamp);
message.setReceiptHandle(receiptHandle);
message.setVisibleAt(visibleAt);
}
}
private boolean tryClaim(Message msg, int effectiveTimeout, int maxReceiveCount,
String deadLetterTargetArn, List<Message> claimed,
List<Message> dlqCandidates) {
List<Message> dlqCandidates, List<DeliveryState> previous) {
previous.add(new DeliveryState(msg));
msg.setReceiveCount(msg.getReceiveCount() + 1);
if (msg.getFirstReceiveTimestamp() == null) {
msg.setFirstReceiveTimestamp(Instant.now());
@@ -132,17 +145,17 @@ class GuardedMessageQueue {
private void claimStandard(int maxMessages, int effectiveTimeout,
int maxReceiveCount, String deadLetterTargetArn,
List<Message> claimed, List<Message> dlqCandidates) {
List<Message> claimed, List<Message> dlqCandidates, List<DeliveryState> previous) {
for (Message msg : messages) {
if (claimed.size() >= maxMessages) break;
if (!msg.isVisible()) continue;
tryClaim(msg, effectiveTimeout, maxReceiveCount, deadLetterTargetArn, claimed, dlqCandidates);
tryClaim(msg, effectiveTimeout, maxReceiveCount, deadLetterTargetArn, claimed, dlqCandidates, previous);
}
}
private void claimFifo(int maxMessages, int effectiveTimeout,
int maxReceiveCount, String deadLetterTargetArn,
List<Message> claimed, List<Message> dlqCandidates) {
List<Message> claimed, List<Message> dlqCandidates, List<DeliveryState> previous) {
// Cross-call group locking: a group that already has an in-flight
// message from a previous ReceiveMessage call is blocked until that
// message is deleted or its visibility expires. Within a single call
@@ -163,7 +176,7 @@ class GuardedMessageQueue {
String groupId = msg.getMessageGroupId();
if (groupId != null && groupsWithInFlight.contains(groupId)) continue;
tryClaim(msg, effectiveTimeout, maxReceiveCount, deadLetterTargetArn, claimed, dlqCandidates);
tryClaim(msg, effectiveTimeout, maxReceiveCount, deadLetterTargetArn, claimed, dlqCandidates, previous);
}
}
@@ -179,8 +192,9 @@ class GuardedMessageQueue {
if (result != HandleResult.APPLIED) {
return new Removal(result, null);
}
messages.remove(msg);
persist();
List<Message> candidate = new ArrayList<>(messages);
candidate.remove(msg);
commit(candidate);
return new Removal(HandleResult.APPLIED, msg);
}
}
@@ -190,8 +204,14 @@ class GuardedMessageQueue {
Message msg = findByMessageId(handle.messageId());
HandleResult result = checkHandle(msg, handle, fifo);
if (result == HandleResult.APPLIED) {
Instant previous = msg.getVisibleAt();
msg.setVisibleAt(Instant.now().plusSeconds(visibilityTimeout));
persist();
try {
persist(messages);
} catch (RuntimeException exception) {
msg.setVisibleAt(previous);
throw exception;
}
}
return result;
}
@@ -222,31 +242,31 @@ class GuardedMessageQueue {
void removeMessages(List<Message> toRemove) {
try (Guard _ = hold()) {
messages.removeAll(toRemove);
persist();
List<Message> candidate = new ArrayList<>(messages);
candidate.removeAll(toRemove);
commit(candidate);
}
}
void removeExpired(Instant cutoff) {
try (Guard _ = hold()) {
if (messages.removeIf(msg -> msg.isExpired(cutoff))) {
persist();
List<Message> candidate = new ArrayList<>(messages);
if (candidate.removeIf(msg -> msg.isExpired(cutoff))) {
commit(candidate);
}
}
}
void purge() {
try (Guard _ = hold()) {
messages.clear();
persist();
commit(List.of());
}
}
List<Message> drainAll() {
try (Guard _ = hold()) {
List<Message> drained = new ArrayList<>(messages);
messages.clear();
persist();
commit(List.of());
return drained;
}
}
@@ -260,8 +280,9 @@ class GuardedMessageQueue {
if (messages.isEmpty() || !eligible.test(messages.getFirst())) {
return null;
}
Message head = messages.removeFirst();
persist();
List<Message> candidate = new ArrayList<>(messages);
Message head = candidate.removeFirst();
commit(candidate);
return head;
}
}
@@ -269,8 +290,9 @@ class GuardedMessageQueue {
/** Put a message that could not be delivered back at the head, preserving queue order. */
void restoreFirst(Message message) {
try (Guard _ = hold()) {
messages.addFirst(message);
persist();
List<Message> candidate = new ArrayList<>(messages);
candidate.addFirst(message);
commit(candidate);
}
}
@@ -369,18 +391,32 @@ class GuardedMessageQueue {
closed = true;
}
private void persist() {
private void commit(List<Message> candidate) {
persist(candidate);
messages.clear();
messages.addAll(candidate);
}
private List<Message> snapshot(List<Message> source) {
if (!detachedSnapshots) {
return new ArrayList<>(source);
}
return source.stream().map(Message::copy).collect(Collectors.toCollection(ArrayList::new));
}
private void persist(List<Message> candidate) {
if (closed || messageStore == null || storageKey == null) {
return;
}
List<Message> snapshot = snapshot(candidate);
if (messageStore instanceof AccountAwareStorageBackend<List<Message>> aware) {
String accountId = extractAccountFromStorageKey(storageKey);
if (accountId != null) {
aware.putForAccount(accountId, storageKey, new ArrayList<>(messages));
aware.putForAccount(accountId, storageKey, snapshot);
return;
}
}
messageStore.put(storageKey, new ArrayList<>(messages));
messageStore.put(storageKey, snapshot);
}
/**
@@ -69,16 +69,30 @@ public class Message {
this.md5OfBody = computeMd5(body);
}
/** A copy for delivery to another queue by StartMessageMoveTask. The content carries over. AWS
* gives it a new message id, and per-receive state (receive count, first-receive timestamp,
* receipt handle, visibility) starts over. The source instance is untouched so a failed
* delivery can put it back as it was. */
public Message copyForRedrive() {
/** A detached snapshot that retains this message's identity and delivery state. */
public Message copy() {
Message copy = new Message();
copy.messageId = UUID.randomUUID().toString();
copy.messageId = messageId;
copy.body = body;
copy.messageAttributes = messageAttributes == null ? new HashMap<>() : new HashMap<>(messageAttributes);
if (messageAttributes == null) {
copy.messageAttributes = null;
} else {
messageAttributes.forEach((name, attribute) -> {
if (attribute == null) {
copy.messageAttributes.put(name, null);
return;
}
MessageAttributeValue value = new MessageAttributeValue();
value.setStringValue(attribute.getStringValue());
value.setDataType(attribute.getDataType());
byte[] binary = attribute.getBinaryValue();
value.setBinaryValue(binary == null ? null : binary.clone());
copy.messageAttributes.put(name, value);
});
}
copy.sentTimestamp = sentTimestamp;
copy.firstReceiveTimestamp = firstReceiveTimestamp;
copy.receiveCount = receiveCount;
copy.md5OfBody = md5OfBody;
copy.md5OfMessageAttributes = md5OfMessageAttributes;
copy.messageGroupId = messageGroupId;
@@ -86,9 +100,28 @@ public class Message {
copy.sequenceNumber = sequenceNumber;
copy.originalSourceQueueUrl = originalSourceQueueUrl;
copy.awsTraceHeader = awsTraceHeader;
copy.senderId = this.senderId;
copy.senderId = senderId;
copy.retentionStartTimestamp = retentionStartTimestamp;
copy.receiptHandle = receiptHandle;
copy.visibleAt = visibleAt;
return copy;
}
/** A copy for delivery to another queue by StartMessageMoveTask. The content carries over. AWS
* gives it a new message id, and per-receive state (receive count, first-receive timestamp,
* receipt handle, visibility) starts over. The source instance is untouched so a failed
* delivery can put it back as it was. */
public Message copyForRedrive() {
Message copy = copy();
copy.messageId = UUID.randomUUID().toString();
if (copy.messageAttributes == null) {
copy.messageAttributes = new HashMap<>();
}
copy.receiveCount = 0;
copy.firstReceiveTimestamp = null;
copy.receiptHandle = null;
copy.visibleAt = null;
copy.retentionStartTimestamp = Instant.now();
// receiveCount 0, firstReceiveTimestamp / receiptHandle / visibleAt null: a fresh life.
return copy;
}