mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(sqs): wake long polls after redrive and message moves (#9140)
This commit is contained in:
1 parent
e6345cf331
commit
82bc86f7f3
2 files changed
+160
-36
No files matched your search
@@ -90,7 +90,7 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
private final StorageBackend<String, Map<String, Long>> dedupStore;
|
||||
private final StorageBackend<String, Map<String, Map<String, String>>> dedupIdentityStore;
|
||||
private final ConcurrentHashMap<String, GuardedMessageQueue> messagesByQueue = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, Object> queueLocks = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, AtomicLong> queueLocks = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, RedrivePolicy> redrivePolicyCache = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, ConcurrentHashMap<String, Instant>> deduplicationCache = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, ConcurrentHashMap<String, DeduplicationIdentity>> deduplicationIdentityCache =
|
||||
@@ -1482,9 +1482,10 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
}
|
||||
|
||||
private void notifyReceivers(String storageKey) {
|
||||
Object lock = queueLocks.get(storageKey);
|
||||
AtomicLong lock = queueLocks.get(storageKey);
|
||||
if (lock != null) {
|
||||
synchronized (lock) {
|
||||
lock.incrementAndGet();
|
||||
lock.notifyAll();
|
||||
}
|
||||
}
|
||||
@@ -1538,13 +1539,14 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
|
||||
long start = System.currentTimeMillis();
|
||||
long maxWait = resolveWaitTimeSeconds(queue, waitTimeSeconds) * 1000L;
|
||||
Object lock = queueLocks.computeIfAbsent(storageKey, k -> new Object());
|
||||
AtomicLong lock = queueLocks.computeIfAbsent(storageKey, k -> new AtomicLong());
|
||||
// The queue incarnation this call polls against. DeleteQueue removes it
|
||||
// from messagesByQueue (and CreateQueue registers a fresh instance), so
|
||||
// an identity change tells a parked long poll that its queue is gone.
|
||||
GuardedMessageQueue polledQueue = getOrCreateQueue(storageKey);
|
||||
|
||||
while (true) {
|
||||
long notification = lock.get();
|
||||
if (messagesByQueue.get(storageKey) != polledQueue) {
|
||||
// The queue was deleted mid-poll (and possibly recreated under
|
||||
// the same URL). Finish empty-handed: a receive opened against
|
||||
@@ -1569,7 +1571,10 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
}
|
||||
try {
|
||||
synchronized (lock) {
|
||||
lock.wait(Math.min(1000, maxWait - elapsed));
|
||||
// A delivery after the empty check must trigger a retry, even before wait().
|
||||
if (lock.get() == notification) {
|
||||
lock.wait(Math.min(1000, maxWait - elapsed));
|
||||
}
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
@@ -1653,6 +1658,7 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
}
|
||||
String dlqStorageKey = regionKey(region, dlqUrl);
|
||||
getOrCreateQueue(dlqStorageKey).addAll(dlqCandidates);
|
||||
notifyReceivers(dlqStorageKey);
|
||||
LOG.infov("Moved {0} messages to DLQ {1}", dlqCandidates.size(), dlqUrl);
|
||||
}
|
||||
|
||||
@@ -1923,7 +1929,7 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
// remainder runs on the background worker at the requested rate, draining
|
||||
// one message at a time so the source queue stays observably populated.
|
||||
long initialMoved = 0;
|
||||
if (moveOneMessage(srcQueueInitial, destUrl, region)) {
|
||||
if (moveOneMessage(srcQueueInitial, srcKey, destUrl, region)) {
|
||||
initialMoved = 1;
|
||||
updateMoveTaskCounter(taskHandle, initialMoved);
|
||||
}
|
||||
@@ -1948,6 +1954,7 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
if (destUrl != null) {
|
||||
String destKey = regionKey(region, destUrl);
|
||||
getOrCreateQueue(destKey).addAll(List.of(moved));
|
||||
notifyReceivers(destKey);
|
||||
return true;
|
||||
}
|
||||
if (msg.getOriginalSourceQueueUrl() != null) {
|
||||
@@ -1957,6 +1964,7 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
// the queue any future receive will see.
|
||||
String originKey = regionKey(region, msg.getOriginalSourceQueueUrl());
|
||||
getOrCreateQueue(originKey).addAll(List.of(moved));
|
||||
notifyReceivers(originKey);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
@@ -1972,13 +1980,14 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
/** Move the head message of {@code sourceQueue}. Returns {@code false} when there is
|
||||
* nothing to move, the target queue is missing, or delivery failed; in the latter case
|
||||
* the message is put back at the head so the source keeps its order. */
|
||||
private boolean moveOneMessage(GuardedMessageQueue sourceQueue, String destUrl, String region) {
|
||||
private boolean moveOneMessage(GuardedMessageQueue sourceQueue, String sourceKey, String destUrl, String region) {
|
||||
Message message = sourceQueue.drainFirstIf(msg -> canDeliverMovedMessage(msg, destUrl, region));
|
||||
if (message == null) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
if (deliverMovedMessage(message, destUrl, region)) {
|
||||
notifyReceivers(sourceKey);
|
||||
return true;
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
@@ -2014,7 +2023,7 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
}
|
||||
}
|
||||
removeExpiredMessages(srcKey);
|
||||
if (!moveOneMessage(srcQueue, destUrl, region)) {
|
||||
if (!moveOneMessage(srcQueue, srcKey, destUrl, region)) {
|
||||
break;
|
||||
}
|
||||
moved++;
|
||||
|
||||
@@ -23,6 +23,8 @@ import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.net.URI;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
@@ -2561,30 +2563,16 @@ class SqsServiceTest {
|
||||
assertTrue(sqsService.receiveMessage(queueUrl, 1, 30, 0, region).isEmpty(),
|
||||
"The next message must remain blocked while the head is in flight");
|
||||
|
||||
FutureTask<List<Message>> receive = new FutureTask<>(
|
||||
() -> sqsService.receiveMessage(queueUrl, 1, 30, 20, region));
|
||||
Thread poller = new Thread(receive, "sqs-fifo-delete-wakeup");
|
||||
poller.start();
|
||||
try {
|
||||
// Observe the actual wait rather than sleeping and assuming the receive has parked.
|
||||
await().pollInterval(Duration.ofMillis(1)).atMost(Duration.ofSeconds(5))
|
||||
.until(() -> poller.getState() == Thread.State.TIMED_WAITING);
|
||||
List<Message> received = receiveAfterAction(queueUrl, region, () -> {
|
||||
if (inBatch) {
|
||||
sqsService.deleteMessageInBatch(queueUrl, head.getReceiptHandle(), region);
|
||||
} else {
|
||||
sqsService.deleteMessage(queueUrl, head.getReceiptHandle(), region);
|
||||
}
|
||||
|
||||
// Require a wakeup before the one-second polling retry.
|
||||
List<Message> received = receive.get(750, TimeUnit.MILLISECONDS);
|
||||
assertEquals(1, received.size());
|
||||
assertEquals(next.getMessageId(), received.getFirst().getMessageId());
|
||||
assertEquals(1, received.getFirst().getReceiveCount());
|
||||
} finally {
|
||||
poller.interrupt();
|
||||
poller.join(5000);
|
||||
}
|
||||
assertFalse(poller.isAlive());
|
||||
});
|
||||
assertEquals(1, received.size());
|
||||
assertEquals(next.getMessageId(), received.getFirst().getMessageId());
|
||||
assertEquals(1, received.getFirst().getReceiveCount());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -2598,13 +2586,7 @@ class SqsServiceTest {
|
||||
Message head = sqsService.receiveMessage(queueUrl, 1, 30, 0, region).getFirst();
|
||||
assertTrue(sqsService.receiveMessage(queueUrl, 1, 30, 0, region).isEmpty());
|
||||
|
||||
FutureTask<List<Message>> receive = new FutureTask<>(
|
||||
() -> sqsService.receiveMessage(queueUrl, 1, 30, 20, region));
|
||||
Thread poller = new Thread(receive, "sqs-visibility-wakeup");
|
||||
poller.start();
|
||||
try {
|
||||
await().pollInterval(Duration.ofMillis(1)).atMost(Duration.ofSeconds(5))
|
||||
.until(() -> poller.getState() == Thread.State.TIMED_WAITING);
|
||||
List<Message> received = receiveAfterAction(queueUrl, region, () -> {
|
||||
switch (operation) {
|
||||
case "single" -> sqsService.changeMessageVisibility(queueUrl, head.getReceiptHandle(), 0, region);
|
||||
case "batch" -> {
|
||||
@@ -2617,12 +2599,125 @@ class SqsServiceTest {
|
||||
head.getReceiptHandle(), head.getVisibleAt(), 0, region));
|
||||
default -> throw new AssertionError("Unknown visibility operation: " + operation);
|
||||
}
|
||||
});
|
||||
assertEquals(1, received.size());
|
||||
assertEquals(head.getMessageId(), received.getFirst().getMessageId());
|
||||
assertEquals(2, received.getFirst().getReceiveCount());
|
||||
}
|
||||
|
||||
// Require a wakeup before the one-second polling retry.
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void deadLetterRedriveWakesParkedReceive(boolean fifo) throws Exception {
|
||||
String region = "eu-west-1";
|
||||
String suffix = fifo ? ".fifo" : "";
|
||||
Map<String, String> attributes = fifo ? Map.of("FifoQueue", "true") : null;
|
||||
Queue dlq = sqsService.createQueue("wakeup-dlq" + suffix, attributes, region);
|
||||
String dlqArn = sqsService.getQueueAttributes(dlq.getQueueUrl(), List.of("QueueArn"), region).get("QueueArn");
|
||||
String policy = "{\"deadLetterTargetArn\":\"" + dlqArn + "\",\"maxReceiveCount\":\"1\"}";
|
||||
Queue source = sqsService.createQueue("wakeup-source" + suffix,
|
||||
fifo ? Map.of("FifoQueue", "true", "RedrivePolicy", policy) : Map.of("RedrivePolicy", policy), region);
|
||||
Message sent = sqsService.sendMessage(source.getQueueUrl(), "dead-lettered", 0,
|
||||
fifo ? "group" : null, fifo ? "message" : null, region);
|
||||
assertEquals(1, sqsService.receiveMessage(source.getQueueUrl(), 1, 0, 0, region).size());
|
||||
|
||||
List<Message> received = receiveAfterAction(dlq.getQueueUrl(), region, () ->
|
||||
assertTrue(sqsService.receiveMessage(source.getQueueUrl(), 1, 0, 0, region).isEmpty()));
|
||||
assertEquals(1, received.size());
|
||||
assertEquals(sent.getMessageId(), received.getFirst().getMessageId());
|
||||
assertEquals("dead-lettered", received.getFirst().getBody());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"false,false", "false,true", "true,false", "true,true"})
|
||||
void messageMoveTaskWakesParkedDestination(boolean fifo, boolean explicitDestination) throws Exception {
|
||||
String region = "eu-west-1";
|
||||
String suffix = fifo ? ".fifo" : "";
|
||||
Map<String, String> attributes = fifo ? Map.of("FifoQueue", "true") : null;
|
||||
Queue dlq = sqsService.createQueue("move-wakeup-dlq" + suffix, attributes, region);
|
||||
String dlqArn = sqsService.getQueueAttributes(dlq.getQueueUrl(), List.of("QueueArn"), region).get("QueueArn");
|
||||
String policy = "{\"deadLetterTargetArn\":\"" + dlqArn + "\",\"maxReceiveCount\":\"1\"}";
|
||||
Queue source = sqsService.createQueue("move-wakeup-origin" + suffix,
|
||||
fifo ? Map.of("FifoQueue", "true", "RedrivePolicy", policy) : Map.of("RedrivePolicy", policy), region);
|
||||
Message sent = sqsService.sendMessage(source.getQueueUrl(), "moved", 0,
|
||||
fifo ? "group" : null, fifo ? "message" : null, region);
|
||||
sqsService.receiveMessage(source.getQueueUrl(), 1, 0, 0, region);
|
||||
assertTrue(sqsService.receiveMessage(source.getQueueUrl(), 1, 0, 0, region).isEmpty());
|
||||
Queue destination = explicitDestination
|
||||
? sqsService.createQueue("move-wakeup-destination" + suffix, attributes, region) : source;
|
||||
String destinationArn = explicitDestination
|
||||
? sqsService.getQueueAttributes(destination.getQueueUrl(), List.of("QueueArn"), region).get("QueueArn")
|
||||
: null;
|
||||
AtomicReference<String> task = new AtomicReference<>();
|
||||
|
||||
List<Message> received = receiveAfterAction(destination.getQueueUrl(), region,
|
||||
() -> task.set(sqsService.startMessageMoveTask(dlqArn, destinationArn, region)));
|
||||
assertEquals(1, received.size());
|
||||
assertEquals("moved", received.getFirst().getBody());
|
||||
assertNotEquals(sent.getMessageId(), received.getFirst().getMessageId());
|
||||
assertEquals(1, received.getFirst().getReceiveCount());
|
||||
awaitMoveTaskStatus(dlqArn, task.get(), "COMPLETED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void messageMoveTaskWakesParkedFifoSource() throws Exception {
|
||||
String region = "eu-west-1";
|
||||
Queue dlq = sqsService.createQueue("moving-head-dlq.fifo", Map.of("FifoQueue", "true"), region);
|
||||
String dlqArn = sqsService.getQueueAttributes(dlq.getQueueUrl(), List.of("QueueArn"), region).get("QueueArn");
|
||||
String policy = "{\"deadLetterTargetArn\":\"" + dlqArn + "\",\"maxReceiveCount\":\"1\"}";
|
||||
sqsService.createQueue("moving-head-origin.fifo",
|
||||
Map.of("FifoQueue", "true", "RedrivePolicy", policy), region);
|
||||
Queue destination = sqsService.createQueue("moving-head-destination.fifo", Map.of("FifoQueue", "true"), region);
|
||||
String destinationArn = sqsService.getQueueAttributes(
|
||||
destination.getQueueUrl(), List.of("QueueArn"), region).get("QueueArn");
|
||||
sqsService.sendMessage(dlq.getQueueUrl(), "head", 0, "group", "head", region);
|
||||
Message next = sqsService.sendMessage(dlq.getQueueUrl(), "next", 0, "group", "next", region);
|
||||
assertEquals("head", sqsService.receiveMessage(dlq.getQueueUrl(), 1, 30, 0, region).getFirst().getBody());
|
||||
assertTrue(sqsService.receiveMessage(dlq.getQueueUrl(), 1, 30, 0, region).isEmpty());
|
||||
AtomicReference<String> task = new AtomicReference<>();
|
||||
try {
|
||||
List<Message> received = receiveAfterAction(dlq.getQueueUrl(), region,
|
||||
() -> task.set(sqsService.startMessageMoveTask(dlqArn, destinationArn, 1, region)));
|
||||
assertEquals(1, received.size());
|
||||
assertEquals(next.getMessageId(), received.getFirst().getMessageId());
|
||||
assertEquals(1, received.getFirst().getReceiveCount());
|
||||
} finally {
|
||||
if (task.get() != null) {
|
||||
sqsService.cancelMessageMoveTask(task.get(), region);
|
||||
awaitMoveTaskStatus(dlqArn, task.get(), "CANCELLED");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void redriveBetweenEmptyCheckAndWaitDoesNotLoseWakeup() throws Exception {
|
||||
String region = "eu-west-1";
|
||||
Queue dlq = sqsService.createQueue("check-wait-dlq", null, region);
|
||||
String dlqArn = sqsService.getQueueAttributes(dlq.getQueueUrl(), List.of("QueueArn"), region).get("QueueArn");
|
||||
String policy = "{\"deadLetterTargetArn\":\"" + dlqArn + "\",\"maxReceiveCount\":\"1\"}";
|
||||
Queue source = sqsService.createQueue("check-wait-source", Map.of("RedrivePolicy", policy), region);
|
||||
Message sent = sqsService.sendMessage(source.getQueueUrl(), "redriven", 0, region);
|
||||
sqsService.receiveMessage(source.getQueueUrl(), 1, 0, 0, region);
|
||||
assertTrue(sqsService.receiveMessage(dlq.getQueueUrl(), 1, 30, 0, region).isEmpty());
|
||||
|
||||
// Hold the actual wait monitor to stop the receiver after its empty check, before wait().
|
||||
Field locksField = SqsService.class.getDeclaredField("queueLocks");
|
||||
locksField.setAccessible(true);
|
||||
Map<?, ?> locks = (Map<?, ?>) locksField.get(sqsService);
|
||||
Object lock = locks.get(region + "::" + URI.create(dlq.getQueueUrl()).getPath());
|
||||
assertNotNull(lock);
|
||||
FutureTask<List<Message>> receive = new FutureTask<>(
|
||||
() -> sqsService.receiveMessage(dlq.getQueueUrl(), 1, 30, 20, region));
|
||||
Thread poller = new Thread(receive, "sqs-check-wait-redrive");
|
||||
try {
|
||||
synchronized (lock) {
|
||||
poller.start();
|
||||
await().pollInterval(Duration.ofMillis(1)).atMost(Duration.ofSeconds(5))
|
||||
.until(() -> poller.getState() == Thread.State.BLOCKED);
|
||||
assertTrue(sqsService.receiveMessage(source.getQueueUrl(), 1, 0, 0, region).isEmpty());
|
||||
}
|
||||
List<Message> received = receive.get(750, TimeUnit.MILLISECONDS);
|
||||
assertEquals(1, received.size());
|
||||
assertEquals(head.getMessageId(), received.getFirst().getMessageId());
|
||||
assertEquals(2, received.getFirst().getReceiveCount());
|
||||
assertEquals(sent.getMessageId(), received.getFirst().getMessageId());
|
||||
} finally {
|
||||
poller.interrupt();
|
||||
poller.join(5000);
|
||||
@@ -2630,6 +2725,26 @@ class SqsServiceTest {
|
||||
assertFalse(poller.isAlive());
|
||||
}
|
||||
|
||||
private List<Message> receiveAfterAction(String queueUrl, String region, Runnable action) throws Exception {
|
||||
FutureTask<List<Message>> receive = new FutureTask<>(
|
||||
() -> sqsService.receiveMessage(queueUrl, 1, 30, 20, region));
|
||||
Thread poller = new Thread(receive, "sqs-wakeup");
|
||||
poller.start();
|
||||
List<Message> received;
|
||||
try {
|
||||
await().pollInterval(Duration.ofMillis(1)).atMost(Duration.ofSeconds(5))
|
||||
.until(() -> poller.getState() == Thread.State.TIMED_WAITING);
|
||||
action.run();
|
||||
// Require a wakeup before the one-second polling retry.
|
||||
received = receive.get(750, TimeUnit.MILLISECONDS);
|
||||
} finally {
|
||||
poller.interrupt();
|
||||
poller.join(5000);
|
||||
}
|
||||
assertFalse(poller.isAlive());
|
||||
return received;
|
||||
}
|
||||
|
||||
// --- DeleteQueue releases in-flight ReceiveMessage long polls ---
|
||||
|
||||
@Test
|
||||
|
||||
Reference in new issue
Block a user