feat(sqs): expire messages after MessageRetentionPeriod (#4706)

* feat(sqs): expire messages after MessageRetentionPeriod

ReceiveMessage, GetQueueAttributes counts, the inspection endpoint and
StartMessageMoveTask skip messages older than the queue's retention
period. A sweeper frees expired messages every 60 seconds.

As on AWS, a standard DLQ keeps the original enqueue time, while a FIFO
DLQ and StartMessageMoveTask start the retention period over.
SentTimestamp is kept in all cases.

* fix(sqs): drop messages that expire during a rate-limited move task

* test(sqs): cover a failing retention sweep

* test(sqs): make the rate-limited move task expiry test deterministic

* test(sqs): assert the expiring message is live when the move task starts

* fix(sqs): reject MessageRetentionPeriod outside 60 to 1209600 seconds
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-09-30 00:03:48 -04:00
1 parent ae710c04d0
commit e6ee346761
8 files changed
+375 -7

No files matched your search

@@ -198,6 +198,14 @@ class GuardedMessageQueue {
}
}
void removeExpired(Instant cutoff) {
try (Guard _ = hold()) {
if (messages.removeIf(msg -> msg.isExpired(cutoff))) {
persist();
}
}
}
void purge() {
try (Guard _ = hold()) {
messages.clear();
@@ -0,0 +1,56 @@
package io.github.hectorvent.floci.services.sqs;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.quarkus.runtime.ShutdownEvent;
import io.quarkus.runtime.StartupEvent;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@ApplicationScoped
public class SqsRetentionSweeper {
private static final Logger LOG = Logger.getLogger(SqsRetentionSweeper.class);
private static final long SWEEP_INTERVAL_SECONDS = 60;
private final SqsService sqsService;
private final boolean enabled;
private final ScheduledExecutorService scheduler;
@Inject
public SqsRetentionSweeper(SqsService sqsService, EmulatorConfig config) {
this.sqsService = sqsService;
this.enabled = config.services().sqs().enabled();
this.scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "sqs-retention-sweeper");
t.setDaemon(true);
return t;
});
}
void onStart(@Observes StartupEvent ignored) {
if (!enabled) {
return;
}
scheduler.scheduleAtFixedRate(this::sweep, SWEEP_INTERVAL_SECONDS, SWEEP_INTERVAL_SECONDS,
TimeUnit.SECONDS);
LOG.infov("SQS retention sweeper scheduled ({0}s interval)", SWEEP_INTERVAL_SECONDS);
}
void onStop(@Observes ShutdownEvent ignored) {
scheduler.shutdownNow();
}
void sweep() {
try {
sqsService.deleteExpiredMessages();
} catch (RuntimeException e) {
LOG.warnv(e, "SQS retention sweep failed; retrying on the next run");
}
}
}
@@ -65,6 +65,9 @@ public class SqsService implements Resettable, ResourceProvider {
* Both the maximum and the default were raised from 256 KiB in August 2025. */
private static final int MIN_MAXIMUM_MESSAGE_SIZE = 1024;
private static final int AWS_MAXIMUM_MESSAGE_SIZE = 1048576;
private static final int DEFAULT_MESSAGE_RETENTION_PERIOD_SECONDS = 345600;
private static final int MIN_MESSAGE_RETENTION_PERIOD_SECONDS = 60;
private static final int MAX_MESSAGE_RETENTION_PERIOD_SECONDS = 1209600;
private final StorageBackend<String, Queue> queueStore;
private final StorageBackend<String, List<Message>> messageStore;
@@ -570,6 +573,7 @@ public class SqsService implements Resettable, ResourceProvider {
}
validateMaximumMessageSize(attributes);
attributes = validateMessageRetentionPeriod(attributes);
String accountId = regionResolver.getAccountId();
String queueUrl = baseUrl + "/" + accountId + "/" + queueName;
@@ -693,7 +697,7 @@ public class SqsService implements Resettable, ResourceProvider {
attrs.put("CreatedTimestamp", String.valueOf(queue.getCreatedTimestamp().getEpochSecond()));
attrs.put("LastModifiedTimestamp", String.valueOf(queue.getLastModifiedTimestamp().getEpochSecond()));
GuardedMessageQueue.MessageCounts counts = getOrCreateQueue(storageKey).messageCounts();
GuardedMessageQueue.MessageCounts counts = unexpiredMessages(storageKey, queue).messageCounts();
attrs.put("ApproximateNumberOfMessages", String.valueOf(counts.visible()));
attrs.put("ApproximateNumberOfMessagesNotVisible", String.valueOf(counts.inFlight()));
attrs.put("ApproximateNumberOfMessagesDelayed", String.valueOf(counts.delayed()));
@@ -948,6 +952,30 @@ public class SqsService implements Resettable, ResourceProvider {
}
}
/** AWS stores a valid value in canonical form, so "060" and "+60" read back as "60". */
private static Map<String, String> validateMessageRetentionPeriod(Map<String, String> attributes) {
if (attributes == null || !attributes.containsKey("MessageRetentionPeriod")) {
return attributes;
}
int parsed;
try {
parsed = Integer.parseInt(attributes.get("MessageRetentionPeriod"));
} catch (NumberFormatException ignored) {
throw invalidMessageRetentionPeriod();
}
if (parsed < MIN_MESSAGE_RETENTION_PERIOD_SECONDS || MAX_MESSAGE_RETENTION_PERIOD_SECONDS < parsed) {
throw invalidMessageRetentionPeriod();
}
Map<String, String> normalized = new HashMap<>(attributes);
normalized.put("MessageRetentionPeriod", String.valueOf(parsed));
return normalized;
}
private static AwsException invalidMessageRetentionPeriod() {
return new AwsException("InvalidAttributeValue",
"Invalid value for the parameter MessageRetentionPeriod.", 400);
}
private AwsException invalidMaximumMessageSize() {
return new AwsException("InvalidAttributeValue",
"Invalid value for the parameter MaximumMessageSize.", 400);
@@ -1167,7 +1195,7 @@ public class SqsService implements Resettable, ResourceProvider {
int maxReceiveCount = rp != null ? rp.maxReceiveCount() : -1;
String deadLetterTargetArn = rp != null ? rp.deadLetterTargetArn() : null;
GuardedMessageQueue guardedQueue = getOrCreateQueue(storageKey);
GuardedMessageQueue guardedQueue = unexpiredMessages(storageKey, queue);
GuardedMessageQueue.ClaimResult claimResult = guardedQueue.claimVisibleMessages(
maxMessages, effectiveTimeout, queue.isFifo(), maxReceiveCount, deadLetterTargetArn);
@@ -1183,6 +1211,9 @@ public class SqsService implements Resettable, ResourceProvider {
// Remember where the message came from so StartMessageMoveTask
// with no DestinationArn can put it back.
msg.setOriginalSourceQueueUrl(queue.getQueueUrl());
if (queue.isFifo()) {
msg.setRetentionStartTimestamp(Instant.now());
}
}
String dlqStorageKey = regionKey(region, dlqUrl);
getOrCreateQueue(dlqStorageKey).addAll(dlqCandidates);
@@ -1206,8 +1237,10 @@ public class SqsService implements Resettable, ResourceProvider {
public List<Message> peekMessages(String queueUrl, String region) {
String storageKey = regionKey(region, queueUrl);
ensureQueueExists(storageKey);
return getOrCreateQueue(storageKey).peekAll();
Queue queue = queueStore.get(storageKey)
.orElseThrow(() -> new AwsException("AWS.SimpleQueueService.NonExistentQueue",
"The specified queue does not exist.", 400));
return unexpiredMessages(storageKey, queue).peekAll();
}
public void deleteMessage(String queueUrl, String receiptHandle, String region) {
@@ -1270,6 +1303,7 @@ public class SqsService implements Resettable, ResourceProvider {
.orElseThrow(() -> new AwsException("AWS.SimpleQueueService.NonExistentQueue",
"The specified queue does not exist.", 400));
validateMaximumMessageSize(attributes);
attributes = validateMessageRetentionPeriod(attributes);
if (attributes != null) {
for (Map.Entry<String, String> entry : attributes.entrySet()) {
if (entry.getValue() == null || entry.getValue().isEmpty()) {
@@ -1313,7 +1347,8 @@ public class SqsService implements Resettable, ResourceProvider {
"Invalid source ARN: " + sourceArn, 400);
}
String srcKey = regionKey(region, sourceUrl);
if (queueStore.get(srcKey).isEmpty()) {
Optional<Queue> srcQueue = queueStore.get(srcKey);
if (srcQueue.isEmpty()) {
throw new AwsException("ResourceNotFoundException",
"The resource that you specified for the SourceArn parameter does not exist.", 404);
}
@@ -1354,7 +1389,7 @@ public class SqsService implements Resettable, ResourceProvider {
}
}
GuardedMessageQueue srcQueueInitial = getOrCreateQueue(srcKey);
GuardedMessageQueue srcQueueInitial = unexpiredMessages(srcKey, srcQueue.get());
GuardedMessageQueue.MessageCounts srcCounts = srcQueueInitial.messageCounts();
long toMove = srcCounts.visible() + srcCounts.inFlight() + srcCounts.delayed();
@@ -1462,6 +1497,7 @@ public class SqsService implements Resettable, ResourceProvider {
return;
}
}
removeExpiredMessages(srcKey);
if (!moveOneMessage(srcQueue, destUrl, region)) {
break;
}
@@ -1783,6 +1819,41 @@ public class SqsService implements Resettable, ResourceProvider {
return queueUrl.substring(pathStart);
}
private GuardedMessageQueue unexpiredMessages(String storageKey, Queue queue) {
GuardedMessageQueue messages = getOrCreateQueue(storageKey);
messages.removeExpired(retentionCutoff(queue));
return messages;
}
private static Instant retentionCutoff(Queue queue) {
int retentionSeconds = DEFAULT_MESSAGE_RETENTION_PERIOD_SECONDS;
String value = queue.getAttributes().get("MessageRetentionPeriod");
if (value != null) {
try {
retentionSeconds = Integer.parseInt(value.trim());
} catch (NumberFormatException e) {
LOG.debugv("Ignoring invalid MessageRetentionPeriod {0} on queue {1}", value, queue.getQueueUrl());
}
}
return Instant.now().minusSeconds(retentionSeconds);
}
/** Frees the memory and storage held by expired messages. Reads already skip them. */
void deleteExpiredMessages() {
for (String storageKey : messagesByQueue.keySet()) {
removeExpiredMessages(storageKey);
}
}
private void removeExpiredMessages(String storageKey) {
GuardedMessageQueue messages = messagesByQueue.get(storageKey);
if (messages == null) {
return;
}
String queueUrl = baseUrl + storageKey.substring(storageKey.indexOf("::") + 2);
getQueueByUrl(storageKey, queueUrl).ifPresent(queue -> messages.removeExpired(retentionCutoff(queue)));
}
private void ensureQueueExists(String storageKey) {
if (queueStore.get(storageKey).isEmpty()) {
throw new AwsException("AWS.SimpleQueueService.NonExistentQueue",
@@ -46,6 +46,10 @@ public class Message {
// on ReceiveMessage when requested.
private String awsTraceHeader;
// The retention period starts over when a message is moved to a FIFO DLQ or by a message
// move task. A standard DLQ keeps the original enqueue time.
private Instant retentionStartTimestamp;
// Transient fields for visibility timeout tracking
@JsonIgnore
private String receiptHandle;
@@ -81,6 +85,7 @@ public class Message {
copy.sequenceNumber = sequenceNumber;
copy.originalSourceQueueUrl = originalSourceQueueUrl;
copy.awsTraceHeader = awsTraceHeader;
copy.retentionStartTimestamp = Instant.now();
// receiveCount 0, firstReceiveTimestamp / receiptHandle / visibleAt null: a fresh life.
return copy;
}
@@ -130,6 +135,15 @@ public class Message {
public String getAwsTraceHeader() { return awsTraceHeader; }
public void setAwsTraceHeader(String awsTraceHeader) { this.awsTraceHeader = awsTraceHeader; }
public Instant getRetentionStartTimestamp() { return retentionStartTimestamp; }
public void setRetentionStartTimestamp(Instant retentionStartTimestamp) { this.retentionStartTimestamp = retentionStartTimestamp; }
@JsonIgnore
public boolean isExpired(Instant cutoff) {
Instant start = retentionStartTimestamp != null ? retentionStartTimestamp : sentTimestamp;
return start != null && !start.isAfter(cutoff);
}
@JsonIgnore
public boolean isVisible() {
return visibleAt == null || !Instant.now().isBefore(visibleAt);