mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(sqs): retain fifo deduplication after message deletion (#4460)
* fix(sqs): retain fifo deduplication after message deletion * fix(sqs): preserve fifo send identity after deletion * fix(sqs): serialize fifo dedup expiry with sends * fix(sqs): narrow FIFO deduplication send locking * chore(ci): rerun PR test workflow --------- Co-authored-by: Vamsi Akavarapu <16164447+vamsiak@users.noreply.github.com>
This commit is contained in:
1 parent
2cccc73499
commit
bbb1e10fc8
3 files changed
+419
-49
No files matched your search
@@ -57,6 +57,7 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(SqsService.class);
|
||||
private static final int DEDUP_WINDOW_SECONDS = 300; // 5 minutes
|
||||
private static final int DEDUP_LOCK_STRIPES = 256;
|
||||
private static final int MAX_RECEIVE_WAIT_TIME_SECONDS = 20;
|
||||
private static final int MAX_TERMINAL_MOVE_TASKS = 10;
|
||||
private static final Duration TERMINAL_MOVE_TASK_TTL = Duration.ofHours(1);
|
||||
@@ -68,10 +69,14 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
private final StorageBackend<String, Queue> queueStore;
|
||||
private final StorageBackend<String, List<Message>> messageStore;
|
||||
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, RedrivePolicy> redrivePolicyCache = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, ConcurrentHashMap<String, Instant>> deduplicationCache = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, ConcurrentHashMap<String, DeduplicationIdentity>> deduplicationIdentityCache =
|
||||
new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, Object[]> deduplicationLocks = new ConcurrentHashMap<>();
|
||||
/** Move tasks keyed by opaque task handle. */
|
||||
private final MoveTaskStore moveTasksByHandle;
|
||||
/** Per-task cancellation signal: the move worker waits on it between moves, so a cancel wakes
|
||||
@@ -92,6 +97,9 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
private record RedrivePolicy(int maxReceiveCount, String deadLetterTargetArn) {
|
||||
}
|
||||
|
||||
private record DeduplicationIdentity(String messageId, long sequenceNumber) {
|
||||
}
|
||||
|
||||
public record MoveTask(String taskHandle, String sourceArn, String destinationArn,
|
||||
int maxNumberOfMessagesPerSecond, String status,
|
||||
long approximateNumberOfMessagesMoved,
|
||||
@@ -278,6 +286,9 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
storageFactory.create("sqs", "sqs-dedup.json",
|
||||
new TypeReference<Map<String, Map<String, Long>>>() {
|
||||
}),
|
||||
storageFactory.create("sqs", "sqs-dedup-identities.json",
|
||||
new TypeReference<Map<String, Map<String, Map<String, String>>>>() {
|
||||
}),
|
||||
config.services().sqs().defaultVisibilityTimeout(),
|
||||
config.services().sqs().maxMessageSize(),
|
||||
config.effectiveBaseUrl(),
|
||||
@@ -325,9 +336,20 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
int defaultVisibilityTimeout, int maxMessageSize, String baseUrl,
|
||||
RegionResolver regionResolver, boolean clearFifoDeduplicationCacheOnPurge,
|
||||
SnsService snsService, Clock clock) {
|
||||
this(queueStore, messageStore, dedupStore, null, defaultVisibilityTimeout, maxMessageSize,
|
||||
baseUrl, regionResolver, clearFifoDeduplicationCacheOnPurge, snsService, clock);
|
||||
}
|
||||
|
||||
SqsService(StorageBackend<String, Queue> queueStore, StorageBackend<String, List<Message>> messageStore,
|
||||
StorageBackend<String, Map<String, Long>> dedupStore,
|
||||
StorageBackend<String, Map<String, Map<String, String>>> dedupIdentityStore,
|
||||
int defaultVisibilityTimeout, int maxMessageSize, String baseUrl,
|
||||
RegionResolver regionResolver, boolean clearFifoDeduplicationCacheOnPurge,
|
||||
SnsService snsService, Clock clock) {
|
||||
this.queueStore = queueStore;
|
||||
this.messageStore = messageStore;
|
||||
this.dedupStore = dedupStore;
|
||||
this.dedupIdentityStore = dedupIdentityStore;
|
||||
this.defaultVisibilityTimeout = defaultVisibilityTimeout;
|
||||
this.maxMessageSize = maxMessageSize;
|
||||
this.maxAllowedMessageSize = Math.max(AWS_MAXIMUM_MESSAGE_SIZE, maxMessageSize);
|
||||
@@ -339,6 +361,7 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
this.moveTasksByHandle = new MoveTaskStore(clock);
|
||||
loadPersistedMessages();
|
||||
loadPersistedDedup();
|
||||
loadPersistedDedupIdentities();
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
@@ -352,6 +375,8 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
queueLocks.clear();
|
||||
redrivePolicyCache.clear();
|
||||
deduplicationCache.clear();
|
||||
deduplicationIdentityCache.clear();
|
||||
deduplicationLocks.clear();
|
||||
moveTaskCancellation.values().forEach(MoveTaskCancellation::request);
|
||||
moveTaskCancellation.clear();
|
||||
moveTasksByHandle.clear();
|
||||
@@ -376,7 +401,7 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
if (dedupStore == null) {
|
||||
return;
|
||||
}
|
||||
Instant now = Instant.now();
|
||||
Instant now = clock.instant();
|
||||
if (dedupStore instanceof AccountAwareStorageBackend<Map<String, Long>> aware) {
|
||||
aware.scanAllAccountsAsMap().forEach((key, entries) -> loadDedupEntries(key, entries, now));
|
||||
} else {
|
||||
@@ -399,6 +424,44 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
private void loadPersistedDedupIdentities() {
|
||||
if (dedupIdentityStore == null) {
|
||||
return;
|
||||
}
|
||||
if (dedupIdentityStore instanceof AccountAwareStorageBackend<Map<String, Map<String, String>>> aware) {
|
||||
aware.scanAllAccountsAsMap().forEach(this::loadDedupIdentities);
|
||||
} else {
|
||||
for (String key : dedupIdentityStore.keys()) {
|
||||
dedupIdentityStore.get(key).ifPresent(identities -> loadDedupIdentities(key, identities));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void loadDedupIdentities(String key, Map<String, Map<String, String>> entries) {
|
||||
ConcurrentHashMap<String, Instant> activeDedupEntries = deduplicationCache.get(key);
|
||||
if (activeDedupEntries == null) {
|
||||
return;
|
||||
}
|
||||
ConcurrentHashMap<String, DeduplicationIdentity> activeIdentities = new ConcurrentHashMap<>();
|
||||
entries.forEach((dedupKey, identityFields) -> {
|
||||
if (!activeDedupEntries.containsKey(dedupKey)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
String messageId = identityFields.get("messageId");
|
||||
long sequenceNumber = Long.parseLong(identityFields.get("sequenceNumber"));
|
||||
if (messageId != null && !messageId.isBlank()) {
|
||||
activeIdentities.put(dedupKey, new DeduplicationIdentity(messageId, sequenceNumber));
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("Ignoring invalid FIFO deduplication identity for queue {0}, key {1}", key, dedupKey);
|
||||
}
|
||||
});
|
||||
if (!activeIdentities.isEmpty()) {
|
||||
deduplicationIdentityCache.put(key, activeIdentities);
|
||||
}
|
||||
}
|
||||
|
||||
private GuardedMessageQueue getOrCreateQueue(String storageKey) {
|
||||
return messagesByQueue.computeIfAbsent(storageKey,
|
||||
k -> new GuardedMessageQueue(messageStore, k));
|
||||
@@ -409,13 +472,54 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
return;
|
||||
}
|
||||
ConcurrentHashMap<String, Instant> dedupMap = deduplicationCache.get(storageKey);
|
||||
if (dedupMap != null && !dedupMap.isEmpty()) {
|
||||
Map<String, Long> serializable = new HashMap<>();
|
||||
dedupMap.forEach((id, expiry) -> serializable.put(id, expiry.toEpochMilli()));
|
||||
dedupStore.put(storageKey, serializable);
|
||||
} else {
|
||||
if (dedupMap == null) {
|
||||
dedupStore.delete(storageKey);
|
||||
return;
|
||||
}
|
||||
// Serialize snapshots, not the entire send. Otherwise a slow message write
|
||||
// also blocks sends for unrelated deduplication IDs.
|
||||
synchronized (dedupMap) {
|
||||
if (dedupMap.isEmpty()) {
|
||||
dedupStore.delete(storageKey);
|
||||
} else {
|
||||
Map<String, Long> serializable = new HashMap<>();
|
||||
dedupMap.forEach((id, expiry) -> serializable.put(id, expiry.toEpochMilli()));
|
||||
dedupStore.put(storageKey, serializable);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void persistDedupIdentities(String storageKey) {
|
||||
if (dedupIdentityStore == null) {
|
||||
return;
|
||||
}
|
||||
ConcurrentHashMap<String, DeduplicationIdentity> identityMap = deduplicationIdentityCache.get(storageKey);
|
||||
if (identityMap == null) {
|
||||
dedupIdentityStore.delete(storageKey);
|
||||
return;
|
||||
}
|
||||
synchronized (identityMap) {
|
||||
if (identityMap.isEmpty()) {
|
||||
dedupIdentityStore.delete(storageKey);
|
||||
} else {
|
||||
Map<String, Map<String, String>> serializable = new HashMap<>();
|
||||
identityMap.forEach((dedupKey, identity) -> serializable.put(dedupKey, Map.of(
|
||||
"messageId", identity.messageId(),
|
||||
"sequenceNumber", Long.toString(identity.sequenceNumber()))));
|
||||
dedupIdentityStore.put(storageKey, serializable);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Object deduplicationLock(String storageKey, String dedupKey) {
|
||||
Object[] locks = deduplicationLocks.computeIfAbsent(storageKey, key -> {
|
||||
Object[] stripes = new Object[DEDUP_LOCK_STRIPES];
|
||||
for (int i = 0; i < stripes.length; i++) {
|
||||
stripes[i] = new Object();
|
||||
}
|
||||
return stripes;
|
||||
});
|
||||
return locks[dedupKey.hashCode() & (DEDUP_LOCK_STRIPES - 1)];
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -532,12 +636,17 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
removed.close();
|
||||
}
|
||||
deduplicationCache.remove(storageKey);
|
||||
deduplicationIdentityCache.remove(storageKey);
|
||||
deduplicationLocks.remove(storageKey);
|
||||
if (messageStore != null) {
|
||||
messageStore.delete(storageKey);
|
||||
}
|
||||
if (dedupStore != null) {
|
||||
dedupStore.delete(storageKey);
|
||||
}
|
||||
if (dedupIdentityStore != null) {
|
||||
dedupIdentityStore.delete(storageKey);
|
||||
}
|
||||
// Wake parked ReceiveMessage long polls so they observe the deletion
|
||||
// and finish, instead of staying registered against this queue URL.
|
||||
// Left alone they would survive a delete + recreate under the same URL
|
||||
@@ -700,52 +809,86 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
// Use NUL as the delimiter — it is outside the SQS-allowed character set for
|
||||
// MessageGroupId/MessageDeduplicationId, so the composite key is unambiguous.
|
||||
String dedupCacheKey = groupScoped ? messageGroupId + "\0" + dedupId : dedupId;
|
||||
cleanupDeduplicationCache(storageKey);
|
||||
ConcurrentHashMap<String, Instant> dedupMap = deduplicationCache.computeIfAbsent(storageKey, k -> new ConcurrentHashMap<>());
|
||||
Instant expiry = Instant.now().plusSeconds(DEDUP_WINDOW_SECONDS);
|
||||
Instant previous = dedupMap.putIfAbsent(dedupCacheKey, expiry);
|
||||
persistDedup(storageKey);
|
||||
if (previous != null && Instant.now().isBefore(previous)) {
|
||||
// Duplicate within window — keep the original messageId and
|
||||
// sequenceNumber but compute response MD5s from this request's
|
||||
// body and attributes, otherwise SDK clients (which validate
|
||||
// MD5 against what they sent) reject the response.
|
||||
Message existing = getOrCreateQueue(storageKey).findByDeduplicationId(
|
||||
dedupId, groupScoped ? messageGroupId : null);
|
||||
if (existing != null) {
|
||||
cleanupDeduplicationCache(storageKey);
|
||||
synchronized (deduplicationLock(storageKey, dedupCacheKey)) {
|
||||
Instant now = clock.instant();
|
||||
Instant expiry = now.plusSeconds(DEDUP_WINDOW_SECONDS);
|
||||
Instant previous = dedupMap.putIfAbsent(dedupCacheKey, expiry);
|
||||
if (previous != null && !now.isBefore(previous)) {
|
||||
dedupMap.replace(dedupCacheKey, previous, expiry);
|
||||
ConcurrentHashMap<String, DeduplicationIdentity> identities =
|
||||
deduplicationIdentityCache.get(storageKey);
|
||||
if (identities != null) {
|
||||
identities.remove(dedupCacheKey);
|
||||
}
|
||||
previous = null;
|
||||
}
|
||||
if (previous != null && now.isBefore(previous)) {
|
||||
// Duplicate within window — keep the original messageId and
|
||||
// sequenceNumber but compute response MD5s from this request's
|
||||
// body and attributes, otherwise SDK clients (which validate
|
||||
// MD5 against what they sent) reject the response.
|
||||
ConcurrentHashMap<String, DeduplicationIdentity> identities =
|
||||
deduplicationIdentityCache.get(storageKey);
|
||||
DeduplicationIdentity identity = identities == null ? null : identities.get(dedupCacheKey);
|
||||
if (identity == null) {
|
||||
Message existing = getOrCreateQueue(storageKey).findByDeduplicationId(
|
||||
dedupId, groupScoped ? messageGroupId : null);
|
||||
if (existing != null) {
|
||||
identity = new DeduplicationIdentity(
|
||||
existing.getMessageId(), existing.getSequenceNumber());
|
||||
deduplicationIdentityCache.computeIfAbsent(storageKey, k -> new ConcurrentHashMap<>())
|
||||
.putIfAbsent(dedupCacheKey, identity);
|
||||
persistDedupIdentities(storageKey);
|
||||
}
|
||||
}
|
||||
// The original message may have been received and deleted, but SQS
|
||||
// continues tracking the deduplication ID for the full interval.
|
||||
// Return the original identity without re-enqueueing a message.
|
||||
Message response = new Message(body);
|
||||
response.setMessageId(existing.getMessageId());
|
||||
if (identity != null) {
|
||||
response.setMessageId(identity.messageId());
|
||||
response.setSequenceNumber(identity.sequenceNumber());
|
||||
} else {
|
||||
response.setSequenceNumber(sequenceCounter.incrementAndGet());
|
||||
}
|
||||
response.setMessageGroupId(messageGroupId);
|
||||
response.setMessageDeduplicationId(dedupId);
|
||||
response.setSequenceNumber(existing.getSequenceNumber());
|
||||
if (messageAttributes != null && !messageAttributes.isEmpty()) {
|
||||
response.getMessageAttributes().putAll(messageAttributes);
|
||||
response.updateMd5OfMessageAttributes();
|
||||
}
|
||||
return response;
|
||||
}
|
||||
}
|
||||
|
||||
Message message = new Message(body);
|
||||
message.setMessageGroupId(messageGroupId);
|
||||
message.setMessageDeduplicationId(dedupId);
|
||||
message.setSequenceNumber(sequenceCounter.incrementAndGet());
|
||||
message.setAwsTraceHeader(awsTraceHeader);
|
||||
if (effectiveDelaySeconds > 0) {
|
||||
message.setVisibleAt(Instant.now().plusSeconds(effectiveDelaySeconds));
|
||||
}
|
||||
if (messageAttributes != null && !messageAttributes.isEmpty()) {
|
||||
message.getMessageAttributes().putAll(messageAttributes);
|
||||
message.updateMd5OfMessageAttributes();
|
||||
}
|
||||
persistDedup(storageKey);
|
||||
|
||||
getOrCreateQueue(storageKey).addMessage(message);
|
||||
notifyReceivers(storageKey);
|
||||
LOG.debugv("Sent FIFO message {0} to queue {1}, group={2}, seq={3}",
|
||||
message.getMessageId(), queueUrl, messageGroupId, message.getSequenceNumber());
|
||||
LOG.tracev("Sent message {0} to queue {1} body={2} attributes={3}",
|
||||
message.getMessageId(), queueUrl, body, message.getMessageAttributes());
|
||||
return message;
|
||||
Message message = new Message(body);
|
||||
message.setMessageGroupId(messageGroupId);
|
||||
message.setMessageDeduplicationId(dedupId);
|
||||
message.setSequenceNumber(sequenceCounter.incrementAndGet());
|
||||
message.setAwsTraceHeader(awsTraceHeader);
|
||||
if (effectiveDelaySeconds > 0) {
|
||||
message.setVisibleAt(Instant.now().plusSeconds(effectiveDelaySeconds));
|
||||
}
|
||||
if (messageAttributes != null && !messageAttributes.isEmpty()) {
|
||||
message.getMessageAttributes().putAll(messageAttributes);
|
||||
message.updateMd5OfMessageAttributes();
|
||||
}
|
||||
|
||||
getOrCreateQueue(storageKey).addMessage(message);
|
||||
deduplicationIdentityCache.computeIfAbsent(storageKey, k -> new ConcurrentHashMap<>())
|
||||
.putIfAbsent(dedupCacheKey,
|
||||
new DeduplicationIdentity(message.getMessageId(), message.getSequenceNumber()));
|
||||
persistDedupIdentities(storageKey);
|
||||
notifyReceivers(storageKey);
|
||||
LOG.debugv("Sent FIFO message {0} to queue {1}, group={2}, seq={3}",
|
||||
message.getMessageId(), queueUrl, messageGroupId, message.getSequenceNumber());
|
||||
LOG.tracev("Sent message {0} to queue {1} body={2} attributes={3}",
|
||||
message.getMessageId(), queueUrl, body, message.getMessageAttributes());
|
||||
return message;
|
||||
}
|
||||
}
|
||||
|
||||
// Standard queue. MessageGroupId is retained for ReceiveMessage to
|
||||
@@ -882,8 +1025,28 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
private void cleanupDeduplicationCache(String queueUrl) {
|
||||
ConcurrentHashMap<String, Instant> dedupMap = deduplicationCache.get(queueUrl);
|
||||
if (dedupMap != null) {
|
||||
Instant now = Instant.now();
|
||||
dedupMap.entrySet().removeIf(e -> now.isAfter(e.getValue()));
|
||||
Instant now = clock.instant();
|
||||
Set<String> expiredKeys = dedupMap.entrySet().stream()
|
||||
.filter(e -> !now.isBefore(e.getValue()))
|
||||
.map(Map.Entry::getKey)
|
||||
.collect(Collectors.toSet());
|
||||
boolean removed = false;
|
||||
for (String key : expiredKeys) {
|
||||
synchronized (deduplicationLock(queueUrl, key)) {
|
||||
Instant expiry = dedupMap.get(key);
|
||||
if (expiry != null && !now.isBefore(expiry) && dedupMap.remove(key, expiry)) {
|
||||
ConcurrentHashMap<String, DeduplicationIdentity> identityMap =
|
||||
deduplicationIdentityCache.get(queueUrl);
|
||||
if (identityMap != null) {
|
||||
identityMap.remove(key);
|
||||
}
|
||||
removed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (removed) {
|
||||
persistDedupIdentities(queueUrl);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1085,9 +1248,14 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
getOrCreateQueue(storageKey).purge();
|
||||
if (clearFifoDeduplicationCacheOnPurge) {
|
||||
deduplicationCache.remove(storageKey);
|
||||
deduplicationIdentityCache.remove(storageKey);
|
||||
deduplicationLocks.remove(storageKey);
|
||||
if (dedupStore != null) {
|
||||
dedupStore.delete(storageKey);
|
||||
}
|
||||
if (dedupIdentityStore != null) {
|
||||
dedupIdentityStore.delete(storageKey);
|
||||
}
|
||||
if (snsService != null) {
|
||||
snsService.clearFifoDeduplicationCacheForSqsQueueSubscriptions(queueUrl, region);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user