mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(ses): implement Contact CRUD for SES v2 (#1723)
* feat(ses): implement Contact CRUD for SES v2
Add the SES v2 Contact APIs under /v2/email/contact-lists/{name}/contacts:
CreateContact, GetContact, ListContacts (POST .../contacts/list),
UpdateContact, DeleteContact. Contacts carry per-topic subscription
preferences, an unsubscribe-all flag, and free-form attributes;
TopicDefaultPreferences is derived at read time from the list's topics.
Behaviour is verified against real AWS: validation order (Smithy enum ->
EmailAddress format -> list existence -> topic existence), AlreadyExists /
NotFound / invalid-topic / invalid-email error shapes, and the UpdateContact
semantics (TopicPreferences merge by topic name; AttributesData and
UnsubscribeAll replaced). Covered by a RestAssured integration test and an
AWS Java SDK v2 compatibility test.
* refactor(ses): resolve contact list once for reads and delete under lock
Address review consistency findings on the Contact CRUD read/delete paths:
- getContact/listContacts returned only the contact(s), so the controller
fetched the ContactList a second time to render TopicDefaultPreferences.
Between the two calls a concurrent delete could turn a successful read into a
misleading "List not found". The service now returns the resolved list
alongside the contact(s) (ContactWithList / ContactsWithList), so the read is
a single, consistent lookup.
- deleteContact re-checked list existence before acquiring contactMutationLock,
unlike createContact/updateContact which re-check inside it. Move the
getContactList check inside the lock so a concurrent deleteContactList
surfaces "list not found" rather than "contact not found".
This commit is contained in:
1 parent
48f310b63f
commit
10f799a2b7
12 files changed
+1069
-10
No files matched your search
@@ -9,9 +9,11 @@ import io.github.hectorvent.floci.services.ses.model.GuardianOptions;
|
||||
import io.github.hectorvent.floci.services.ses.model.BulkEmailEntry;
|
||||
import io.github.hectorvent.floci.services.ses.model.BulkEmailEntryResult;
|
||||
import io.github.hectorvent.floci.services.ses.model.ConfigurationSet;
|
||||
import io.github.hectorvent.floci.services.ses.model.Contact;
|
||||
import io.github.hectorvent.floci.services.ses.model.ContactList;
|
||||
import io.github.hectorvent.floci.services.ses.model.DedicatedIpPool;
|
||||
import io.github.hectorvent.floci.services.ses.model.Topic;
|
||||
import io.github.hectorvent.floci.services.ses.model.TopicPreference;
|
||||
import io.github.hectorvent.floci.services.ses.model.DeliveryOptions;
|
||||
import io.github.hectorvent.floci.services.ses.model.EmailTemplate;
|
||||
import io.github.hectorvent.floci.services.ses.model.EventDestination;
|
||||
@@ -1342,6 +1344,189 @@ public class SesController {
|
||||
return result;
|
||||
}
|
||||
|
||||
// ───────────────────────────── Contacts ─────────────────────────────
|
||||
|
||||
@POST
|
||||
@Path("/contact-lists/{contactListName}/contacts")
|
||||
public Response createContact(@Context HttpHeaders headers,
|
||||
@PathParam("contactListName") String contactListName, String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
if (body == null || body.isBlank()) {
|
||||
throw new AwsException("BadRequestException", "Request body is required.", 400);
|
||||
}
|
||||
JsonNode request = objectMapper.readTree(body);
|
||||
requireJsonObject(request);
|
||||
String emailAddress = request.path("EmailAddress").asText(null);
|
||||
List<TopicPreference> prefs = parseTopicPreferences(request.path("TopicPreferences"));
|
||||
Boolean unsubscribeAll = parseUnsubscribeAll(request);
|
||||
String attributesData = parseAttributesData(request);
|
||||
sesService.createContact(contactListName, emailAddress, prefs, unsubscribeAll, attributesData, region);
|
||||
LOG.infov("SES V2 CreateContact: {0} in {1}", emailAddress, contactListName);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
} catch (AwsException e) {
|
||||
throw remapV1Exception(e);
|
||||
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/contact-lists/{contactListName}/contacts/list")
|
||||
public Response listContacts(@Context HttpHeaders headers,
|
||||
@PathParam("contactListName") String contactListName, String body) {
|
||||
// AWS uses POST .../contacts/list with Filter/PageSize/NextToken in the body; Floci returns
|
||||
// all contacts (filtering/pagination not yet implemented) but still rejects a malformed or
|
||||
// non-object body like the other v2 endpoints.
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
if (body != null && !body.isBlank()) {
|
||||
requireJsonObject(objectMapper.readTree(body));
|
||||
}
|
||||
SesService.ContactsWithList listed = sesService.listContacts(contactListName, region);
|
||||
ObjectNode result = objectMapper.createObjectNode();
|
||||
ArrayNode arr = result.putArray("Contacts");
|
||||
for (Contact c : listed.contacts()) {
|
||||
arr.add(contactJson(c, listed.list(), false));
|
||||
}
|
||||
return Response.ok(result).build();
|
||||
} catch (AwsException e) {
|
||||
throw remapV1Exception(e);
|
||||
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/contact-lists/{contactListName}/contacts/{emailAddress}")
|
||||
public Response getContact(@Context HttpHeaders headers,
|
||||
@PathParam("contactListName") String contactListName,
|
||||
@PathParam("emailAddress") String emailAddress) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
SesService.ContactWithList result = sesService.getContact(contactListName, emailAddress, region);
|
||||
return Response.ok(contactJson(result.contact(), result.list(), true)).build();
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Path("/contact-lists/{contactListName}/contacts/{emailAddress}")
|
||||
public Response updateContact(@Context HttpHeaders headers,
|
||||
@PathParam("contactListName") String contactListName,
|
||||
@PathParam("emailAddress") String emailAddress, String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
JsonNode request = (body == null || body.isBlank())
|
||||
? objectMapper.createObjectNode()
|
||||
: objectMapper.readTree(body);
|
||||
requireJsonObject(request);
|
||||
JsonNode prefsNode = request.path("TopicPreferences");
|
||||
boolean prefsPresent = !prefsNode.isMissingNode() && !prefsNode.isNull();
|
||||
List<TopicPreference> prefs = prefsPresent ? parseTopicPreferences(prefsNode) : null;
|
||||
Boolean unsubscribeAll = parseUnsubscribeAll(request);
|
||||
String attributesData = parseAttributesData(request);
|
||||
sesService.updateContact(contactListName, emailAddress, prefs, prefsPresent,
|
||||
unsubscribeAll, attributesData, region);
|
||||
LOG.infov("SES V2 UpdateContact: {0} in {1}", emailAddress, contactListName);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
} catch (AwsException e) {
|
||||
throw remapV1Exception(e);
|
||||
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/contact-lists/{contactListName}/contacts/{emailAddress}")
|
||||
public Response deleteContact(@Context HttpHeaders headers,
|
||||
@PathParam("contactListName") String contactListName,
|
||||
@PathParam("emailAddress") String emailAddress) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
sesService.deleteContact(contactListName, emailAddress, region);
|
||||
LOG.infov("SES V2 DeleteContact: {0} in {1}", emailAddress, contactListName);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private List<TopicPreference> parseTopicPreferences(JsonNode node) {
|
||||
if (node == null || node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!node.isArray()) {
|
||||
throw new AwsException("BadRequestException", "TopicPreferences must be an array.", 400);
|
||||
}
|
||||
List<TopicPreference> out = new ArrayList<>();
|
||||
for (JsonNode p : node) {
|
||||
out.add(new TopicPreference(
|
||||
p.path("TopicName").asText(null),
|
||||
p.path("SubscriptionStatus").asText(null)));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// UnsubscribeAll is a Boolean; AWS coerces it the same way as any other SES v2 boolean
|
||||
// (see parseSendingEnabled): a JSON string coerces to true, a number/null/array/object is a
|
||||
// SerializationException. Absent leaves it unset.
|
||||
private static Boolean parseUnsubscribeAll(JsonNode request) {
|
||||
if (!request.has("UnsubscribeAll")) {
|
||||
return null;
|
||||
}
|
||||
return coerceBoolean(request.path("UnsubscribeAll"));
|
||||
}
|
||||
|
||||
// AttributesData is a String; a non-string (number/boolean/array/object) is a
|
||||
// SerializationException. Absent or explicit null leaves it unset.
|
||||
private static String parseAttributesData(JsonNode request) {
|
||||
if (!request.has("AttributesData")) {
|
||||
return null;
|
||||
}
|
||||
JsonNode node = request.path("AttributesData");
|
||||
if (node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (node.isTextual()) {
|
||||
return node.textValue();
|
||||
}
|
||||
if (node.isNumber()) {
|
||||
throw new AwsException("SerializationException",
|
||||
"NUMBER_VALUE can not be converted to a String", 400);
|
||||
}
|
||||
if (node.isBoolean()) {
|
||||
throw new AwsException("SerializationException",
|
||||
(node.booleanValue() ? "TRUE_VALUE" : "FALSE_VALUE")
|
||||
+ " can not be converted to a String", 400);
|
||||
}
|
||||
throw unexpectedStartError(node);
|
||||
}
|
||||
|
||||
private ObjectNode contactJson(Contact c, ContactList list, boolean full) {
|
||||
ObjectNode result = objectMapper.createObjectNode();
|
||||
if (full) {
|
||||
result.put("ContactListName", list.getContactListName());
|
||||
}
|
||||
result.put("EmailAddress", c.getEmailAddress());
|
||||
ArrayNode prefs = result.putArray("TopicPreferences");
|
||||
for (TopicPreference p : c.getTopicPreferences()) {
|
||||
ObjectNode po = prefs.addObject();
|
||||
po.put("TopicName", p.getTopicName());
|
||||
po.put("SubscriptionStatus", p.getSubscriptionStatus());
|
||||
}
|
||||
ArrayNode defaults = result.putArray("TopicDefaultPreferences");
|
||||
for (TopicPreference p : sesService.deriveTopicDefaultPreferences(c, list)) {
|
||||
ObjectNode po = defaults.addObject();
|
||||
po.put("TopicName", p.getTopicName());
|
||||
po.put("SubscriptionStatus", p.getSubscriptionStatus());
|
||||
}
|
||||
result.put("UnsubscribeAll", c.isUnsubscribeAll());
|
||||
if (full && c.getAttributesData() != null) {
|
||||
result.put("AttributesData", c.getAttributesData());
|
||||
}
|
||||
if (full && c.getCreatedTimestamp() != null) {
|
||||
result.put("CreatedTimestamp", c.getCreatedTimestamp().getEpochSecond());
|
||||
}
|
||||
if (c.getLastUpdatedTimestamp() != null) {
|
||||
result.put("LastUpdatedTimestamp", c.getLastUpdatedTimestamp().getEpochSecond());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ──────────────────────────── Account ────────────────────────────
|
||||
|
||||
@GET
|
||||
@@ -1835,20 +2020,26 @@ public class SesController {
|
||||
if (enabledNode.isMissingNode()) {
|
||||
return false;
|
||||
}
|
||||
if (enabledNode.isBoolean()) {
|
||||
return enabledNode.booleanValue();
|
||||
return coerceBoolean(enabledNode);
|
||||
}
|
||||
|
||||
// AWS-verified Jackson coercion for a SES v2 boolean field: a JSON string coerces to true,
|
||||
// while a number/null/array/object is a SerializationException.
|
||||
private static boolean coerceBoolean(JsonNode node) {
|
||||
if (node.isBoolean()) {
|
||||
return node.booleanValue();
|
||||
}
|
||||
if (enabledNode.isTextual()) {
|
||||
if (node.isTextual()) {
|
||||
return true;
|
||||
}
|
||||
if (enabledNode.isNull()) {
|
||||
if (node.isNull()) {
|
||||
throw new AwsException("SerializationException", null, 400);
|
||||
}
|
||||
if (enabledNode.isNumber()) {
|
||||
if (node.isNumber()) {
|
||||
throw new AwsException("SerializationException",
|
||||
"NUMBER_VALUE can not be converted to a Boolean", 400);
|
||||
}
|
||||
throw unexpectedStartError(enabledNode);
|
||||
throw unexpectedStartError(node);
|
||||
}
|
||||
|
||||
private static AwsException unexpectedStartError(JsonNode node) {
|
||||
|
||||
@@ -15,6 +15,7 @@ import io.github.hectorvent.floci.services.ses.model.BulkEmailEntry;
|
||||
import io.github.hectorvent.floci.services.ses.model.BulkEmailEntryResult;
|
||||
import io.github.hectorvent.floci.services.ses.model.CloudWatchDimensionConfiguration;
|
||||
import io.github.hectorvent.floci.services.ses.model.ConfigurationSet;
|
||||
import io.github.hectorvent.floci.services.ses.model.Contact;
|
||||
import io.github.hectorvent.floci.services.ses.model.ContactList;
|
||||
import io.github.hectorvent.floci.services.ses.model.DedicatedIpPool;
|
||||
import io.github.hectorvent.floci.services.ses.model.DeliveryOptions;
|
||||
@@ -24,6 +25,7 @@ import io.github.hectorvent.floci.services.ses.model.Identity;
|
||||
import io.github.hectorvent.floci.services.ses.model.MessageHeader;
|
||||
import io.github.hectorvent.floci.services.ses.model.MessageTag;
|
||||
import io.github.hectorvent.floci.services.ses.model.Topic;
|
||||
import io.github.hectorvent.floci.services.ses.model.TopicPreference;
|
||||
import io.github.hectorvent.floci.services.ses.model.TrackingOptions;
|
||||
import io.github.hectorvent.floci.services.ses.model.VdmOptions;
|
||||
import io.github.hectorvent.floci.services.ses.model.SentEmail;
|
||||
@@ -84,8 +86,12 @@ public class SesService {
|
||||
private final StorageBackend<String, AccountSuppressionAttributes> accountSuppressionStore;
|
||||
private final StorageBackend<String, DedicatedIpPool> dedicatedIpPoolStore;
|
||||
private final StorageBackend<String, ContactList> contactListStore;
|
||||
private final StorageBackend<String, Contact> contactStore;
|
||||
// Guards the one-list-per-account check-then-create so concurrent creates can't both pass.
|
||||
private final Object contactListCreateLock = new Object();
|
||||
// Serializes contact create/update against contact-list deletion so a concurrent delete
|
||||
// can't purge the list between validation and the write, leaving an orphaned contact.
|
||||
private final Object contactMutationLock = new Object();
|
||||
private final SmtpRelay smtpRelay;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final SesEventPublisher eventPublisher;
|
||||
@@ -116,6 +122,8 @@ public class SesService {
|
||||
new TypeReference<Map<String, DedicatedIpPool>>() {});
|
||||
this.contactListStore = storageFactory.create("ses", "ses-contact-lists.json",
|
||||
new TypeReference<Map<String, ContactList>>() {});
|
||||
this.contactStore = storageFactory.create("ses", "ses-contacts.json",
|
||||
new TypeReference<Map<String, Contact>>() {});
|
||||
this.smtpRelay = smtpRelay;
|
||||
this.objectMapper = objectMapper;
|
||||
this.eventPublisher = eventPublisher;
|
||||
@@ -133,11 +141,13 @@ public class SesService {
|
||||
StorageBackend<String, AccountSuppressionAttributes> accountSuppressionStore,
|
||||
StorageBackend<String, DedicatedIpPool> dedicatedIpPoolStore,
|
||||
StorageBackend<String, ContactList> contactListStore,
|
||||
StorageBackend<String, Contact> contactStore,
|
||||
SmtpRelay smtpRelay,
|
||||
ObjectMapper objectMapper,
|
||||
Clock clock) {
|
||||
this(identityStore, emailStore, accountSettingsStore, templateStore, configSetStore, suppressionStore,
|
||||
accountSuppressionStore, dedicatedIpPoolStore, contactListStore, smtpRelay, objectMapper, null, clock);
|
||||
accountSuppressionStore, dedicatedIpPoolStore, contactListStore, contactStore, smtpRelay,
|
||||
objectMapper, null, clock);
|
||||
}
|
||||
|
||||
SesService(StorageBackend<String, Identity> identityStore,
|
||||
@@ -149,6 +159,7 @@ public class SesService {
|
||||
StorageBackend<String, AccountSuppressionAttributes> accountSuppressionStore,
|
||||
StorageBackend<String, DedicatedIpPool> dedicatedIpPoolStore,
|
||||
StorageBackend<String, ContactList> contactListStore,
|
||||
StorageBackend<String, Contact> contactStore,
|
||||
SmtpRelay smtpRelay,
|
||||
ObjectMapper objectMapper,
|
||||
Route53Service route53Service,
|
||||
@@ -162,6 +173,7 @@ public class SesService {
|
||||
this.accountSuppressionStore = accountSuppressionStore;
|
||||
this.dedicatedIpPoolStore = dedicatedIpPoolStore;
|
||||
this.contactListStore = contactListStore;
|
||||
this.contactStore = contactStore;
|
||||
this.smtpRelay = smtpRelay;
|
||||
this.objectMapper = objectMapper;
|
||||
this.eventPublisher = null;
|
||||
@@ -1366,10 +1378,25 @@ public class SesService {
|
||||
|
||||
public void deleteContactList(String name, String region) {
|
||||
String key = contactListKey(region, name);
|
||||
if (contactListStore.get(key).isEmpty()) {
|
||||
throw contactListNotFound(name);
|
||||
// Existence check, list delete, and contact purge all under the lock: concurrent deletes
|
||||
// can't both pass the check (one must 404), and a concurrent create/update can't slip a
|
||||
// contact in after the purge. Contacts are stored independently, so purging them here keeps
|
||||
// them from leaking into a same-named list recreated later (AWS deletes them with the list).
|
||||
String prefix = "contact::" + region + "::" + name + "::";
|
||||
synchronized (contactMutationLock) {
|
||||
if (contactListStore.get(key).isEmpty()) {
|
||||
throw contactListNotFound(name);
|
||||
}
|
||||
contactListStore.delete(key);
|
||||
// Delete by the actual stored keys (not keys rebuilt from each value's EmailAddress),
|
||||
// so a persisted entry whose key and EmailAddress diverge is still purged.
|
||||
List<String> contactKeys = contactStore.keys().stream()
|
||||
.filter(k -> k.startsWith(prefix))
|
||||
.toList();
|
||||
for (String contactKey : contactKeys) {
|
||||
contactStore.delete(contactKey);
|
||||
}
|
||||
}
|
||||
contactListStore.delete(key);
|
||||
LOG.infov("Deleted SES contact list: {0} in region {1}", name, region);
|
||||
}
|
||||
|
||||
@@ -1481,6 +1508,196 @@ public class SesService {
|
||||
return "contactList::" + region + "::" + name;
|
||||
}
|
||||
|
||||
// ─────────────────────────── Contacts ───────────────────────────
|
||||
|
||||
private static final Pattern EMAIL_PATTERN = Pattern.compile("^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$");
|
||||
|
||||
public Contact createContact(String listName, String emailAddress, List<TopicPreference> topicPreferences,
|
||||
Boolean unsubscribeAll, String attributesData, String region) {
|
||||
validateContactInput(listName, emailAddress, topicPreferences, region);
|
||||
Contact contact = new Contact(emailAddress);
|
||||
contact.setTopicPreferences(topicPreferences);
|
||||
contact.setUnsubscribeAll(unsubscribeAll != null && unsubscribeAll);
|
||||
contact.setAttributesData(attributesData);
|
||||
Instant now = Instant.now(clock);
|
||||
contact.setCreatedTimestamp(now);
|
||||
contact.setLastUpdatedTimestamp(now);
|
||||
String key = contactKey(region, listName, emailAddress);
|
||||
// Re-check the list, duplicate, and put under the lock so a concurrent deleteContactList
|
||||
// can't purge the list between validation and the write (which would orphan this contact).
|
||||
synchronized (contactMutationLock) {
|
||||
getContactList(listName, region);
|
||||
if (contactStore.get(key).isPresent()) {
|
||||
throw new AwsException("AlreadyExistsException",
|
||||
emailAddress + " already exists in List.", 400);
|
||||
}
|
||||
contactStore.put(key, contact);
|
||||
}
|
||||
LOG.infov("Created SES contact {0} in list {1} (region {2})", emailAddress, listName, region);
|
||||
return contact;
|
||||
}
|
||||
|
||||
// Read operations return the resolved ContactList alongside the contact(s) so the controller
|
||||
// can render TopicDefaultPreferences without a second getContactList round-trip (which would
|
||||
// open a TOCTOU window where a concurrent delete turns a successful read into "List not found").
|
||||
public record ContactWithList(Contact contact, ContactList list) {
|
||||
}
|
||||
|
||||
public record ContactsWithList(List<Contact> contacts, ContactList list) {
|
||||
}
|
||||
|
||||
public ContactWithList getContact(String listName, String emailAddress, String region) {
|
||||
validateEmailAddress(emailAddress);
|
||||
ContactList list = getContactList(listName, region);
|
||||
Contact contact = contactStore.get(contactKey(region, listName, emailAddress))
|
||||
.orElseThrow(() -> contactNotFound(emailAddress));
|
||||
return new ContactWithList(contact, list);
|
||||
}
|
||||
|
||||
public ContactsWithList listContacts(String listName, String region) {
|
||||
ContactList list = getContactList(listName, region);
|
||||
String prefix = "contact::" + region + "::" + listName + "::";
|
||||
List<Contact> contacts = contactStore.scan(k -> k.startsWith(prefix)).stream()
|
||||
.sorted(Comparator.comparing(Contact::getEmailAddress,
|
||||
Comparator.nullsFirst(Comparator.naturalOrder())))
|
||||
.toList();
|
||||
return new ContactsWithList(contacts, list);
|
||||
}
|
||||
|
||||
public Contact updateContact(String listName, String emailAddress, List<TopicPreference> topicPreferences,
|
||||
boolean topicPreferencesPresent, Boolean unsubscribeAll, String attributesData,
|
||||
String region) {
|
||||
validateContactInput(listName, emailAddress, topicPreferences, region);
|
||||
String key = contactKey(region, listName, emailAddress);
|
||||
Contact existing;
|
||||
// Re-check the list and read-modify-write under the lock so a concurrent deleteContactList
|
||||
// can't purge the contact/list between validation and the write (which would resurrect it).
|
||||
synchronized (contactMutationLock) {
|
||||
getContactList(listName, region);
|
||||
existing = contactStore.get(key).orElseThrow(() -> contactNotFound(emailAddress));
|
||||
// Verified against real AWS: TopicPreferences merge by topic name (omitting keeps existing);
|
||||
// AttributesData and UnsubscribeAll are replaced (omitting clears / resets them).
|
||||
if (topicPreferencesPresent) {
|
||||
existing.setTopicPreferences(mergeTopicPreferences(existing.getTopicPreferences(), topicPreferences));
|
||||
}
|
||||
existing.setUnsubscribeAll(unsubscribeAll != null && unsubscribeAll);
|
||||
existing.setAttributesData(attributesData);
|
||||
existing.setLastUpdatedTimestamp(Instant.now(clock));
|
||||
contactStore.put(key, existing);
|
||||
}
|
||||
LOG.infov("Updated SES contact {0} in list {1}", emailAddress, listName);
|
||||
return existing;
|
||||
}
|
||||
|
||||
public void deleteContact(String listName, String emailAddress, String region) {
|
||||
validateEmailAddress(emailAddress);
|
||||
String key = contactKey(region, listName, emailAddress);
|
||||
// List re-check + existence check + delete under the lock (matching create/update): a
|
||||
// concurrent deleteContactList then surfaces "list not found" rather than "contact not
|
||||
// found", and an updateContact can't put a just-deleted contact back (resurrecting it).
|
||||
synchronized (contactMutationLock) {
|
||||
getContactList(listName, region);
|
||||
if (contactStore.get(key).isEmpty()) {
|
||||
throw contactNotFound(emailAddress);
|
||||
}
|
||||
contactStore.delete(key);
|
||||
}
|
||||
LOG.infov("Deleted SES contact {0} in list {1}", emailAddress, listName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Derives {@code TopicDefaultPreferences}: each list topic the contact has not set an explicit
|
||||
* preference for, carrying that topic's default subscription status.
|
||||
*/
|
||||
public List<TopicPreference> deriveTopicDefaultPreferences(Contact contact, ContactList list) {
|
||||
Set<String> explicit = new HashSet<>();
|
||||
for (TopicPreference p : contact.getTopicPreferences()) {
|
||||
explicit.add(p.getTopicName());
|
||||
}
|
||||
List<TopicPreference> defaults = new ArrayList<>();
|
||||
for (Topic t : list.getTopics()) {
|
||||
if (!explicit.contains(t.getTopicName())) {
|
||||
defaults.add(new TopicPreference(t.getTopicName(), t.getDefaultSubscriptionStatus()));
|
||||
}
|
||||
}
|
||||
return defaults;
|
||||
}
|
||||
|
||||
private static AwsException contactNotFound(String emailAddress) {
|
||||
return new AwsException("NotFoundException", emailAddress + " doesn't exist in List.", 404);
|
||||
}
|
||||
|
||||
// Validation order verified against real AWS: protocol-layer (Smithy) topic-preference checks
|
||||
// first, then EmailAddress format, then contact-list existence, then topic existence.
|
||||
private void validateContactInput(String listName, String emailAddress, List<TopicPreference> prefs,
|
||||
String region) {
|
||||
if (prefs != null) {
|
||||
for (int i = 0; i < prefs.size(); i++) {
|
||||
TopicPreference p = prefs.get(i);
|
||||
String member = "topicPreferences." + (i + 1) + ".member.";
|
||||
if (p.getTopicName() == null) {
|
||||
throw validationError(member + "topicName", "Member must not be null");
|
||||
}
|
||||
if (p.getSubscriptionStatus() == null) {
|
||||
throw validationError(member + "subscriptionStatus", "Member must not be null");
|
||||
}
|
||||
if (!SUBSCRIPTION_STATUSES.contains(p.getSubscriptionStatus())) {
|
||||
throw validationError(member + "subscriptionStatus",
|
||||
"Member must satisfy enum value set: [OPT_OUT, OPT_IN]");
|
||||
}
|
||||
}
|
||||
}
|
||||
validateEmailAddress(emailAddress);
|
||||
ContactList list = getContactList(listName, region);
|
||||
if (prefs != null && !prefs.isEmpty()) {
|
||||
Set<String> topicNames = new HashSet<>();
|
||||
for (Topic t : list.getTopics()) {
|
||||
topicNames.add(t.getTopicName());
|
||||
}
|
||||
for (TopicPreference p : prefs) {
|
||||
if (!topicNames.contains(p.getTopicName())) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"List: " + listName + " doesn't contain Topic: " + p.getTopicName(), 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static List<TopicPreference> mergeTopicPreferences(List<TopicPreference> existing,
|
||||
List<TopicPreference> provided) {
|
||||
Map<String, TopicPreference> byTopic = new LinkedHashMap<>();
|
||||
if (existing != null) {
|
||||
for (TopicPreference p : existing) {
|
||||
byTopic.put(p.getTopicName(), p);
|
||||
}
|
||||
}
|
||||
if (provided != null) {
|
||||
for (TopicPreference p : provided) {
|
||||
byTopic.put(p.getTopicName(), p);
|
||||
}
|
||||
}
|
||||
return new ArrayList<>(byTopic.values());
|
||||
}
|
||||
|
||||
private static void validateEmailAddress(String emailAddress) {
|
||||
// Verified against real AWS: a missing/null required member is a Smithy validation error,
|
||||
// an empty/blank value is "can't be blank", and only a non-blank malformed value is "invalid".
|
||||
if (emailAddress == null) {
|
||||
throw validationError("emailAddress", "Member must not be null");
|
||||
}
|
||||
if (emailAddress.isBlank()) {
|
||||
throw new AwsException("BadRequestException", "EmailAddress can't be blank.", 400);
|
||||
}
|
||||
if (!EMAIL_PATTERN.matcher(emailAddress).matches()) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"EmailAddress <" + emailAddress + "> is invalid", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static String contactKey(String region, String listName, String emailAddress) {
|
||||
return "contact::" + region + "::" + listName + "::" + emailAddress;
|
||||
}
|
||||
|
||||
static void validateConfigurationSetName(String name) {
|
||||
if (name == null || name.isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package io.github.hectorvent.floci.services.ses.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A contact within an SES V2 contact list: an email address plus its explicit
|
||||
* per-topic subscription preferences, an unsubscribe-all flag, and free-form
|
||||
* attributes. {@code TopicDefaultPreferences} is not stored — it is derived at
|
||||
* read time from the list's topics for topics the contact hasn't set explicitly.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class Contact {
|
||||
|
||||
@JsonProperty("EmailAddress")
|
||||
private String emailAddress;
|
||||
|
||||
@JsonProperty("TopicPreferences")
|
||||
private List<TopicPreference> topicPreferences = new ArrayList<>();
|
||||
|
||||
@JsonProperty("UnsubscribeAll")
|
||||
private boolean unsubscribeAll;
|
||||
|
||||
@JsonProperty("AttributesData")
|
||||
private String attributesData;
|
||||
|
||||
@JsonProperty("CreatedTimestamp")
|
||||
private Instant createdTimestamp;
|
||||
|
||||
@JsonProperty("LastUpdatedTimestamp")
|
||||
private Instant lastUpdatedTimestamp;
|
||||
|
||||
public Contact() {}
|
||||
|
||||
public Contact(String emailAddress) {
|
||||
this.emailAddress = emailAddress;
|
||||
}
|
||||
|
||||
public String getEmailAddress() { return emailAddress; }
|
||||
public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; }
|
||||
|
||||
public List<TopicPreference> getTopicPreferences() { return topicPreferences; }
|
||||
public void setTopicPreferences(List<TopicPreference> topicPreferences) {
|
||||
this.topicPreferences = topicPreferences == null ? new ArrayList<>() : topicPreferences;
|
||||
}
|
||||
|
||||
public boolean isUnsubscribeAll() { return unsubscribeAll; }
|
||||
public void setUnsubscribeAll(boolean unsubscribeAll) { this.unsubscribeAll = unsubscribeAll; }
|
||||
|
||||
public String getAttributesData() { return attributesData; }
|
||||
public void setAttributesData(String attributesData) { this.attributesData = attributesData; }
|
||||
|
||||
public Instant getCreatedTimestamp() { return createdTimestamp; }
|
||||
public void setCreatedTimestamp(Instant createdTimestamp) { this.createdTimestamp = createdTimestamp; }
|
||||
|
||||
public Instant getLastUpdatedTimestamp() { return lastUpdatedTimestamp; }
|
||||
public void setLastUpdatedTimestamp(Instant lastUpdatedTimestamp) {
|
||||
this.lastUpdatedTimestamp = lastUpdatedTimestamp;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package io.github.hectorvent.floci.services.ses.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
/**
|
||||
* A contact's subscription preference for a single SES V2 contact-list topic:
|
||||
* a topic name and a subscription status ({@code OPT_IN} or {@code OPT_OUT}).
|
||||
*/
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class TopicPreference {
|
||||
|
||||
@JsonProperty("TopicName")
|
||||
private String topicName;
|
||||
|
||||
@JsonProperty("SubscriptionStatus")
|
||||
private String subscriptionStatus;
|
||||
|
||||
public TopicPreference() {}
|
||||
|
||||
public TopicPreference(String topicName, String subscriptionStatus) {
|
||||
this.topicName = topicName;
|
||||
this.subscriptionStatus = subscriptionStatus;
|
||||
}
|
||||
|
||||
public String getTopicName() { return topicName; }
|
||||
public void setTopicName(String topicName) { this.topicName = topicName; }
|
||||
|
||||
public String getSubscriptionStatus() { return subscriptionStatus; }
|
||||
public void setSubscriptionStatus(String subscriptionStatus) {
|
||||
this.subscriptionStatus = subscriptionStatus;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user