mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(lambda): keep the visibility a function sets on failed SQS messages (#9003)
This commit is contained in:
1 parent
07f93dc8e5
commit
ede9601b82
6 files changed
+281
-24
No files matched your search
@@ -22,11 +22,14 @@ import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
@@ -126,9 +129,14 @@ public class SqsEventSourcePoller implements Resettable {
|
||||
/** Messages received across earlier polls that a batching window is still holding open. */
|
||||
private static final class PendingBatch {
|
||||
final List<Message> messages = new ArrayList<>();
|
||||
final Map<String, ReceivedMessage> receivedById = new HashMap<>();
|
||||
long windowStartedAtMs;
|
||||
}
|
||||
|
||||
/** The receipt handle and visibility one receive gave a message. */
|
||||
private record ReceivedMessage(String receiptHandle, Instant visibleAt) {
|
||||
}
|
||||
|
||||
public void startPolling(EventSourceMapping esm) {
|
||||
if (timerIds.containsKey(esm.getUuid())) {
|
||||
return; // already polling
|
||||
@@ -201,13 +209,16 @@ public class SqsEventSourcePoller implements Resettable {
|
||||
esm.getQueueUrl(), Math.min(10, wanted), visibilityTimeout, 0, esm.getRegion());
|
||||
|
||||
List<Message> messages;
|
||||
Map<String, ReceivedMessage> receivedById;
|
||||
if (window <= 0) {
|
||||
// No window, or one that was just turned off: deliver now, draining anything a
|
||||
// previous positive window had buffered so those messages are not stranded
|
||||
// until their visibility expires (and cannot be replayed if the window returns).
|
||||
List<Message> batch = pending != null ? pending.messages : new ArrayList<>();
|
||||
receivedById = pending != null ? pending.receivedById : new HashMap<>();
|
||||
pendingBatches.remove(esm.getUuid());
|
||||
batch.addAll(received);
|
||||
recordReceipts(received, receivedById);
|
||||
if (batch.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
@@ -221,6 +232,7 @@ public class SqsEventSourcePoller implements Resettable {
|
||||
pending.windowStartedAtMs = clockMs.getAsLong();
|
||||
}
|
||||
pending.messages.addAll(received);
|
||||
recordReceipts(received, pending.receivedById);
|
||||
if (pending.messages.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
@@ -231,6 +243,7 @@ public class SqsEventSourcePoller implements Resettable {
|
||||
return;
|
||||
}
|
||||
messages = new ArrayList<>(pending.messages);
|
||||
receivedById = new HashMap<>(pending.receivedById);
|
||||
pendingBatches.remove(esm.getUuid());
|
||||
}
|
||||
|
||||
@@ -307,12 +320,12 @@ public class SqsEventSourcePoller implements Resettable {
|
||||
if (!failedIds.isEmpty()) {
|
||||
List<Message> toReturn = matched.stream()
|
||||
.filter(m -> failedIds.contains(m.getMessageId())).toList();
|
||||
returnMessagesToQueue(esm, toReturn);
|
||||
returnMessagesToQueue(esm, toReturn, receivedById);
|
||||
}
|
||||
} else {
|
||||
LOG.warnv("ESM {0}: Lambda returned error [{1}], returning {2} delivered message(s) to queue for retry/redrive",
|
||||
esm.getUuid(), result.getFunctionError(), matched.size());
|
||||
returnMessagesToQueue(esm, matched);
|
||||
returnMessagesToQueue(esm, matched, receivedById);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("ESM {0}: poll/invoke error: {1} ({2})",
|
||||
@@ -334,13 +347,30 @@ public class SqsEventSourcePoller implements Resettable {
|
||||
* 0 would cause for a persistently failing function) — so ApproximateReceiveCount
|
||||
* climbs and the queue's RedrivePolicy moves them to the DLQ once
|
||||
* {@code maxReceiveCount} is exceeded.
|
||||
*
|
||||
* <p>A message whose visibility changed during the invocation keeps it, as on AWS, where the
|
||||
* mapping leaves a failed message's visibility alone: the function may have called
|
||||
* ChangeMessageVisibility, or another consumer may have received the message since. The reset
|
||||
* uses the handle and visibility this mapping's receive recorded, never the live message's,
|
||||
* which a later receive replaces.
|
||||
*/
|
||||
private void returnMessagesToQueue(EventSourceMapping esm, List<Message> messages) {
|
||||
private void returnMessagesToQueue(EventSourceMapping esm, List<Message> messages,
|
||||
Map<String, ReceivedMessage> receivedById) {
|
||||
int retryVisibility = retryVisibilityTimeout(esm);
|
||||
for (Message msg : messages) {
|
||||
ReceivedMessage receipt = receivedById.get(msg.getMessageId());
|
||||
if (receipt == null) {
|
||||
LOG.warnv("ESM {0}: no receive recorded for message {1}, leaving its visibility as it is",
|
||||
esm.getUuid(), msg.getMessageId());
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
sqsService.changeMessageVisibility(
|
||||
esm.getQueueUrl(), msg.getReceiptHandle(), retryVisibility, esm.getRegion());
|
||||
boolean returned = sqsService.changeMessageVisibilityIfUnchanged(esm.getQueueUrl(),
|
||||
receipt.receiptHandle(), receipt.visibleAt(), retryVisibility, esm.getRegion());
|
||||
if (!returned) {
|
||||
LOG.debugv("ESM {0}: message {1} keeps the visibility set during the invocation",
|
||||
esm.getUuid(), msg.getMessageId());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("ESM {0}: failed to return message {1} to queue: {2}",
|
||||
esm.getUuid(), msg.getMessageId(), e.getMessage());
|
||||
@@ -348,6 +378,17 @@ public class SqsEventSourcePoller implements Resettable {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Received messages are the queue's live instances, which a ChangeMessageVisibility call or a
|
||||
* later receive updates during the invocation, so the handle and visibility each receive gave
|
||||
* them are recorded separately.
|
||||
*/
|
||||
private static void recordReceipts(List<Message> received, Map<String, ReceivedMessage> receivedById) {
|
||||
for (Message msg : received) {
|
||||
receivedById.put(msg.getMessageId(), new ReceivedMessage(msg.getReceiptHandle(), msg.getVisibleAt()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The visibility timeout to apply when returning a failed message to the queue: the
|
||||
* queue's configured {@code VisibilityTimeout}, or the AWS default of 30s when unset
|
||||
|
||||
@@ -178,7 +178,7 @@ class GuardedMessageQueue {
|
||||
}
|
||||
}
|
||||
|
||||
enum HandleResult { APPLIED, MESSAGE_GONE, HANDLE_EXPIRED }
|
||||
enum HandleResult { APPLIED, MESSAGE_GONE, HANDLE_EXPIRED, VISIBILITY_CHANGED }
|
||||
|
||||
record Removal(HandleResult result, Message message) {
|
||||
}
|
||||
@@ -196,8 +196,25 @@ class GuardedMessageQueue {
|
||||
}
|
||||
|
||||
HandleResult changeVisibility(ReceiptHandle handle, int visibilityTimeout, boolean fifo) {
|
||||
return changeVisibility(handle, null, visibilityTimeout, fifo);
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the message's visibility only while it is still {@code expectedVisibleAt}, so a change
|
||||
* made since (by a ChangeMessageVisibility call or another receive) is kept. A null
|
||||
* {@code expectedVisibleAt} changes it unconditionally.
|
||||
*
|
||||
* <p>The visibility is compared before the handle is checked: after another receive, a FIFO
|
||||
* queue would reject the caller's older handle as expired, but the outcome the caller asked
|
||||
* for, leaving a changed message alone, is the same.
|
||||
*/
|
||||
HandleResult changeVisibility(ReceiptHandle handle, Instant expectedVisibleAt, int visibilityTimeout,
|
||||
boolean fifo) {
|
||||
try (Guard _ = hold()) {
|
||||
Message msg = findByMessageId(handle.messageId());
|
||||
if (msg != null && expectedVisibleAt != null && !expectedVisibleAt.equals(msg.getVisibleAt())) {
|
||||
return HandleResult.VISIBILITY_CHANGED;
|
||||
}
|
||||
HandleResult result = checkHandle(msg, handle, fifo);
|
||||
if (result == HandleResult.APPLIED) {
|
||||
Instant previous = msg.getVisibleAt();
|
||||
|
||||
@@ -1712,11 +1712,22 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
}
|
||||
|
||||
public void changeMessageVisibility(String queueUrl, String receiptHandle, int visibilityTimeout, String region) {
|
||||
changeMessageVisibility(queueUrl, receiptHandle, visibilityTimeout, region, false);
|
||||
changeMessageVisibility(queueUrl, receiptHandle, null, visibilityTimeout, region, false);
|
||||
}
|
||||
|
||||
private void changeMessageVisibility(String queueUrl, String receiptHandle, int visibilityTimeout,
|
||||
String region, boolean inBatch) {
|
||||
/**
|
||||
* Changes a message's visibility timeout unless its visibility is no longer
|
||||
* {@code expectedVisibleAt}: a consumer that called ChangeMessageVisibility since keeps the
|
||||
* timeout it set. Returns whether the timeout was changed.
|
||||
*/
|
||||
public boolean changeMessageVisibilityIfUnchanged(String queueUrl, String receiptHandle,
|
||||
Instant expectedVisibleAt, int visibilityTimeout,
|
||||
String region) {
|
||||
return changeMessageVisibility(queueUrl, receiptHandle, expectedVisibleAt, visibilityTimeout, region, false);
|
||||
}
|
||||
|
||||
private boolean changeMessageVisibility(String queueUrl, String receiptHandle, Instant expectedVisibleAt,
|
||||
int visibilityTimeout, String region, boolean inBatch) {
|
||||
String storageKey = regionKey(region, queueUrl);
|
||||
Queue queue = queueStore.get(storageKey)
|
||||
.orElseThrow(() -> new AwsException("AWS.SimpleQueueService.NonExistentQueue",
|
||||
@@ -1725,12 +1736,14 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
|
||||
GuardedMessageQueue messages = getOrCreateQueue(storageKey);
|
||||
messages.activity().accessed();
|
||||
GuardedMessageQueue.HandleResult result = messages.changeVisibility(handle, visibilityTimeout, queue.isFifo());
|
||||
GuardedMessageQueue.HandleResult result =
|
||||
messages.changeVisibility(handle, expectedVisibleAt, visibilityTimeout, queue.isFifo());
|
||||
rejectUnusableHandle(result, receiptHandle, inBatch);
|
||||
if (result == GuardedMessageQueue.HandleResult.MESSAGE_GONE) {
|
||||
throw invalidReceiptHandle(receiptHandle,
|
||||
"Message does not exist or is not available for visibility timeout change", inBatch);
|
||||
}
|
||||
return result == GuardedMessageQueue.HandleResult.APPLIED;
|
||||
}
|
||||
|
||||
private static void rejectUnusableHandle(GuardedMessageQueue.HandleResult result, String receiptHandle,
|
||||
@@ -2096,7 +2109,7 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
List<BatchResultEntry> results = new ArrayList<>();
|
||||
for (ChangeVisibilityBatchEntry entry : entries) {
|
||||
try {
|
||||
changeMessageVisibility(queueUrl, entry.receiptHandle(), entry.visibilityTimeout(), region, true);
|
||||
changeMessageVisibility(queueUrl, entry.receiptHandle(), null, entry.visibilityTimeout(), region, true);
|
||||
results.add(new BatchResultEntry(entry.id(), true, null, null));
|
||||
} catch (AwsException e) {
|
||||
results.add(new BatchResultEntry(entry.id(), false, e.getErrorCode(), e.getMessage()));
|
||||
|
||||
Reference in new issue
Block a user