fix(sns): honor FifoThroughputScope=MessageGroup on FIFO topics (#3181)

* fix(sns): honor FifoThroughputScope=MessageGroup on FIFO topics

A FIFO topic accepted FifoThroughputScope and echoed it back from
GetTopicAttributes, but deduplication stayed topic-wide, so the same
MessageDeduplicationId published under two different MessageGroupIds
delivered only the first message. A fan-out that reuses one dedup id per
group silently lost every message after the first.

Scope the deduplication cache key to the message group when the topic
sets FifoThroughputScope=MessageGroup, on both Publish and PublishBatch,
mirroring how SQS handles DeduplicationScope=messageGroup. Topic remains
the default and keeps the existing topic-wide behavior.

* fix(cloudformation): forward SNS FifoThroughputScope from AWS::SNS::Topic

SnsCfnProvisioner only forwarded ContentBasedDeduplication, so a topic
provisioned from a template kept the default topic-wide deduplication
even with FifoThroughputScope set, and a FIFO topic left unnamed got a
generated name without the .fifo suffix SnsService recognizes.

Forward FifoThroughputScope, suffix a generated FIFO topic name with
.fifo as CloudFormation does, treat a prior name whose suffix no longer
matches the createOnly FifoTopic flag as a replacing update, and rewrite
the mutable attributes on UpdateStack, which createTopic leaves untouched
when the topic already exists.

* fix(cloudformation): reset dropped SNS topic attributes on update

An UpdateStack that dropped FifoThroughputScope or
ContentBasedDeduplication kept the old value while reporting success.
Write the create-time default instead, for FIFO topics only: real SNS
rejects both on a standard topic.

A FifoTopic flip now fails rather than replacing the topic under a new
generated name, which would orphan it and its subscriptions. An
explicitly named .fifo topic counts as FIFO without the flag.

* fix(sns): make the group-scoped FIFO dedup key unambiguous

Nothing validates the characters in either id, so the NUL delimiter
could arrive inside one and make two different group and dedup pairs
share a cache key. Length-prefix the group instead.

* fix(sns): keep FIFO dedup scopes in separate cache namespaces

A topic-scoped dedup id shaped like the group-scoped key, "1#ab" for
group "a" with id "b", hit the same cache entry once the scope changed
inside the deduplication window. Mark each key with its scope so the
two formats cannot collide.
This commit is contained in:
lyrray authored and GitHub committed 2026-09-07 11:52:20 -05:00
1 parent 0cff3156ec
commit a1d0597ffe
6 files changed
+570 -9

No files matched your search

+29
View File
@@ -88,6 +88,35 @@ Supported subscription protocols:
- `http` / `https` — posts to an HTTP endpoint
- `application` — fans out to a mobile push platform endpoint (see [Mobile push](#mobile-push-mock))
## FIFO topics
A topic whose name ends in `.fifo` is a FIFO topic. `Publish` and `PublishBatch` require a
`MessageGroupId`, and a message is deduplicated against its `MessageDeduplicationId` for five
minutes. Set `ContentBasedDeduplication` on the topic to derive that id from the message body.
The `FifoThroughputScope` attribute decides how wide that deduplication reaches:
| Value | Deduplication scope |
|---|---|
| `Topic` (default) | Across the whole topic: the same `MessageDeduplicationId` is a duplicate no matter which message group it arrives under |
| `MessageGroup` | Within a single message group: the same `MessageDeduplicationId` under two different `MessageGroupId`s is two distinct messages |
`MessageGroup` is what a fan-out that reuses one deduplication id per group needs, for example
publishing the same event to a topic once per tenant with the tenant as the message group.
```bash
aws sns create-topic --name events.fifo \
--attributes FifoTopic=true,FifoThroughputScope=MessageGroup \
--endpoint-url $AWS_ENDPOINT_URL
```
When the topic forwards to an SQS FIFO queue, set the matching queue attributes
(`DeduplicationScope=messageGroup` and `FifoThroughputLimit=perMessageGroupId`), otherwise the
queue deduplicates topic-wide on the way in.
CloudFormation carries both settings through: `AWS::SNS::Topic` forwards `FifoThroughputScope` and
`ContentBasedDeduplication`, and a FIFO topic left unnamed gets a generated name ending in `.fifo`.
## Control Tower managed topic
AWS Control Tower creates the regional
@@ -20,6 +20,7 @@ public class SnsCfnProvisioner implements CfnResourceProvisioner {
private static final String SUBSCRIPTION = "AWS::SNS::Subscription";
private static final String TOPIC_POLICY = "AWS::SNS::TopicPolicy";
private static final int TOPIC_NAME_MAX_LENGTH = 256;
private static final String FIFO_SUFFIX = ".fifo";
private final SnsService snsService;
@@ -46,22 +47,55 @@ public class SnsCfnProvisioner implements CfnResourceProvisioner {
private void provisionTopic(StackResource r, JsonNode props, ProvisionContext ctx) {
String topicName = ctx.resolveOptional(props, "TopicName");
String contentBasedDedupFlag = ctx.resolveOptional(props, "ContentBasedDeduplication");
String throughputScope = ctx.resolveOptional(props, "FifoThroughputScope");
// The .fifo suffix is what makes SnsService treat a topic as FIFO, so an explicitly named
// one is FIFO with or without the flag, which only has to steer a generated name.
boolean fifo = "true".equalsIgnoreCase(ctx.resolveOptional(props, "FifoTopic"))
|| (topicName != null && topicName.endsWith(FIFO_SUFFIX));
String priorName = r.getAttributes().get("TopicName");
// FifoTopic is createOnly and carried by the name, so a flip needs a replacement. Nothing
// cleans up the displaced topic or its subscriptions, so refuse it, as SqsCfnProvisioner
// does for FifoQueue.
if (ctx.isUpdate() && priorName != null && !priorName.isBlank()
&& priorName.endsWith(FIFO_SUFFIX) != fifo) {
throw new AwsException("ValidationError",
"Updating FifoTopic requires resource replacement, which is not supported.", 400);
}
if (topicName == null || topicName.isBlank()) {
// ctx.stablePhysicalName does not fit here: the physical id is the topic ARN, so the
// prior name comes from the attribute recorded at create time. Reusing it keeps an
// unnamed topic (and its subscriptions) across updates instead of orphaning it.
String priorName = r.getAttributes().get("TopicName");
topicName = priorName != null && !priorName.isBlank()
? priorName
: ctx.generatePhysicalName(r.getLogicalId(), TOPIC_NAME_MAX_LENGTH, false);
if (priorName != null && !priorName.isBlank()) {
topicName = priorName;
} else if (fifo) {
// Like real CloudFormation, a generated FIFO name ends in .fifo.
topicName = ctx.generatePhysicalName(r.getLogicalId(),
TOPIC_NAME_MAX_LENGTH - FIFO_SUFFIX.length(), false) + FIFO_SUFFIX;
} else {
topicName = ctx.generatePhysicalName(r.getLogicalId(), TOPIC_NAME_MAX_LENGTH, false);
}
}
Map<String, String> attributes = new HashMap<>();
if (contentBasedDedupFlag != null && !contentBasedDedupFlag.isBlank()) {
attributes.put("ContentBasedDeduplication", contentBasedDedupFlag);
}
if (throughputScope != null && !throughputScope.isBlank()) {
attributes.put("FifoThroughputScope", throughputScope);
}
var topic = snsService.createTopic(topicName, attributes, Map.of(), ctx.region());
// createTopic leaves an existing topic untouched, so an update writes the mutable
// attributes itself. A property the template dropped is reset, not left standing.
if (ctx.isUpdate()) {
Map<String, String> desired = new HashMap<>(attributes);
if (fifo) {
desired.putIfAbsent("ContentBasedDeduplication", "false");
desired.putIfAbsent("FifoThroughputScope", "Topic");
}
desired.forEach((name, value) ->
snsService.setTopicAttributes(topic.getTopicArn(), name, value, ctx.region()));
}
// Ref returns the topic ARN, which is why the physical id is the ARN and not the name.
r.setPhysicalId(topic.getTopicArn());
// TopicArn is the attribute aws-sns-topic.json declares read-only. Arn is kept alongside it
@@ -435,7 +435,8 @@ public class SnsService implements Resettable, ResourceProvider {
if (dedupId == null && "true".equals(topic.getAttributes().get("ContentBasedDeduplication"))) {
dedupId = sha256(message);
}
if (dedupId != null && isDuplicate(effectiveArn, dedupId)) {
if (dedupId != null && isDuplicate(effectiveArn, messageGroupId, dedupId,
isGroupScopedDeduplication(topic))) {
LOG.debugv("FIFO dedup: skipping duplicate for topic {0}, dedupId {1}", effectiveArn, dedupId);
return UUID.randomUUID().toString();
}
@@ -841,6 +842,7 @@ public class SnsService implements Resettable, ResourceProvider {
}
boolean isFifo = "true".equals(topic.getAttributes().get("FifoTopic"));
boolean groupScopedDedup = isGroupScopedDeduplication(topic);
List<String[]> successful = new ArrayList<>();
List<String[]> failed = new ArrayList<>();
for (Map<String, Object> entry : entries) {
@@ -871,7 +873,8 @@ public class SnsService implements Resettable, ResourceProvider {
if (isFifo && messageDeduplicationId == null && "true".equals(topic.getAttributes().get("ContentBasedDeduplication"))) {
messageDeduplicationId = sha256(message);
}
if (isFifo && messageDeduplicationId != null && isDuplicate(topicArn, messageDeduplicationId)) {
if (isFifo && messageDeduplicationId != null && isDuplicate(topicArn, messageGroupId,
messageDeduplicationId, groupScopedDedup)) {
successful.add(new String[]{id, UUID.randomUUID().toString()});
continue;
}
@@ -1252,8 +1255,23 @@ public class SnsService implements Resettable, ResourceProvider {
return true;
}
private boolean isDuplicate(String topicArn, String deduplicationId) {
String cacheKey = topicArn + ":" + deduplicationId;
/**
* {@code MessageGroup} narrows deduplication to a single message group. {@code Topic}, the AWS
* default, keeps it topic-wide.
*/
private static boolean isGroupScopedDeduplication(Topic topic) {
return "MessageGroup".equalsIgnoreCase(topic.getAttributes().get("FifoThroughputScope"));
}
private boolean isDuplicate(String topicArn, String messageGroupId, String deduplicationId,
boolean groupScoped) {
// The scope is part of the key: the attribute can change inside the deduplication window,
// and a topic-scoped id must never land on a group-scoped entry. The group is
// length-prefixed because nothing validates the characters in either id.
String scopedId = groupScoped
? "group:" + messageGroupId.length() + ":" + messageGroupId + deduplicationId
: "topic:" + deduplicationId;
String cacheKey = topicArn + ":" + scopedId;
Instant now = Instant.now();
Instant existing = fifoDeduplicationCache.get(cacheKey);
if (existing != null && existing.plus(FIFO_DEDUP_WINDOW).isAfter(now)) {
@@ -0,0 +1,208 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* A FIFO topic fanning out to a FIFO queue, the shape a template takes to publish one event per
* message group: the scope reaches the topic, per-group dedup holds end to end, and an UpdateStack
* back to {@code Topic} takes effect on the topic that already exists.
*/
@QuarkusTest
class SnsFifoThroughputScopeCfnIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/cloudformation/aws4_request";
private static final String SNS_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/sns/aws4_request";
private static final String SQS_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/sqs/aws4_request";
private static final String STACK = "sns-fifo-scope-cfn-it";
/** Per-group dedup on the queue too, so its own topic-wide window cannot mask the topic's. */
private static final String TEMPLATE = """
{
"Parameters": {"Scope": {"Type": "String"}},
"Resources": {
"Topic": {
"Type": "AWS::SNS::Topic",
"Properties": {
"TopicName": "sns-fifo-scope-cfn-it.fifo",
"FifoTopic": true,
"ContentBasedDeduplication": false,
"FifoThroughputScope": {"Ref": "Scope"}
}
},
"Queue": {
"Type": "AWS::SQS::Queue",
"Properties": {
"QueueName": "sns-fifo-scope-cfn-it.fifo",
"FifoQueue": true,
"DeduplicationScope": "messageGroup",
"FifoThroughputLimit": "perMessageGroupId"
}
},
"Subscription": {
"Type": "AWS::SNS::Subscription",
"Properties": {
"TopicArn": {"Ref": "Topic"},
"Protocol": "sqs",
"Endpoint": {"Fn::GetAtt": ["Queue", "Arn"]},
"RawMessageDelivery": true
}
}
},
"Outputs": {
"TopicArn": {"Value": {"Ref": "Topic"}},
"QueueUrl": {"Value": {"Ref": "Queue"}}
}
}
""";
@Test
void aTemplateAskingForPerGroupDeduplicationGetsIt() throws InterruptedException {
cloudFormation("CreateStack", "MessageGroup");
String created = describeStacks("CREATE_COMPLETE");
String topicArn = outputValue(created, "TopicArn");
String queueUrl = outputValue(created, "QueueUrl");
assertEquals("MessageGroup", topicAttribute(topicArn, "FifoThroughputScope"),
"the template's FifoThroughputScope has to reach the topic");
// One deduplication id, two message groups. Under MessageGroup scope they are two messages.
publish(topicArn, "group-1", "per-group-dedup", "per-group-one");
publish(topicArn, "group-2", "per-group-dedup", "per-group-two");
String perGroup = drain(queueUrl);
assertTrue(perGroup.contains("per-group-one"), perGroup);
assertTrue(perGroup.contains("per-group-two"),
"the second group's message was deduplicated against the first: " + perGroup);
// A received message stays in flight and holds its group, so clear the queue first.
purgeQueue(queueUrl);
cloudFormation("UpdateStack", "Topic");
describeStacks("UPDATE_COMPLETE");
assertEquals("Topic", topicAttribute(topicArn, "FifoThroughputScope"),
"createTopic hands an existing topic back untouched, so an update has to rewrite it");
// The same pair against the AWS default scope: the second publish is a topic-wide duplicate.
publish(topicArn, "group-1", "topic-wide-dedup", "topic-scope-one");
publish(topicArn, "group-2", "topic-wide-dedup", "topic-scope-two");
String topicWide = drain(queueUrl);
assertTrue(topicWide.contains("topic-scope-one"), topicWide);
assertFalse(topicWide.contains("topic-scope-two"),
"Topic scope must keep deduplicating across groups: " + topicWide);
cloudFormation("DeleteStack", null);
awaitStackDeleted();
topicAttributes(topicArn).statusCode(404);
}
private static void cloudFormation(String action, String scope) {
RequestSpecification request = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", action)
.formParam("StackName", STACK);
if (scope != null) {
request.formParam("TemplateBody", TEMPLATE)
.formParam("Parameters.member.1.ParameterKey", "Scope")
.formParam("Parameters.member.1.ParameterValue", scope);
}
request.when().post("/").then().statusCode(200);
}
private static String describeStacks(String expectedStatus) {
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", STACK)
.when().post("/").then().statusCode(200)
.body(org.hamcrest.Matchers.containsString("<StackStatus>" + expectedStatus + "</StackStatus>"))
.extract().asString();
}
/** DeleteStack runs asynchronously; a successful delete removes the stack entirely. */
private static void awaitStackDeleted() throws InterruptedException {
for (int i = 0; i < 100; i++) {
String body = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", STACK)
.when().post("/").then().extract().asString();
if (body.contains("does not exist")) {
return;
}
if (body.contains("<StackStatus>DELETE_FAILED</StackStatus>")) {
fail("stack delete failed: " + body);
}
Thread.sleep(50);
}
fail("stack " + STACK + " was not deleted within the timeout");
}
private static String outputValue(String xml, String key) {
return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
}
private static ValidatableResponse topicAttributes(String topicArn) {
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", SNS_AUTH)
.formParam("Action", "GetTopicAttributes")
.formParam("TopicArn", topicArn)
.when().post("/").then();
}
private static String topicAttribute(String topicArn, String name) {
String xml = topicAttributes(topicArn).statusCode(200).extract().asString();
return XmlParser.extractPairs(xml, "entry", "key", "value").get(name);
}
private static void publish(String topicArn, String groupId, String dedupId, String message) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", SNS_AUTH)
.formParam("Action", "Publish")
.formParam("TopicArn", topicArn)
.formParam("Message", message)
.formParam("MessageGroupId", groupId)
.formParam("MessageDeduplicationId", dedupId)
.when().post("/").then().statusCode(200);
}
/** A FIFO receive can return one group at a time, so read repeatedly. */
private static String drain(String queueUrl) {
StringBuilder received = new StringBuilder();
for (int i = 0; i < 6; i++) {
received.append(given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", SQS_AUTH)
.formParam("Action", "ReceiveMessage")
.formParam("QueueUrl", queueUrl)
.formParam("MaxNumberOfMessages", "10")
.when().post("/").then().statusCode(200).extract().asString());
}
return received.toString();
}
private static void purgeQueue(String queueUrl) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", SQS_AUTH)
.formParam("Action", "PurgeQueue")
.formParam("QueueUrl", queueUrl)
.when().post("/").then().statusCode(200);
}
}
@@ -168,6 +168,140 @@ class SnsCfnProvisionerTest {
"an absent flag must not be sent as an empty attribute");
}
@Test
void fifoThroughputScopeIsForwardedOnlyWhenSet() {
ArgumentCaptor<Map<String, String>> attrs = ArgumentCaptor.forClass(Map.class);
when(sns.createTopic(anyString(), attrs.capture(), anyMap(), anyString())).thenReturn(topic(TOPIC_ARN));
provision("AWS::SNS::Topic", """
{"TopicName": "events.fifo", "FifoTopic": true, "FifoThroughputScope": "MessageGroup"}
""");
assertEquals("MessageGroup", attrs.getValue().get("FifoThroughputScope"));
verify(sns, never()).setTopicAttributes(anyString(), anyString(), anyString(), anyString());
setUp();
ArgumentCaptor<Map<String, String>> plain = ArgumentCaptor.forClass(Map.class);
when(sns.createTopic(anyString(), plain.capture(), anyMap(), anyString())).thenReturn(topic(TOPIC_ARN));
provision("AWS::SNS::Topic", """
{"TopicName": "events.fifo", "FifoTopic": true}
""");
assertFalse(plain.getValue().containsKey("FifoThroughputScope"),
"an absent scope must not be sent as an empty attribute");
}
@Test
void anUnnamedFifoTopicGetsAGeneratedNameEndingInFifo() {
ArgumentCaptor<String> name = ArgumentCaptor.forClass(String.class);
when(sns.createTopic(name.capture(), anyMap(), anyMap(), anyString())).thenReturn(topic(TOPIC_ARN));
provision("AWS::SNS::Topic", """
{"FifoTopic": true, "FifoThroughputScope": "MessageGroup"}
""");
assertTrue(name.getValue().startsWith("my-stack-Topic-"));
assertTrue(name.getValue().endsWith(".fifo"),
"SnsService reads FifoTopic off the name, so a generated one must carry the suffix");
setUp();
ArgumentCaptor<String> standard = ArgumentCaptor.forClass(String.class);
when(sns.createTopic(standard.capture(), anyMap(), anyMap(), anyString())).thenReturn(topic(TOPIC_ARN));
provision("AWS::SNS::Topic", "{}");
assertFalse(standard.getValue().endsWith(".fifo"),
"a standard topic must not be renamed into a FIFO one");
}
/**
* Replacing would displace a topic nothing cleans up, subscriptions included, so it is refused.
*/
@Test
void aTopicTurningFifoIsRejectedRatherThanReplaced() {
StackResource r = new StackResource();
r.setLogicalId("Topic");
r.setResourceType("AWS::SNS::Topic");
r.setAttributes(new HashMap<>(Map.of("TopicName", "my-stack-Topic-abc123def456")));
r.setPhysicalId(TOPIC_ARN);
ProvisionContext update =
new ProvisionContext(ctx.engine(), REGION, "000000000000", "my-stack", TOPIC_ARN);
JsonNode turningFifo = props("""
{"FifoTopic": true}
""");
AwsException e = assertThrows(AwsException.class,
() -> provisioner.provision(r, turningFifo, update));
assertEquals("ValidationError", e.getErrorCode());
assertTrue(e.getMessage().contains("requires resource replacement"), e.getMessage());
verify(sns, never()).createTopic(anyString(), anyMap(), anyMap(), anyString());
}
/** The suffix carries FifoTopic on its own, so this is the same topic, not a mode change. */
@Test
void anExplicitlyNamedFifoTopicUpdatesWithoutTheFlag() {
when(sns.createTopic(eq("events.fifo"), anyMap(), anyMap(), eq(REGION))).thenReturn(topic(TOPIC_ARN));
provisionUpdate("""
{"TopicName": "events.fifo"}
""");
verify(sns).createTopic(eq("events.fifo"), anyMap(), anyMap(), eq(REGION));
}
@Test
void anUpdateThatDropsAPropertyResetsItToItsDefault() {
when(sns.createTopic(eq("events.fifo"), anyMap(), anyMap(), eq(REGION))).thenReturn(topic(TOPIC_ARN));
// The template dropped both properties, so both go back to their create-time values.
provisionUpdate("""
{"TopicName": "events.fifo", "FifoTopic": true}
""");
verify(sns).setTopicAttributes(TOPIC_ARN, "FifoThroughputScope", "Topic", REGION);
verify(sns).setTopicAttributes(TOPIC_ARN, "ContentBasedDeduplication", "false", REGION);
}
/** Real SNS rejects both attributes on a standard topic, so an update must not invent them. */
@Test
void aStandardTopicUpdateWritesNoFifoDefaults() {
when(sns.createTopic(eq("events"), anyMap(), anyMap(), eq(REGION))).thenReturn(topic(TOPIC_ARN));
provisionUpdate("""
{"TopicName": "events"}
""");
verify(sns, never()).setTopicAttributes(anyString(), anyString(), anyString(), anyString());
}
/** Provisions an existing topic again, the way UpdateStack re-invokes the provisioner. */
private void provisionUpdate(String json) {
StackResource r = new StackResource();
r.setLogicalId("Topic");
r.setResourceType("AWS::SNS::Topic");
JsonNode resolved = props(json);
String priorName = resolved.path("TopicName").asText(null);
r.setAttributes(new HashMap<>(Map.of("TopicName", priorName)));
r.setPhysicalId(TOPIC_ARN);
provisioner.provision(r, resolved,
new ProvisionContext(ctx.engine(), REGION, "000000000000", "my-stack", TOPIC_ARN));
}
@Test
void mutableTopicAttributesAreWrittenOnUpdate() {
when(sns.createTopic(eq("events.fifo"), anyMap(), anyMap(), eq(REGION))).thenReturn(topic(TOPIC_ARN));
StackResource r = new StackResource();
r.setLogicalId("Topic");
r.setResourceType("AWS::SNS::Topic");
r.setAttributes(new HashMap<>(Map.of("TopicName", "events.fifo")));
r.setPhysicalId(TOPIC_ARN);
provisioner.provision(r, props("""
{"TopicName": "events.fifo", "FifoTopic": true, "FifoThroughputScope": "MessageGroup",
"ContentBasedDeduplication": "true"}
"""), new ProvisionContext(ctx.engine(), REGION, "000000000000", "my-stack", TOPIC_ARN));
// createTopic returns the existing topic, so without this a changed scope would be lost.
verify(sns).setTopicAttributes(TOPIC_ARN, "FifoThroughputScope", "MessageGroup", REGION);
verify(sns).setTopicAttributes(TOPIC_ARN, "ContentBasedDeduplication", "true", REGION);
}
@Test
void subscriptionRefIsTheSubscriptionArn() {
when(sns.subscribe(eq(TOPIC_ARN), eq("sqs"), eq("arn:queue"), eq(REGION), anyMap()))
@@ -15,7 +15,8 @@ import static org.junit.jupiter.api.Assertions.*;
/**
* Tests that SNS FIFO topic delivery correctly passes messageDeduplicationId
* through to subscribed SQS FIFO queues.
* through to subscribed SQS FIFO queues, and that the topic's FifoThroughputScope
* decides whether deduplication is topic-wide or per message group.
*/
class SnsSqsFanoutFifoDeliveryTest {
@@ -165,6 +166,143 @@ class SnsSqsFanoutFifoDeliveryTest {
assertTrue(messages.get(0).getBody().contains("first"));
}
@Test
void publish_withDefaultThroughputScope_dedupsAcrossMessageGroups() {
// Arrange: no FifoThroughputScope, so the AWS default (Topic) applies
String queueUrl = createGroupScopedQueue("fifo-topic-scope-queue.fifo");
String topicArn = createFifoTopic("fifo-topic-scope-topic.fifo", Map.of("FifoTopic", "true"),
"fifo-topic-scope-queue.fifo");
// Act: same dedup ID under two different message groups
snsService.publish(topicArn, null, null, "group-one", null, null, "group-1", "shared-dedup", REGION);
snsService.publish(topicArn, null, null, "group-two", null, null, "group-2", "shared-dedup", REGION);
// Assert: deduplication is topic-wide, so the second publish is swallowed
List<Message> messages = sqsService.receiveMessage(queueUrl, 10, 30, 0, REGION);
assertEquals(1, messages.size());
assertTrue(messages.getFirst().getBody().contains("group-one"));
}
@Test
void publish_withMessageGroupThroughputScope_deliversSameDedupIdInDifferentGroups() {
// Arrange
String queueUrl = createGroupScopedQueue("fifo-group-scope-queue.fifo");
String topicArn = createFifoTopic("fifo-group-scope-topic.fifo",
Map.of("FifoTopic", "true", "FifoThroughputScope", "MessageGroup"),
"fifo-group-scope-queue.fifo");
// Act: same dedup ID under two different message groups
snsService.publish(topicArn, null, null, "group-one", null, null, "group-1", "shared-dedup", REGION);
snsService.publish(topicArn, null, null, "group-two", null, null, "group-2", "shared-dedup", REGION);
// Assert: deduplication is scoped per group, so both are distinct messages
List<Message> messages = sqsService.receiveMessage(queueUrl, 10, 30, 0, REGION);
assertEquals(2, messages.size());
List<String> bodies = messages.stream().map(Message::getBody).toList();
assertTrue(bodies.stream().anyMatch(b -> b.contains("group-one")));
assertTrue(bodies.stream().anyMatch(b -> b.contains("group-two")));
}
@Test
void publish_withMessageGroupThroughputScope_stillDedupsWithinOneGroup() {
// Arrange
String queueUrl = createGroupScopedQueue("fifo-group-scope-dup-queue.fifo");
String topicArn = createFifoTopic("fifo-group-scope-dup-topic.fifo",
Map.of("FifoTopic", "true", "FifoThroughputScope", "MessageGroup"),
"fifo-group-scope-dup-queue.fifo");
// Act: same dedup ID twice under the same message group
snsService.publish(topicArn, null, null, "first", null, null, "group-1", "shared-dedup", REGION);
snsService.publish(topicArn, null, null, "second", null, null, "group-1", "shared-dedup", REGION);
// Assert: narrowing the scope must not disable deduplication inside a group
List<Message> messages = sqsService.receiveMessage(queueUrl, 10, 30, 0, REGION);
assertEquals(1, messages.size());
assertTrue(messages.getFirst().getBody().contains("first"));
}
@Test
void publish_withMessageGroupThroughputScope_isCaseInsensitive() {
// Arrange
String queueUrl = createGroupScopedQueue("fifo-group-scope-case-queue.fifo");
String topicArn = createFifoTopic("fifo-group-scope-case-topic.fifo",
Map.of("FifoTopic", "true", "FifoThroughputScope", "messagegroup"),
"fifo-group-scope-case-queue.fifo");
// Act
snsService.publish(topicArn, null, null, "group-one", null, null, "group-1", "shared-dedup", REGION);
snsService.publish(topicArn, null, null, "group-two", null, null, "group-2", "shared-dedup", REGION);
// Assert
assertEquals(2, sqsService.receiveMessage(queueUrl, 10, 30, 0, REGION).size());
}
@Test
void publish_afterThroughputScopeChanges_doesNotHitTheOtherScopesCacheEntry() {
// Arrange
String queueUrl = createGroupScopedQueue("fifo-scope-switch-queue.fifo");
String topicArn = createFifoTopic("fifo-scope-switch-topic.fifo",
Map.of("FifoTopic", "true", "FifoThroughputScope", "MessageGroup"),
"fifo-scope-switch-queue.fifo");
// Act: publish group-scoped, then again topic-scoped with a dedup id shaped like the
// group-scoped key, inside the deduplication window.
snsService.publish(topicArn, null, null, "group-scoped", null, null, "a", "b", REGION);
snsService.setTopicAttributes(topicArn, "FifoThroughputScope", "Topic", REGION);
snsService.publish(topicArn, null, null, "topic-scoped", null, null, "z", "1#ab", REGION);
// Assert: the two scopes keep separate cache namespaces, so neither suppresses the other.
List<Message> messages = sqsService.receiveMessage(queueUrl, 10, 30, 0, REGION);
assertEquals(2, messages.size());
List<String> bodies = messages.stream().map(Message::getBody).toList();
assertTrue(bodies.stream().anyMatch(b -> b.contains("group-scoped")));
assertTrue(bodies.stream().anyMatch(b -> b.contains("topic-scoped")));
}
@Test
void publishBatch_withMessageGroupThroughputScope_deliversSameDedupIdInDifferentGroups() {
// Arrange
String queueUrl = createGroupScopedQueue("fifo-batch-group-scope-queue.fifo");
String topicArn = createFifoTopic("fifo-batch-group-scope-topic.fifo",
Map.of("FifoTopic", "true", "FifoThroughputScope", "MessageGroup"),
"fifo-batch-group-scope-queue.fifo");
// Act: one batch, same dedup ID under two different message groups
var entries = List.<Map<String, Object>>of(
Map.of("Id", "e1", "Message", "batch-group-one",
"MessageGroupId", "group-1", "MessageDeduplicationId", "shared-dedup"),
Map.of("Id", "e2", "Message", "batch-group-two",
"MessageGroupId", "group-2", "MessageDeduplicationId", "shared-dedup")
);
var result = snsService.publishBatch(topicArn, entries, REGION);
// Assert
assertEquals(2, result.successful().size());
assertEquals(0, result.failed().size());
List<Message> messages = sqsService.receiveMessage(queueUrl, 10, 30, 0, REGION);
assertEquals(2, messages.size());
List<String> bodies = messages.stream().map(Message::getBody).toList();
assertTrue(bodies.stream().anyMatch(b -> b.contains("batch-group-one")));
assertTrue(bodies.stream().anyMatch(b -> b.contains("batch-group-two")));
}
/** Per-group dedup on the queue too, so its own topic-wide window cannot mask the topic's. */
private String createGroupScopedQueue(String queueName) {
sqsService.createQueue(queueName, Map.of(
"FifoQueue", "true",
"DeduplicationScope", "messageGroup",
"FifoThroughputLimit", "perMessageGroupId"), REGION);
return BASE_URL + "/" + ACCOUNT + "/" + queueName;
}
private String createFifoTopic(String topicName, Map<String, String> attributes, String queueName) {
snsService.createTopic(topicName, attributes, null, REGION);
String topicArn = "arn:aws:sns:" + REGION + ":" + ACCOUNT + ":" + topicName;
snsService.subscribe(topicArn, "sqs",
"arn:aws:sqs:" + REGION + ":" + ACCOUNT + ":" + queueName, REGION, Map.of());
return topicArn;
}
@Test
void clearFifoDedupForSubscribedQueue_thenRepublishWithSameDedupId_deliversAgain() {
RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT);