feat(ses): apply the ListContacts filter (#4981)

* feat(ses): apply the ListContacts filter

ListContacts now honours Filter.FilteredStatus and Filter.TopicFilter the way
SES v2 matches them, with the validation messages and precedence SES answers.
The filter is applied before the page is cut, so filtered pages are exact,
and a token stays a position in the list, as on SES, rather than being bound
to the filter.

* test(ses): name the filter unit test SesContactFilterServiceTest
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-10-02 20:32:49 -04:00
1 parent a68f8eab3a
commit ef9ed50742
8 files changed
+545 -8

No files matched your search

@@ -0,0 +1,161 @@
package io.github.hectorvent.floci.services.ses;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.ses.SesContactService.ContactFilter;
import io.github.hectorvent.floci.services.ses.SesContactService.TopicFilter;
import io.github.hectorvent.floci.services.ses.model.Contact;
import io.github.hectorvent.floci.services.ses.model.Topic;
import io.github.hectorvent.floci.services.ses.model.TopicPreference;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import java.time.Clock;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* The ListContacts {@code Filter}. The fixture is the one the filter was probed with on real SES v2:
* topic {@code tin} defaults to OPT_IN and {@code tout} to OPT_OUT, and every expected list below is
* what SES returned for the same contacts and filter.
*/
class SesContactFilterServiceTest {
private static final String REGION = "us-east-1";
private static final String LIST = "filter-list";
private static final String IN = "OPT_IN";
private static final String OUT = "OPT_OUT";
private SesContactService service;
@BeforeEach
void setUp() {
service = new SesContactService(new InMemoryStorage<>(), new InMemoryStorage<>(), Clock.systemUTC());
service.createContactList(LIST, "d", List.of(new Topic("tin", "In", IN, "d"),
new Topic("tout", "Out", OUT, "d")), List.of(), REGION);
contact("c1", false, new TopicPreference("tin", OUT), new TopicPreference("tout", IN));
contact("c2", false, new TopicPreference("tin", IN), new TopicPreference("tout", OUT));
contact("c3", false);
contact("c4", true);
contact("c5", true, new TopicPreference("tin", IN), new TopicPreference("tout", IN));
contact("c6", false, new TopicPreference("tin", OUT));
contact("c7", false, new TopicPreference("tout", IN));
}
@Test
void filteredStatusAlone_matchesUnsubscribeAllOnly() {
assertEquals(List.of("c1", "c2", "c3", "c6", "c7"), names(new ContactFilter(IN, null)));
assertEquals(List.of("c4", "c5"), names(new ContactFilter(OUT, null)));
}
@Test
void topicFilter_usesTheTopicDefaultOnlyWhenAskedTo() {
assertEquals(List.of("c2"), names(topic(IN, "tin", false)));
assertEquals(List.of("c2", "c3", "c7"), names(topic(IN, "tin", true)));
assertEquals(List.of("c1", "c4", "c5", "c6"), names(topic(OUT, "tin", false)));
assertEquals(List.of("c1", "c4", "c5", "c6"), names(topic(OUT, "tin", true)));
assertEquals(List.of("c1", "c7"), names(topic(IN, "tout", false)));
assertEquals(List.of("c1", "c7"), names(topic(IN, "tout", true)));
assertEquals(List.of("c2", "c4", "c5"), names(topic(OUT, "tout", false)));
assertEquals(List.of("c2", "c3", "c4", "c5", "c6"), names(topic(OUT, "tout", true)));
}
@Test
void filteredPages_areExactAndTheTokenIsNotBoundToTheFilter() {
PaginatedResult<Contact> first = page(new ContactFilter(IN, null), 2, null);
assertEquals(List.of("c1", "c2"), names(first.items()));
PaginatedResult<Contact> second = page(new ContactFilter(IN, null), 2, first.nextToken());
assertEquals(List.of("c3", "c6"), names(second.items()));
// The token is a position, so another filter (or none) continues from the same place.
assertEquals(List.of("c3", "c4"), names(page(null, 2, first.nextToken()).items()));
assertEquals(List.of("c4", "c5"), names(page(new ContactFilter(OUT, null), 2, first.nextToken()).items()));
}
@Test
void lastFilteredPage_hasNoToken() {
PaginatedResult<Contact> only = page(new ContactFilter(OUT, null), 2, null);
assertEquals(List.of("c4", "c5"), names(only.items()));
assertNull(only.nextToken());
}
@Test
void invalidStatus_isAValidationError() {
assertError("BadRequestException", "1 validation error detected: Value at 'filter.filteredStatus' "
+ "failed to satisfy constraint: Member must satisfy enum value set: [OPT_OUT, OPT_IN]",
() -> service.listContacts(LIST, REGION, SesListPaging.V2_LIST_CONTACTS, null, null,
new ContactFilter("opt_in", null)));
}
@Test
void missingStatusOrBlankTopic_isRejected() {
assertError("BadRequestException", "Invalid FilteredStatus <null>",
() -> list(LIST, null, null, new ContactFilter(null, new TopicFilter("tin", false))));
assertError("BadRequestException", "TopicName can't be blank in TopicFilter.",
() -> list(LIST, null, null, topic(IN, "", false)));
assertError("BadRequestException", "TopicName can't be blank in TopicFilter.",
() -> list(LIST, null, null, topic(IN, null, false)));
}
@Test
void unknownTopic_isNotFoundAfterTheList() {
assertError("NotFoundException", "List: filter-list doesn't contain Topic: nope",
() -> list(LIST, null, null, topic(IN, "nope", true)));
assertError("NotFoundException", "List with name: ghost doesn't exist.",
() -> list("ghost", null, null, topic(IN, "nope", false)));
}
// Probed precedence: enum, page size, filter shape, token, list, topic.
@Test
void errors_followTheProbedPrecedence() {
assertError("BadRequestException", "1 validation error detected: Value at 'filter.filteredStatus' "
+ "failed to satisfy constraint: Member must satisfy enum value set: [OPT_OUT, OPT_IN]",
() -> list("ghost", 0, "garbage", new ContactFilter("BOGUS", new TopicFilter("", false))));
assertError("BadRequestException", "The page size must be between 1 and 1000",
() -> list(LIST, 0, null, new ContactFilter(null, null)));
assertError("BadRequestException", "TopicName can't be blank in TopicFilter.",
() -> list("ghost", null, "garbage", topic(IN, "", false)));
assertError("BadRequestException", "Provided NextToken is invalid",
() -> list(LIST, null, "garbage", topic(IN, "nope", false)));
}
private void contact(String name, boolean unsubscribeAll, TopicPreference... preferences) {
service.createContact(LIST, name + "@example.com", List.of(preferences), unsubscribeAll, null, REGION);
}
private static ContactFilter topic(String status, String topicName, boolean useDefault) {
return new ContactFilter(status, new TopicFilter(topicName, useDefault));
}
private List<String> names(ContactFilter filter) {
return names(page(filter, 1000, null).items());
}
private PaginatedResult<Contact> page(ContactFilter filter, Integer pageSize, String token) {
return list(LIST, pageSize, token, filter).contacts();
}
private SesContactService.ContactPage list(String listName, Integer pageSize, String token,
ContactFilter filter) {
return service.listContacts(listName, REGION, SesListPaging.V2_LIST_CONTACTS, pageSize, token, filter);
}
private static List<String> names(List<Contact> contacts) {
List<String> names = new ArrayList<>();
for (Contact contact : contacts) {
names.add(contact.getEmailAddress().substring(0, contact.getEmailAddress().indexOf('@')));
}
return names;
}
private static void assertError(String code, String message, Executable call) {
AwsException e = assertThrows(AwsException.class, call);
assertEquals(code, e.getErrorCode());
assertEquals(message, e.getMessage());
}
}
@@ -0,0 +1,152 @@
package io.github.hectorvent.floci.services.ses;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
/**
* ListContacts {@code Filter} on the wire: parsing, the SES v2 boolean coercion of
* UseDefaultIfPreferenceUnavailable, exact filtered pages and the error statuses. The membership
* rules and the full error precedence are covered by {@code SesContactFilterServiceTest}.
*/
@QuarkusTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class SesContactFilterV2IntegrationTest {
private static final String REGION = "me-central-1";
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/" + REGION + "/ses/aws4_request";
private static final String LIST = "filter-wire";
private static final String CONTACTS = "/v2/email/contact-lists/" + LIST + "/contacts";
private boolean created;
// Not @BeforeAll: the Quarkus test port is only bound once the first test starts.
@BeforeEach
void createContacts() {
if (created) {
return;
}
send("/v2/email/contact-lists", """
{"ContactListName": "%s", "Topics": [
{"TopicName": "news", "DisplayName": "News", "DefaultSubscriptionStatus": "OPT_IN"}]}
""".formatted(LIST)).statusCode(200);
// a and c opted out of news explicitly, b and d have no preference, e unsubscribed from all.
contact("a", "{\"TopicName\":\"news\",\"SubscriptionStatus\":\"OPT_OUT\"}", false);
contact("b", "", false);
contact("c", "{\"TopicName\":\"news\",\"SubscriptionStatus\":\"OPT_OUT\"}", false);
contact("d", "", false);
contact("e", "", true);
created = true;
}
@Test
void topicFilter_withDefault_pagesTheFilteredSetExactly() {
String filter = "\"Filter\": {\"FilteredStatus\": \"OPT_IN\", \"TopicFilter\": "
+ "{\"TopicName\": \"news\", \"UseDefaultIfPreferenceUnavailable\": \"yes\"}}";
String token = list("{" + filter + ", \"PageSize\": 1}")
.body("Contacts.EmailAddress", contains("b@example.com"))
.extract().path("NextToken");
list("{" + filter + ", \"PageSize\": 1, \"NextToken\": \"" + token + "\"}")
.body("Contacts.EmailAddress", contains("d@example.com"))
.body("NextToken", nullValue());
}
@Test
void topicFilter_withoutDefault_skipsContactsWithoutAPreference() {
list("{\"Filter\": {\"FilteredStatus\": \"OPT_OUT\", \"TopicFilter\": {\"TopicName\": \"news\"}}}")
.body("Contacts.EmailAddress", contains("a@example.com", "c@example.com", "e@example.com"));
}
@Test
void filteredStatusAlone_selectsUnsubscribeAll() {
list("{\"Filter\": {\"FilteredStatus\": \"OPT_OUT\"}}")
.body("Contacts.EmailAddress", contains("e@example.com"));
}
@Test
void useDefault_rejectsAStringThatIsNotABoolean() {
send(CONTACTS + "/list", "{\"Filter\": {\"FilteredStatus\": \"OPT_IN\", \"TopicFilter\": "
+ "{\"TopicName\": \"news\", \"UseDefaultIfPreferenceUnavailable\": \"abc\"}}}")
.statusCode(400)
.body("__type", equalTo("SerializationException"))
.body("message", equalTo("STRING_VALUE can not be converted to an Boolean"));
}
@Test
void errors_carryTheProbedStatusesAndMessages() {
send(CONTACTS + "/list", "{\"Filter\": {}}").statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo("Invalid FilteredStatus <null>"));
send(CONTACTS + "/list", "{\"Filter\": {\"FilteredStatus\": \"OPT_IN\", \"TopicFilter\": {}}}")
.statusCode(400)
.body("message", equalTo("TopicName can't be blank in TopicFilter."));
send(CONTACTS + "/list", "{\"Filter\": {\"FilteredStatus\": \"OPT_IN\", \"TopicFilter\": "
+ "{\"TopicName\": \"nope\"}}}")
.statusCode(404)
.body("__type", equalTo("NotFoundException"))
.body("message", equalTo("List: " + LIST + " doesn't contain Topic: nope"));
}
@Test
void wrongJsonTypes_areSerializationExceptions() {
send(CONTACTS + "/list", "{\"Filter\": []}").statusCode(400)
.body("__type", equalTo("SerializationException"))
.body("message", equalTo("Start of list found where not expected"));
send(CONTACTS + "/list", "{\"Filter\": {\"FilteredStatus\": \"OPT_IN\", \"TopicFilter\": \"x\"}}")
.statusCode(400)
.body("__type", equalTo("SerializationException"))
.body("message", equalTo("Expected null"));
send(CONTACTS + "/list", "{\"Filter\": {\"FilteredStatus\": 1}, \"PageSize\": 0}").statusCode(400)
.body("__type", equalTo("SerializationException"))
.body("message", equalTo("NUMBER_VALUE can not be converted to a String"));
}
@Test
void topicName_isMatchedExactly() {
send(CONTACTS + "/list", "{\"Filter\": {\"FilteredStatus\": \"OPT_IN\", \"TopicFilter\": "
+ "{\"TopicName\": \" news \"}}}")
.statusCode(404)
.body("message", equalTo("List: " + LIST + " doesn't contain Topic: news "));
send(CONTACTS + "/list", "{\"Filter\": {\"FilteredStatus\": \"OPT_IN\", \"TopicFilter\": "
+ "{\"TopicName\": \" \"}}}")
.statusCode(400)
.body("message", equalTo("TopicName can't be blank in TopicFilter."));
}
@Test
void nullTopicFilter_isTreatedAsAbsent() {
list("{\"Filter\": {\"FilteredStatus\": \"OPT_OUT\", \"TopicFilter\": null}}")
.body("Contacts.EmailAddress", contains("e@example.com"));
}
@Test
void filterOnAMissingList_reportsTheListBeforeTheTopic() {
send("/v2/email/contact-lists/ghost/contacts/list", "{\"Filter\": {\"FilteredStatus\": \"OPT_IN\", "
+ "\"TopicFilter\": {\"TopicName\": \"nope\"}}}")
.statusCode(404)
.body("message", equalTo("List with name: ghost doesn't exist."));
}
private void contact(String name, String preference, boolean unsubscribeAll) {
send(CONTACTS, """
{"EmailAddress": "%s@example.com", "TopicPreferences": [%s], "UnsubscribeAll": %s}
""".formatted(name, preference, unsubscribeAll)).statusCode(200);
}
private static ValidatableResponse list(String body) {
return send(CONTACTS + "/list", body).statusCode(200);
}
private static ValidatableResponse send(String path, String body) {
return given().contentType("application/json").header("Authorization", AUTH).body(body)
.when().post(path).then();
}
}
@@ -164,6 +164,38 @@ class SesV2JsonTest {
}
}
@Test
void structureMemberOrAbsent_rejectsANonObjectTheWayAwsDoes() {
JsonNode node = json("{\"o\":{},\"n\":null,\"a\":[],\"s\":\"x\",\"i\":1}");
assertTrue(SesV2Json.structureMemberOrAbsent(node, "o").isObject());
assertTrue(SesV2Json.structureMemberOrAbsent(node, "n").isNull());
assertTrue(SesV2Json.structureMemberOrAbsent(node, "missing").isMissingNode());
assertEquals("Start of list found where not expected", assertAws("SerializationException", 400,
() -> SesV2Json.structureMemberOrAbsent(node, "a")).getMessage());
assertEquals("Expected null", assertAws("SerializationException", 400,
() -> SesV2Json.structureMemberOrAbsent(node, "s")).getMessage());
assertEquals("Expected null", assertAws("SerializationException", 400,
() -> SesV2Json.structureMemberOrAbsent(node, "i")).getMessage());
}
@Test
void typedStringMemberOrAbsent_namesTheWrongType() {
JsonNode node = json("{\"s\":\"x\",\"n\":null,\"i\":1,\"t\":true,\"f\":false,\"o\":{},\"a\":[]}");
assertEquals("x", SesV2Json.typedStringMemberOrAbsent(node, "s"));
assertNull(SesV2Json.typedStringMemberOrAbsent(node, "n"));
assertNull(SesV2Json.typedStringMemberOrAbsent(node, "missing"));
assertEquals("NUMBER_VALUE can not be converted to a String", assertAws("SerializationException", 400,
() -> SesV2Json.typedStringMemberOrAbsent(node, "i")).getMessage());
assertEquals("TRUE_VALUE can not be converted to a String", assertAws("SerializationException", 400,
() -> SesV2Json.typedStringMemberOrAbsent(node, "t")).getMessage());
assertEquals("FALSE_VALUE can not be converted to a String", assertAws("SerializationException", 400,
() -> SesV2Json.typedStringMemberOrAbsent(node, "f")).getMessage());
assertEquals("Start of structure or map found where not expected.", assertAws("SerializationException",
400, () -> SesV2Json.typedStringMemberOrAbsent(node, "o")).getMessage());
assertEquals("Start of list found where not expected", assertAws("SerializationException", 400,
() -> SesV2Json.typedStringMemberOrAbsent(node, "a")).getMessage());
}
@Test
void unexpectedStartError_distinguishesListFromStructure() {
assertEquals("Start of list found where not expected",