diff --git a/src/main/java/io/floci/aws/services/sqs/SqsService.java b/src/main/java/io/floci/aws/services/sqs/SqsService.java index af504564c4..7306c3d96a 100644 --- a/src/main/java/io/floci/aws/services/sqs/SqsService.java +++ b/src/main/java/io/floci/aws/services/sqs/SqsService.java @@ -90,7 +90,7 @@ public class SqsService implements Resettable, ResourceProvider { private final StorageBackend> dedupStore; private final StorageBackend>> dedupIdentityStore; private final ConcurrentHashMap messagesByQueue = new ConcurrentHashMap<>(); - private final ConcurrentHashMap queueLocks = new ConcurrentHashMap<>(); + private final ConcurrentHashMap queueLocks = new ConcurrentHashMap<>(); private final ConcurrentHashMap redrivePolicyCache = new ConcurrentHashMap<>(); private final ConcurrentHashMap> deduplicationCache = new ConcurrentHashMap<>(); private final ConcurrentHashMap> 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++; diff --git a/src/test/java/io/floci/aws/services/sqs/SqsServiceTest.java b/src/test/java/io/floci/aws/services/sqs/SqsServiceTest.java index c0d6f7ac1b..e982e45f7d 100644 --- a/src/test/java/io/floci/aws/services/sqs/SqsServiceTest.java +++ b/src/test/java/io/floci/aws/services/sqs/SqsServiceTest.java @@ -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> 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 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 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> 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 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 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 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 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 task = new AtomicReference<>(); + + List 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 task = new AtomicReference<>(); + try { + List 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> 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 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 receiveAfterAction(String queueUrl, String region, Runnable action) throws Exception { + FutureTask> receive = new FutureTask<>( + () -> sqsService.receiveMessage(queueUrl, 1, 30, 20, region)); + Thread poller = new Thread(receive, "sqs-wakeup"); + poller.start(); + List 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