mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
refactor(ses): split SesService into per-domain services behind a facade (#2357)
* refactor(ses): extract SesReceiptRuleService from SesService (strangler step 1) First step of the store-based domain split. Moves the receipt-rule-set domain — its store, lock, name validation, and the six Create/Describe/List/Delete/SetActive/DescribeActive methods — into a new @ApplicationScoped SesReceiptRuleService. SesService becomes a facade that delegates, so the v1 SesQueryHandler call sites are unchanged. The domain service is now unit-testable with just its own store and a clock. * refactor(ses): extract SesAccountService from SesService (strangler step 2) Second store-based domain split, same procedure as the receipt-rule step: the account sending-enabled flag (accountSettingsStore) moves into a new @ApplicationScoped SesAccountService, and SesService delegates. Consumers (v1 SesQueryHandler and v2 SesController) are unchanged. Account suppression/VDM stay in the facade for now — they share validateSuppressionReason with the suppression-list domain and extract with it later. * refactor(ses): extract SesCvetService from SesService (strangler step 3) Third store-based domain split, showing the facade-as-coordinator case: get/list/delete delegate straight through, but create/update keep their From-verified identity validation in the SesService facade before delegating storage, and sendCustomVerificationEmail stays in the facade and reads via cvetService.find() so a domain used by the send path never becomes a cross-service dependency. Consumers (v1 SesQueryHandler, v2 SesController) are unchanged. * refactor(ses): extract SesPolicyService from SesService (strangler step 4) Fourth store-based domain split, showing the two-way relationship with the not-yet-extracted Identity domain: the facade keeps requireIdentityExists and runs it before delegating the v2 policy mutators, while deleteIdentity now calls policyService.deletePoliciesForIdentity — the monolith depending on the extracted service. Policy storage, the per-identity count limit, and name validation move into a new @ApplicationScoped SesPolicyService. Consumers (v1 SesQueryHandler, v2 SesController) are unchanged. * refactor(ses): extract SesContactService from SesService (strangler step 5) Fifth store-based domain split, the first multi-store one: one @ApplicationScoped service owns both the contact-list and contact stores plus their locks, collapsing two SesService constructor arguments into one. It also owns the list-management contact behaviour (auto-create-on-send, opt-out evaluation, unsubscribe); the send orchestration (collectListManagementOptOuts) stays in the facade and calls into the service, keeping the shared extractEmailAddress helper there. SesController's two ContactWithList/ContactsWithList type references move to the service; otherwise consumers are unchanged. * refactor(ses): extract SesSuppressionService from SesService (strangler step 6) Sixth store-based domain split, resolving the shared-helper deferral from the account step: account suppression and the suppression list share validateSuppressionReason, so both stores move together into one @ApplicationScoped SesSuppressionService where the helper becomes private. The send filters stay in the facade — getEffectiveSuppressedReasons reads a configuration set's options or falls back here, and collectSuppressedReasons/resolveSuppressionReason read entries back through findSuppressedDestination. Consumers (v1 SesQueryHandler, v2 SesController) are unchanged. * refactor(ses): fold VDM into SesAccountService (strangler step 7) VDM (accountVdmStore + the account-level VdmAttributes methods) entered the tree via the merged PutAccountVdmAttributes work and was left on the facade during the rebase. It is account-level with no shared helper, so move it into SesAccountService alongside the sending-enabled flag — where it was always meant to live. The facade delegates find/putAccountVdmAttributes; SesController's getAccount VdmAttributes rendering is unchanged. * refactor(ses): extract SesDedicatedIpService from SesService (strangler step 8) * refactor(ses): extract SesTemplateService from SesService (strangler step 9) Ninth store-based domain split: the email templates (templateStore) move to SesTemplateService, with the facade forwarding CRUD and the templated-send path reading via getTemplate. New facet: the shared tag validator stays on the facade — SesTemplateService.createTemplate calls the package-private SesService.validateTag, the same static-utility convention the controllers use for templateNameFromArn — and ARN-dispatched tagging reads/writes through the service's find/save so the facade keeps mergeTags without owning the key derivation. templateNameFromArn stays on the facade because external callers reference it statically. * refactor(ses): extract SesSentEmailService from SesService (strangler step 10) Tenth store-based domain split: the sent-email records (emailStore) move to SesSentEmailService. This is the send path's output sink — the facade keeps the whole send orchestration and only hands the finished record over through record(), while GetSendStatistics and the inspection endpoints read back through countInRegion / listAll / clear. getSentEmailCount keeps its existing region-wide (non-24h) count semantics verbatim. * refactor(ses): move SES tag validation into a shared helper Extract SesService.validateTag into a small SesTags helper so the extracted domain services validate tags without depending back on the facade, keeping them dependency-free leaves. Also tighten the template service's tagging test to assert the save() round-trip, not just find().
This commit is contained in:
1 parent
3374bfeb04
commit
3726b88fc9
27 files changed
+2653
-1273
No files matched your search
@@ -0,0 +1,70 @@
|
||||
package io.github.hectorvent.floci.services.ses;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.ses.model.AccountVdmAttributes;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Account-level SES settings, extracted from {@link SesService} as part of the store-based domain
|
||||
* split. Reached through the {@code SesService} facade, which delegates here.
|
||||
*
|
||||
* <p>Owns the account sending-enabled flag ({@code accountSettingsStore}) and the VDM (Virtual
|
||||
* Deliverability Manager) attributes ({@code accountVdmStore}). Account suppression is account-level
|
||||
* too, but it shares {@code validateSuppressionReason} with the suppression list, so it lives in
|
||||
* {@link SesSuppressionService} instead.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class SesAccountService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(SesAccountService.class);
|
||||
|
||||
private final StorageBackend<String, Boolean> accountSettingsStore;
|
||||
private final StorageBackend<String, AccountVdmAttributes> accountVdmStore;
|
||||
|
||||
@Inject
|
||||
public SesAccountService(StorageFactory storageFactory) {
|
||||
this.accountSettingsStore = storageFactory.create("ses", "ses-account-settings.json",
|
||||
new TypeReference<Map<String, Boolean>>() {});
|
||||
this.accountVdmStore = storageFactory.create("ses", "ses-account-vdm.json",
|
||||
new TypeReference<Map<String, AccountVdmAttributes>>() {});
|
||||
}
|
||||
|
||||
SesAccountService(StorageBackend<String, Boolean> accountSettingsStore,
|
||||
StorageBackend<String, AccountVdmAttributes> accountVdmStore) {
|
||||
this.accountSettingsStore = accountSettingsStore;
|
||||
this.accountVdmStore = accountVdmStore;
|
||||
}
|
||||
|
||||
public boolean isAccountSendingEnabled(String region) {
|
||||
return accountSettingsStore.get("sending::" + region).orElse(true);
|
||||
}
|
||||
|
||||
public void setAccountSendingEnabled(String region, boolean enabled) {
|
||||
accountSettingsStore.put("sending::" + region, enabled);
|
||||
LOG.infov("Updated account sending enabled for region {0}: {1}", region, enabled);
|
||||
}
|
||||
|
||||
// VDM (Virtual Deliverability Manager) is opt-in and per region: GetAccount omits VdmAttributes
|
||||
// entirely until PutAccountVdmAttributes is called for the region, so this returns empty when the
|
||||
// region was never configured. The whole tuple is stored under one region key so GetAccount never
|
||||
// observes a partially updated state.
|
||||
public Optional<AccountVdmAttributes> findAccountVdmAttributes(String region) {
|
||||
return accountVdmStore.get(accountVdmKey(region));
|
||||
}
|
||||
|
||||
public void putAccountVdmAttributes(String region, AccountVdmAttributes vdm) {
|
||||
accountVdmStore.put(accountVdmKey(region), vdm);
|
||||
LOG.infov("Updated account VDM attributes for region {0}: enabled={1}", region, vdm.vdmEnabled());
|
||||
}
|
||||
|
||||
private static String accountVdmKey(String region) {
|
||||
return "account-vdm::" + region;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,583 @@
|
||||
package io.github.hectorvent.floci.services.ses;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
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.Tag;
|
||||
import io.github.hectorvent.floci.services.ses.model.Topic;
|
||||
import io.github.hectorvent.floci.services.ses.model.TopicPreference;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Contact lists and contacts (the {@code contactListStore} + {@code contactStore}), extracted from
|
||||
* {@link SesService} as the fifth step of the store-based domain split.
|
||||
*
|
||||
* <p>New facet: a multi-store domain — one service owns both stores and the locks that serialize
|
||||
* them (contact create/update against contact-list deletion), collapsing two SesService constructor
|
||||
* arguments into one. It also owns the list-management contact behaviour used during a send
|
||||
* ({@link #getOrAutoCreateContact}, {@link #isListManagementOptedOut}, {@link #unsubscribeContact});
|
||||
* the facade's send orchestration ({@code collectListManagementOptOuts}) stays in {@link SesService}
|
||||
* and calls into this service, keeping the shared {@code extractEmailAddress} send helper there.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class SesContactService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(SesContactService.class);
|
||||
|
||||
private static final Set<String> SUBSCRIPTION_STATUSES = Set.of("OPT_IN", "OPT_OUT");
|
||||
private static final Pattern CONTACT_LIST_NAME_CHARS = Pattern.compile("^[A-Za-z0-9_-]{1,64}$");
|
||||
private static final Pattern EMAIL_PATTERN = Pattern.compile("^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$");
|
||||
private static final int MAX_TOPICS_PER_LIST = 20;
|
||||
private static final int MAX_DISPLAY_NAME_LENGTH = 128;
|
||||
private static final int MAX_LIST_DESCRIPTION_LENGTH = 500;
|
||||
|
||||
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 Clock clock;
|
||||
|
||||
@Inject
|
||||
public SesContactService(StorageFactory storageFactory, Clock clock) {
|
||||
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.clock = clock;
|
||||
}
|
||||
|
||||
SesContactService(StorageBackend<String, ContactList> contactListStore,
|
||||
StorageBackend<String, Contact> contactStore, Clock clock) {
|
||||
this.contactListStore = contactListStore;
|
||||
this.contactStore = contactStore;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
// ─────────────────────────── Contact lists ───────────────────────────
|
||||
|
||||
public ContactList createContactList(String name, String description, List<Topic> topics,
|
||||
List<Tag> tags, String region) {
|
||||
validateContactListInput(name, description, topics);
|
||||
ContactList list = new ContactList(name);
|
||||
list.setDescription(description);
|
||||
list.setTopics(topics);
|
||||
list.setTags(tags);
|
||||
Instant now = Instant.now();
|
||||
list.setCreatedTimestamp(now);
|
||||
list.setLastUpdatedTimestamp(now);
|
||||
// AWS allows at most one contact list per account per region (verified against real AWS).
|
||||
// A duplicate name hits this same limit before any "already exists" check, so
|
||||
// AlreadyExistsException is never reachable for contact lists. Lock only the check-then-put
|
||||
// so concurrent calls can't both observe an empty region; building and logging stay outside.
|
||||
synchronized (contactListCreateLock) {
|
||||
if (!listContactLists(region).isEmpty()) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"A maximum of 1 Lists allowed per account.", 400);
|
||||
}
|
||||
contactListStore.put(contactListKey(region, name), list);
|
||||
}
|
||||
LOG.infov("Created SES contact list: {0} in region {1}", name, region);
|
||||
return list;
|
||||
}
|
||||
|
||||
public ContactList getContactList(String name, String region) {
|
||||
return contactListStore.get(contactListKey(region, name))
|
||||
.orElseThrow(() -> contactListNotFound(name));
|
||||
}
|
||||
|
||||
public List<ContactList> listContactLists(String region) {
|
||||
String prefix = "contactList::" + region + "::";
|
||||
return contactListStore.scan(k -> k.startsWith(prefix)).stream()
|
||||
.sorted(Comparator.comparing(ContactList::getContactListName))
|
||||
.toList();
|
||||
}
|
||||
|
||||
public ContactList updateContactList(String name, String description, boolean descriptionPresent,
|
||||
List<Topic> topics, String region) {
|
||||
validateContactListInput(name, description, topics);
|
||||
String key = contactListKey(region, name);
|
||||
ContactList existing = contactListStore.get(key).orElseThrow(() -> contactListNotFound(name));
|
||||
if (topics != null) {
|
||||
existing.setTopics(topics);
|
||||
}
|
||||
if (descriptionPresent) {
|
||||
existing.setDescription(description);
|
||||
}
|
||||
existing.setLastUpdatedTimestamp(Instant.now());
|
||||
contactListStore.put(key, existing);
|
||||
LOG.infov("Updated SES contact list: {0} in region {1}", name, region);
|
||||
return existing;
|
||||
}
|
||||
|
||||
public void deleteContactList(String name, String region) {
|
||||
String key = contactListKey(region, 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);
|
||||
}
|
||||
}
|
||||
LOG.infov("Deleted SES contact list: {0} in region {1}", name, region);
|
||||
}
|
||||
|
||||
private static AwsException contactListNotFound(String name) {
|
||||
return new AwsException("NotFoundException",
|
||||
"List with name: " + name + " doesn't exist.", 404);
|
||||
}
|
||||
|
||||
// SES V2 surfaces missing/invalid input as Smithy validation errors. Field paths and the
|
||||
// enum value order are taken verbatim from real AWS.
|
||||
private static AwsException validationError(String fieldPath, String constraint) {
|
||||
return new AwsException("BadRequestException",
|
||||
"1 validation error detected: Value at '" + fieldPath
|
||||
+ "' failed to satisfy constraint: " + constraint, 400);
|
||||
}
|
||||
|
||||
private static void validateContactListName(String name) {
|
||||
if (name == null) {
|
||||
throw validationError("contactListName", "Member must not be null");
|
||||
}
|
||||
if (name.isBlank()) {
|
||||
throw new AwsException("BadRequestException", "ContactListName can't be blank.", 400);
|
||||
}
|
||||
if (!CONTACT_LIST_NAME_CHARS.matcher(name).matches()) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"ContactListName can contain up to 64 characters. Only alphanumeric characters, "
|
||||
+ "underscores(_) and hyphens(-) are allowed.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateDescription(String description) {
|
||||
if (description != null && description.length() > MAX_LIST_DESCRIPTION_LENGTH) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"List description can contain up to 500 characters.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
// Validates Create/Update input in the same two-phase order as real AWS (verified by probe):
|
||||
// protocol-layer (Smithy) checks across all fields first, then service-level constraints with
|
||||
// ContactListName ahead of topic/description constraints.
|
||||
private static void validateContactListInput(String name, String description, List<Topic> topics) {
|
||||
// Phase 1 — protocol-layer (Smithy) validation: null members and the subscription-status
|
||||
// enum. AWS reports these before any service-level constraint.
|
||||
if (name == null) {
|
||||
throw validationError("contactListName", "Member must not be null");
|
||||
}
|
||||
if (topics != null) {
|
||||
for (int i = 0; i < topics.size(); i++) {
|
||||
Topic t = topics.get(i);
|
||||
String member = "topics." + (i + 1) + ".member.";
|
||||
if (t.getTopicName() == null) {
|
||||
throw validationError(member + "topicName", "Member must not be null");
|
||||
}
|
||||
if (t.getDisplayName() == null) {
|
||||
throw validationError(member + "displayName", "Member must not be null");
|
||||
}
|
||||
if (t.getDefaultSubscriptionStatus() == null) {
|
||||
throw validationError(member + "defaultSubscriptionStatus", "Member must not be null");
|
||||
}
|
||||
if (!SUBSCRIPTION_STATUSES.contains(t.getDefaultSubscriptionStatus())) {
|
||||
throw validationError(member + "defaultSubscriptionStatus",
|
||||
"Member must satisfy enum value set: [OPT_OUT, OPT_IN]");
|
||||
}
|
||||
}
|
||||
}
|
||||
// Phase 2 — service-level constraints: ContactListName first, then topics, then description.
|
||||
if (name.isBlank()) {
|
||||
throw new AwsException("BadRequestException", "ContactListName can't be blank.", 400);
|
||||
}
|
||||
if (!CONTACT_LIST_NAME_CHARS.matcher(name).matches()) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"ContactListName can contain up to 64 characters. Only alphanumeric characters, "
|
||||
+ "underscores(_) and hyphens(-) are allowed.", 400);
|
||||
}
|
||||
if (topics != null) {
|
||||
if (topics.size() > MAX_TOPICS_PER_LIST) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"Maximum of <" + MAX_TOPICS_PER_LIST + "> topics allowed per ContactList", 400);
|
||||
}
|
||||
Set<String> seenNames = new HashSet<>();
|
||||
for (Topic t : topics) {
|
||||
if (t.getTopicName().isBlank()) {
|
||||
throw new AwsException("BadRequestException", "TopicName can't be blank.", 400);
|
||||
}
|
||||
if (!CONTACT_LIST_NAME_CHARS.matcher(t.getTopicName()).matches()) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"TopicName can contain up to 64 characters. Only alphanumeric characters, "
|
||||
+ "underscores(_) and hyphens(-) are allowed.", 400);
|
||||
}
|
||||
if (t.getDisplayName().length() > MAX_DISPLAY_NAME_LENGTH) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"Topic DisplayName can contain up to <" + MAX_DISPLAY_NAME_LENGTH
|
||||
+ "> characters.", 400);
|
||||
}
|
||||
if (!seenNames.add(t.getTopicName())) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"Duplicate topic names are not allowed within a List.", 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
validateDescription(description);
|
||||
}
|
||||
|
||||
private static String contactListKey(String region, String name) {
|
||||
// Validate in the key builder so Get/Update/Delete reject an invalid ContactListName with
|
||||
// the AWS validation error (400) rather than a 404, matching configSetKey. Verified
|
||||
// against real AWS: read/delete with an invalid name returns the same constraint message.
|
||||
validateContactListName(name);
|
||||
return "contactList::" + region + "::" + name;
|
||||
}
|
||||
|
||||
// ─────────────────────────── Contacts ───────────────────────────
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
// ──────────────── List-management contact behaviour (used by the send path) ────────────────
|
||||
|
||||
/**
|
||||
* Returns the contact for {@code email} in {@code list}, creating it automatically when absent —
|
||||
* AWS creates a contact on the list when {@code ListManagementOptions} names a recipient that is
|
||||
* not yet a contact. The auto-created contact has no explicit topic preferences (its effective
|
||||
* per-topic status derives from the list topic defaults) and is not unsubscribed. Creation runs
|
||||
* under {@code contactMutationLock} so a concurrent contact-list deletion can't orphan it.
|
||||
*/
|
||||
public Contact getOrAutoCreateContact(ContactList list, String email, String region) {
|
||||
String key = contactKey(region, list.getContactListName(), email);
|
||||
Contact existing = contactStore.get(key).orElse(null);
|
||||
if (existing != null) {
|
||||
return existing;
|
||||
}
|
||||
synchronized (contactMutationLock) {
|
||||
Contact raced = contactStore.get(key).orElse(null);
|
||||
if (raced != null) {
|
||||
return raced;
|
||||
}
|
||||
// Re-check the list under the lock so a concurrent deleteContactList (which purges the
|
||||
// list and its contacts under the same lock) can't be followed by this creating an
|
||||
// orphaned contact for a list that no longer exists.
|
||||
getContactList(list.getContactListName(), region);
|
||||
Contact contact = new Contact(email);
|
||||
Instant now = Instant.now(clock);
|
||||
contact.setCreatedTimestamp(now);
|
||||
contact.setLastUpdatedTimestamp(now);
|
||||
contactStore.put(key, contact);
|
||||
LOG.infov("Auto-created SES contact {0} in list {1} on send (region {2})",
|
||||
email, list.getContactListName(), region);
|
||||
return contact;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a contact is opted out for a list-managed send. A contact with {@code UnsubscribeAll}
|
||||
* is opted out of everything. When no topic is given, only {@code UnsubscribeAll} suppresses
|
||||
* (AWS documents suppression of whole-list unsubscribers). When a topic is given, an explicit
|
||||
* {@code OPT_OUT} preference for that topic suppresses; absent an explicit preference, the topic's
|
||||
* {@code DefaultSubscriptionStatus} is used — the default-status fallback at send time is not
|
||||
* documented by AWS but mirrors the effective-status model AWS uses for {@code ListContacts}.
|
||||
*/
|
||||
public boolean isListManagementOptedOut(Contact contact, ContactList list, String topicName) {
|
||||
if (contact.isUnsubscribeAll()) {
|
||||
return true;
|
||||
}
|
||||
if (topicName == null) {
|
||||
return false;
|
||||
}
|
||||
String explicit = explicitTopicStatus(contact, topicName);
|
||||
if (explicit != null) {
|
||||
return "OPT_OUT".equals(explicit);
|
||||
}
|
||||
return "OPT_OUT".equals(defaultTopicStatus(list, topicName));
|
||||
}
|
||||
|
||||
private static String explicitTopicStatus(Contact contact, String topicName) {
|
||||
if (contact.getTopicPreferences() == null) {
|
||||
return null;
|
||||
}
|
||||
for (TopicPreference pref : contact.getTopicPreferences()) {
|
||||
if (topicName.equals(pref.getTopicName())) {
|
||||
return pref.getSubscriptionStatus();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public String defaultTopicStatus(ContactList list, String topicName) {
|
||||
if (list.getTopics() == null) {
|
||||
return null;
|
||||
}
|
||||
for (Topic topic : list.getTopics()) {
|
||||
if (topicName.equals(topic.getTopicName())) {
|
||||
return topic.getDefaultSubscriptionStatus();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a list-management unsubscribe (the action behind the {@code /_aws/ses/unsubscribe}
|
||||
* link): with a topic, sets that topic's preference to {@code OPT_OUT}; without a topic,
|
||||
* unsubscribes the contact from the whole list ({@code UnsubscribeAll}). The contact is created
|
||||
* if it does not exist yet, consistent with send-time auto-creation. Runs under
|
||||
* {@code contactMutationLock} so a concurrent contact-list deletion can't orphan it.
|
||||
*/
|
||||
public void unsubscribeContact(String listName, String emailAddress, String topicName, String region) {
|
||||
validateEmailAddress(emailAddress);
|
||||
String effectiveTopic = (topicName == null || topicName.isBlank()) ? null : topicName;
|
||||
String key = contactKey(region, listName, emailAddress);
|
||||
synchronized (contactMutationLock) {
|
||||
ContactList list = getContactList(listName, region);
|
||||
if (effectiveTopic != null && defaultTopicStatus(list, effectiveTopic) == null) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"Topic " + effectiveTopic + " does not exist in contact list " + listName + ".", 400);
|
||||
}
|
||||
Contact contact = contactStore.get(key).orElseGet(() -> {
|
||||
Contact created = new Contact(emailAddress);
|
||||
created.setCreatedTimestamp(Instant.now(clock));
|
||||
return created;
|
||||
});
|
||||
if (effectiveTopic == null) {
|
||||
contact.setUnsubscribeAll(true);
|
||||
} else {
|
||||
setTopicPreference(contact, effectiveTopic, "OPT_OUT");
|
||||
}
|
||||
contact.setLastUpdatedTimestamp(Instant.now(clock));
|
||||
contactStore.put(key, contact);
|
||||
}
|
||||
LOG.infov("List-management unsubscribe: {0} from list {1} topic {2} (region {3})",
|
||||
emailAddress, listName, effectiveTopic == null ? "<all>" : effectiveTopic, region);
|
||||
}
|
||||
|
||||
private static void setTopicPreference(Contact contact, String topicName, String status) {
|
||||
// Copy into a fresh mutable list and set it back, so this works even if the contact's
|
||||
// preferences were stored as an unmodifiable list (setTopicPreferences keeps the list as-is).
|
||||
List<TopicPreference> prefs = new ArrayList<>(contact.getTopicPreferences());
|
||||
boolean found = false;
|
||||
for (TopicPreference pref : prefs) {
|
||||
if (topicName.equals(pref.getTopicName())) {
|
||||
pref.setSubscriptionStatus(status);
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
prefs.add(new TopicPreference(topicName, status));
|
||||
}
|
||||
contact.setTopicPreferences(prefs);
|
||||
}
|
||||
}
|
||||
@@ -1685,7 +1685,7 @@ public class SesController {
|
||||
if (body != null && !body.isBlank()) {
|
||||
requireJsonObject(objectMapper.readTree(body));
|
||||
}
|
||||
SesService.ContactsWithList listed = sesService.listContacts(contactListName, region);
|
||||
SesContactService.ContactsWithList listed = sesService.listContacts(contactListName, region);
|
||||
ObjectNode result = objectMapper.createObjectNode();
|
||||
ArrayNode arr = result.putArray("Contacts");
|
||||
for (Contact c : listed.contacts()) {
|
||||
@@ -1705,7 +1705,7 @@ public class SesController {
|
||||
@PathParam("contactListName") String contactListName,
|
||||
@PathParam("emailAddress") String emailAddress) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
SesService.ContactWithList result = sesService.getContact(contactListName, emailAddress, region);
|
||||
SesContactService.ContactWithList result = sesService.getContact(contactListName, emailAddress, region);
|
||||
return Response.ok(contactJson(result.contact(), result.list(), true)).build();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
package io.github.hectorvent.floci.services.ses;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.ses.model.CustomVerificationEmailTemplate;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Storage for custom verification email templates (the {@code cvetStore}), extracted from
|
||||
* {@link SesService} as the third step of the store-based domain split.
|
||||
*
|
||||
* <p>This owns only the persistence and the concurrency guard. The cross-domain parts stay in the
|
||||
* {@link SesService} facade, which orchestrates them: {@code validateCustomVerificationTemplate}
|
||||
* (its "From must be a verified identity" check reaches the Identity domain) runs in the facade
|
||||
* before create/update delegate here, and {@code sendCustomVerificationEmail} stays in the facade
|
||||
* and only reads a template through {@link #find}. This is the facade-as-coordinator model:
|
||||
* a domain used by the send path is not turned into a cross-service dependency.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class SesCvetService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(SesCvetService.class);
|
||||
|
||||
private final StorageBackend<String, CustomVerificationEmailTemplate> cvetStore;
|
||||
// Serializes custom-verification-template create/update/delete check-then-write so concurrent
|
||||
// creates for the same name can't both succeed and an update can't resurrect a concurrently
|
||||
// deleted template.
|
||||
private final Object cvetMutationLock = new Object();
|
||||
|
||||
@Inject
|
||||
public SesCvetService(StorageFactory storageFactory) {
|
||||
this.cvetStore = storageFactory.create("ses", "ses-custom-verification-templates.json",
|
||||
new TypeReference<Map<String, CustomVerificationEmailTemplate>>() {});
|
||||
}
|
||||
|
||||
SesCvetService(StorageBackend<String, CustomVerificationEmailTemplate> cvetStore) {
|
||||
this.cvetStore = cvetStore;
|
||||
}
|
||||
|
||||
public void createCustomVerificationEmailTemplate(CustomVerificationEmailTemplate template, String region) {
|
||||
String key = cvetKey(region, template.getTemplateName());
|
||||
// Lock only the check-then-put so concurrent creates for the same name can't both observe
|
||||
// the key as absent; the facade's validation and this logging stay outside the lock.
|
||||
synchronized (cvetMutationLock) {
|
||||
if (cvetStore.get(key).isPresent()) {
|
||||
// v1-native code (verified: CustomVerificationEmailTemplateAlreadyExists / 400);
|
||||
// remapV1Exception translates it to AlreadyExistsException / 400 for the v2 boundary.
|
||||
throw new AwsException("CustomVerificationEmailTemplateAlreadyExists",
|
||||
"Custom verification email template <" + template.getTemplateName() + "> already exists", 400);
|
||||
}
|
||||
cvetStore.put(key, template);
|
||||
}
|
||||
LOG.infov("Created custom verification email template {0} in region {1}",
|
||||
template.getTemplateName(), region);
|
||||
}
|
||||
|
||||
public CustomVerificationEmailTemplate getCustomVerificationEmailTemplate(String templateName, String region) {
|
||||
return cvetStore.get(cvetKey(region, templateName)).orElseThrow(() -> cvetNotFound(templateName));
|
||||
}
|
||||
|
||||
public List<CustomVerificationEmailTemplate> listCustomVerificationEmailTemplates(String region) {
|
||||
String prefix = "cvet::" + region + "::";
|
||||
return cvetStore.scan(k -> k.startsWith(prefix)).stream()
|
||||
.sorted(Comparator.comparing(CustomVerificationEmailTemplate::getTemplateName,
|
||||
Comparator.nullsFirst(Comparator.naturalOrder())))
|
||||
.toList();
|
||||
}
|
||||
|
||||
public void updateCustomVerificationEmailTemplate(CustomVerificationEmailTemplate template, String region) {
|
||||
String key = cvetKey(region, template.getTemplateName());
|
||||
// Guard the existence check and the put together so a concurrent delete can't slip between
|
||||
// them and have the update resurrect the just-deleted template.
|
||||
synchronized (cvetMutationLock) {
|
||||
if (cvetStore.get(key).isEmpty()) {
|
||||
throw cvetNotFound(template.getTemplateName());
|
||||
}
|
||||
cvetStore.put(key, template);
|
||||
}
|
||||
LOG.infov("Updated custom verification email template {0} in region {1}",
|
||||
template.getTemplateName(), region);
|
||||
}
|
||||
|
||||
public void deleteCustomVerificationEmailTemplate(String templateName, String region) {
|
||||
String key = cvetKey(region, templateName);
|
||||
// Guard the check-then-delete on the same lock as create/update so the three mutations
|
||||
// serialize against each other.
|
||||
synchronized (cvetMutationLock) {
|
||||
if (cvetStore.get(key).isEmpty()) {
|
||||
throw cvetNotFound(templateName);
|
||||
}
|
||||
cvetStore.delete(key);
|
||||
}
|
||||
LOG.infov("Deleted custom verification email template {0} in region {1}", templateName, region);
|
||||
}
|
||||
|
||||
/**
|
||||
* Looks up a template without throwing, so the facade's {@code sendCustomVerificationEmail} can
|
||||
* raise its own send-specific "does not exist" message rather than the CRUD one.
|
||||
*/
|
||||
public Optional<CustomVerificationEmailTemplate> find(String templateName, String region) {
|
||||
return cvetStore.get(cvetKey(region, templateName));
|
||||
}
|
||||
|
||||
private static AwsException cvetNotFound(String templateName) {
|
||||
// v1-native code (verified: CustomVerificationEmailTemplateDoesNotExist / 400).
|
||||
// SesController.remapV1Exception translates it to NotFoundException / 404 for the v2 boundary.
|
||||
return new AwsException("CustomVerificationEmailTemplateDoesNotExist",
|
||||
"Custom verification email template <" + templateName + "> does not exist", 400);
|
||||
}
|
||||
|
||||
private static String cvetKey(String region, String templateName) {
|
||||
return "cvet::" + region + "::" + templateName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package io.github.hectorvent.floci.services.ses;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.ses.model.DedicatedIpPool;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Dedicated IP pools (the {@code dedicatedIpPoolStore}), extracted from {@link SesService} as part of
|
||||
* the store-based domain split. A clean leaf reached through the {@code SesService}
|
||||
* facade, which delegates here; the facade's configuration-set delivery-options validation also
|
||||
* checks pool existence through {@link #dedicatedIpPoolExists}.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class SesDedicatedIpService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(SesDedicatedIpService.class);
|
||||
|
||||
private static final Set<String> SCALING_MODES = Set.of("STANDARD", "MANAGED");
|
||||
|
||||
private final StorageBackend<String, DedicatedIpPool> dedicatedIpPoolStore;
|
||||
|
||||
@Inject
|
||||
public SesDedicatedIpService(StorageFactory storageFactory) {
|
||||
this.dedicatedIpPoolStore = storageFactory.create("ses", "ses-dedicated-ip-pools.json",
|
||||
new TypeReference<Map<String, DedicatedIpPool>>() {});
|
||||
}
|
||||
|
||||
SesDedicatedIpService(StorageBackend<String, DedicatedIpPool> dedicatedIpPoolStore) {
|
||||
this.dedicatedIpPoolStore = dedicatedIpPoolStore;
|
||||
}
|
||||
|
||||
public DedicatedIpPool createDedicatedIpPool(String poolName, String scalingMode, String region) {
|
||||
if (poolName == null || poolName.isBlank()) {
|
||||
throw new AwsException("BadRequestException", "PoolName is required.", 400);
|
||||
}
|
||||
String effectiveScaling = (scalingMode == null || scalingMode.isBlank()) ? "STANDARD" : scalingMode;
|
||||
if (!SCALING_MODES.contains(effectiveScaling)) {
|
||||
throw new AwsException("BadRequestException", "The ScalingMode parameter is invalid.", 400);
|
||||
}
|
||||
String key = dedicatedIpPoolKey(region, poolName);
|
||||
if (dedicatedIpPoolStore.get(key).isPresent()) {
|
||||
throw new AwsException("AlreadyExistsException",
|
||||
"The pool <" + poolName + "> already exists.", 400);
|
||||
}
|
||||
DedicatedIpPool pool = new DedicatedIpPool(poolName, effectiveScaling);
|
||||
dedicatedIpPoolStore.put(key, pool);
|
||||
LOG.infov("Created SES dedicated IP pool: {0} in region {1}", poolName, region);
|
||||
return pool;
|
||||
}
|
||||
|
||||
public DedicatedIpPool getDedicatedIpPool(String poolName, String region) {
|
||||
return dedicatedIpPoolStore.get(dedicatedIpPoolKey(region, poolName))
|
||||
.orElseThrow(() -> new AwsException("NotFoundException",
|
||||
"The requested pool <" + poolName + "> does not exist.", 404));
|
||||
}
|
||||
|
||||
public boolean dedicatedIpPoolExists(String poolName, String region) {
|
||||
return dedicatedIpPoolStore.get(dedicatedIpPoolKey(region, poolName)).isPresent();
|
||||
}
|
||||
|
||||
public List<String> listDedicatedIpPools(String region) {
|
||||
String prefix = "dedicatedIpPool::" + region + "::";
|
||||
return dedicatedIpPoolStore.scan(k -> k.startsWith(prefix)).stream()
|
||||
.map(DedicatedIpPool::getPoolName)
|
||||
.sorted()
|
||||
.toList();
|
||||
}
|
||||
|
||||
public void deleteDedicatedIpPool(String poolName, String region) {
|
||||
String key = dedicatedIpPoolKey(region, poolName);
|
||||
if (dedicatedIpPoolStore.get(key).isEmpty()) {
|
||||
throw new AwsException("NotFoundException",
|
||||
"The requested pool <" + poolName + "> does not exist.", 404);
|
||||
}
|
||||
dedicatedIpPoolStore.delete(key);
|
||||
LOG.infov("Deleted SES dedicated IP pool: {0} in region {1}", poolName, region);
|
||||
}
|
||||
|
||||
private static String dedicatedIpPoolKey(String region, String name) {
|
||||
return "dedicatedIpPool::" + region + "::" + name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package io.github.hectorvent.floci.services.ses;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Identity sending-authorization policies (the {@code policyStore}), extracted from
|
||||
* {@link SesService} as the fourth step of the store-based domain split.
|
||||
*
|
||||
* <p>New facet vs the earlier steps: a two-way relationship with the (not-yet-extracted) Identity
|
||||
* domain. The facade keeps the identity-existence check ({@code requireIdentityExists} reads the
|
||||
* identity store) and runs it before delegating the v2 mutators here. In the other direction, the
|
||||
* facade's {@code deleteIdentity} calls {@link #deletePoliciesForIdentity} so an identity's policies
|
||||
* are purged with it — the monolith depending on the extracted service, which is how the pieces will
|
||||
* fit once Identity is itself extracted.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class SesPolicyService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(SesPolicyService.class);
|
||||
|
||||
static final int MAX_POLICIES_PER_IDENTITY = 20;
|
||||
private static final Pattern POLICY_NAME_CHARS = Pattern.compile("[A-Za-z0-9_-]+");
|
||||
|
||||
private final StorageBackend<String, String> policyStore;
|
||||
// Serializes the per-identity policy count check-then-put so concurrent creates can't both pass.
|
||||
private final Object policyMutationLock = new Object();
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public SesPolicyService(StorageFactory storageFactory, ObjectMapper objectMapper) {
|
||||
this.policyStore = storageFactory.create("ses", "ses-identity-policies.json",
|
||||
new TypeReference<Map<String, String>>() {});
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
SesPolicyService(StorageBackend<String, String> policyStore, ObjectMapper objectMapper) {
|
||||
this.policyStore = policyStore;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
// v1 PutIdentityPolicy: upsert (create or overwrite); v1 does not require the identity to exist.
|
||||
public void putIdentityPolicy(String identity, String policyName, String policy, String region) {
|
||||
validatePolicyName(policyName);
|
||||
String normalized = normalizePolicy(policy);
|
||||
String key = policyKey(region, identity, policyName);
|
||||
synchronized (policyMutationLock) {
|
||||
if (policyStore.get(key).isEmpty()) {
|
||||
enforcePolicyLimit(region, identity, false);
|
||||
}
|
||||
policyStore.put(key, normalized);
|
||||
}
|
||||
LOG.infov("SES PutIdentityPolicy: {0} on {1} (region {2})", policyName, identity, region);
|
||||
}
|
||||
|
||||
// v2 CreateEmailIdentityPolicy: fails if the name already exists. The identity-existence check is
|
||||
// done by the SesService facade before this is called.
|
||||
public void createEmailIdentityPolicy(String identity, String policyName, String policy, String region) {
|
||||
validatePolicyName(policyName);
|
||||
String normalized = normalizePolicy(policy);
|
||||
String key = policyKey(region, identity, policyName);
|
||||
synchronized (policyMutationLock) {
|
||||
if (policyStore.get(key).isPresent()) {
|
||||
throw new AwsException("AlreadyExistsException",
|
||||
"Policy <" + policyName + "> already exists", 400);
|
||||
}
|
||||
enforcePolicyLimit(region, identity, true);
|
||||
policyStore.put(key, normalized);
|
||||
}
|
||||
LOG.infov("SES v2 CreateEmailIdentityPolicy: {0} on {1} (region {2})", policyName, identity, region);
|
||||
}
|
||||
|
||||
// v2 UpdateEmailIdentityPolicy: fails if the name is missing. Identity check done by the facade.
|
||||
public void updateEmailIdentityPolicy(String identity, String policyName, String policy, String region) {
|
||||
validatePolicyName(policyName);
|
||||
String normalized = normalizePolicy(policy);
|
||||
String key = policyKey(region, identity, policyName);
|
||||
synchronized (policyMutationLock) {
|
||||
if (policyStore.get(key).isEmpty()) {
|
||||
throw policyNotFound(policyName);
|
||||
}
|
||||
policyStore.put(key, normalized);
|
||||
}
|
||||
LOG.infov("SES v2 UpdateEmailIdentityPolicy: {0} on {1} (region {2})", policyName, identity, region);
|
||||
}
|
||||
|
||||
// v1 GetIdentityPolicies: requested names only, missing silently omitted; no identity check.
|
||||
public Map<String, String> getIdentityPolicies(String identity, List<String> policyNames, String region) {
|
||||
Map<String, String> out = new LinkedHashMap<>();
|
||||
for (String name : policyNames) {
|
||||
policyStore.get(policyKey(region, identity, name)).ifPresent(doc -> out.put(name, doc));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// All policies for the identity, keyed by policy name.
|
||||
public Map<String, String> listAllPolicies(String identity, String region) {
|
||||
String prefix = policyPrefix(region, identity);
|
||||
Map<String, String> out = new LinkedHashMap<>();
|
||||
for (String key : policyStore.keys()) {
|
||||
if (key.startsWith(prefix)) {
|
||||
policyStore.get(key).ifPresent(doc -> out.put(key.substring(prefix.length()), doc));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// v1 ListIdentityPolicies: policy names (sorted); no identity check.
|
||||
public List<String> listIdentityPolicyNames(String identity, String region) {
|
||||
return listAllPolicies(identity, region).keySet().stream().sorted().toList();
|
||||
}
|
||||
|
||||
// v2 DeleteEmailIdentityPolicy: NotFound if the policy is missing. Identity check done by the facade.
|
||||
public void deleteEmailIdentityPolicy(String identity, String policyName, String region) {
|
||||
String key = policyKey(region, identity, policyName);
|
||||
synchronized (policyMutationLock) {
|
||||
if (policyStore.get(key).isEmpty()) {
|
||||
throw policyNotFound(policyName);
|
||||
}
|
||||
policyStore.delete(key);
|
||||
}
|
||||
LOG.infov("SES v2 DeleteEmailIdentityPolicy: {0} on {1} (region {2})", policyName, identity, region);
|
||||
}
|
||||
|
||||
// v1 DeleteIdentityPolicy: idempotent; no identity check, no error on a missing policy.
|
||||
public void deleteIdentityPolicy(String identity, String policyName, String region) {
|
||||
policyStore.delete(policyKey(region, identity, policyName));
|
||||
LOG.infov("SES DeleteIdentityPolicy: {0} on {1} (region {2})", policyName, identity, region);
|
||||
}
|
||||
|
||||
/**
|
||||
* Purges every policy attached to an identity. Called by the facade's {@code deleteIdentity} so
|
||||
* policies can't resurrect into a same-named identity recreated later (and the per-identity count
|
||||
* stays correct).
|
||||
*/
|
||||
public void deletePoliciesForIdentity(String identity, String region) {
|
||||
synchronized (policyMutationLock) {
|
||||
String prefix = policyPrefix(region, identity);
|
||||
for (String key : List.copyOf(policyStore.keys())) {
|
||||
if (key.startsWith(prefix)) {
|
||||
policyStore.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void enforcePolicyLimit(String region, String identity, boolean v2) {
|
||||
long count = policyStore.keys().stream()
|
||||
.filter(k -> k.startsWith(policyPrefix(region, identity))).count();
|
||||
if (count >= MAX_POLICIES_PER_IDENTITY) {
|
||||
String msg = "Number of policies for <" + identity
|
||||
+ "> exceeds max allowed number of policies per resource";
|
||||
throw new AwsException(v2 ? "LimitExceededException" : "InvalidParameterValue", msg, 400);
|
||||
}
|
||||
}
|
||||
|
||||
// Error codes are the v1 (Query) codes verified against AWS; the v2 controller remaps them to
|
||||
// BadRequestException. The messages are identical across v1 and v2.
|
||||
private static void validatePolicyName(String policyName) {
|
||||
if (policyName == null || policyName.isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", "PolicyName is required.", 400);
|
||||
}
|
||||
if (policyName.length() > 64) {
|
||||
throw new AwsException("ValidationError",
|
||||
"1 validation error detected: Value at 'policyName' failed to satisfy constraint: "
|
||||
+ "Member must have length less than or equal to 64", 400);
|
||||
}
|
||||
if (!POLICY_NAME_CHARS.matcher(policyName).matches()) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"PolicyName is invalid. Policy names must only include alpha-numeric characters, "
|
||||
+ "dashes, and underscores.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private String normalizePolicy(String policy) {
|
||||
if (policy == null || policy.isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", "Policy is required.", 400);
|
||||
}
|
||||
try {
|
||||
// AWS returns the policy with insignificant whitespace stripped; compact it to match.
|
||||
return objectMapper.readTree(policy).toString();
|
||||
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
|
||||
// Floci does not validate policy semantics; keep an unparseable document verbatim.
|
||||
LOG.debugv("Identity policy is not valid JSON, storing as-is: {0}", e.getMessage());
|
||||
return policy;
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException policyNotFound(String policyName) {
|
||||
return new AwsException("NotFoundException", "Policy <" + policyName + "> does not exist", 404);
|
||||
}
|
||||
|
||||
private static String policyKey(String region, String identity, String policyName) {
|
||||
return policyPrefix(region, identity) + policyName;
|
||||
}
|
||||
|
||||
private static String policyPrefix(String region, String identity) {
|
||||
return "policy::" + region + "::" + identity + "::";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package io.github.hectorvent.floci.services.ses;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.ses.model.ReceiptRuleSet;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Owns the SES receipt-rule-set domain (the {@code receiptRuleSetStore}). Extracted from
|
||||
* {@link SesService} as the first step of the store-based domain split: a leaf
|
||||
* domain with no cross-service coupling, reached only through the {@code SesService} facade, which
|
||||
* now delegates its {@code *ReceiptRuleSet*} methods here.
|
||||
*
|
||||
* <p>Floci has no inbound-mail endpoint, so receipt rule sets are stored inertly: a set never holds
|
||||
* any rules and routes no mail. They exist only so the management API round-trips (enough to unblock
|
||||
* tools such as Terraform that declare a rule set during bootstrap).
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class SesReceiptRuleService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(SesReceiptRuleService.class);
|
||||
|
||||
// These RuleSetName constraints are not in the botocore model: service-2.json (SES 2010-12-01)
|
||||
// declares ReceiptRuleSetName as a bare {"type": "string"} with no pattern or length. They were
|
||||
// established by probing real SES in us-west-2 via boto3 (2026-08): a character outside
|
||||
// ^[a-zA-Z0-9_.-]+$ is a Smithy ValidationError, and a name that is >64 chars or does not
|
||||
// start/end with an alphanumeric is a service-level "Not a valid ruleSetName" InvalidParameterValue.
|
||||
// Re-verify against live SES (not the model, which can't confirm it) if these ever need to change.
|
||||
private static final Pattern RULE_SET_NAME_CHARS = Pattern.compile("^[a-zA-Z0-9_.-]+$");
|
||||
|
||||
private final StorageBackend<String, ReceiptRuleSet> receiptRuleSetStore;
|
||||
// Serializes receipt-rule-set create (check-then-put) and set-active (clear-then-set) so the
|
||||
// one-active-per-region invariant and duplicate-name rejection hold under concurrency.
|
||||
private final Object receiptRuleSetLock = new Object();
|
||||
private final Clock clock;
|
||||
|
||||
@Inject
|
||||
public SesReceiptRuleService(StorageFactory storageFactory, Clock clock) {
|
||||
this.receiptRuleSetStore = storageFactory.create("ses", "ses-receipt-rule-sets.json",
|
||||
new TypeReference<Map<String, ReceiptRuleSet>>() {});
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
SesReceiptRuleService(StorageBackend<String, ReceiptRuleSet> receiptRuleSetStore, Clock clock) {
|
||||
this.receiptRuleSetStore = receiptRuleSetStore;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
public ReceiptRuleSet createReceiptRuleSet(String name, String region) {
|
||||
requireRuleSetName(name);
|
||||
String key = receiptRuleSetKey(region, name);
|
||||
ReceiptRuleSet ruleSet = new ReceiptRuleSet(name, Instant.now(clock));
|
||||
synchronized (receiptRuleSetLock) {
|
||||
if (receiptRuleSetStore.get(key).isPresent()) {
|
||||
throw new AwsException("AlreadyExists", "Rule set already exists: " + name, 400);
|
||||
}
|
||||
receiptRuleSetStore.put(key, ruleSet);
|
||||
}
|
||||
LOG.infov("Created SES receipt rule set: {0} in region {1}", name, region);
|
||||
return ruleSet;
|
||||
}
|
||||
|
||||
public ReceiptRuleSet describeReceiptRuleSet(String name, String region) {
|
||||
requireRuleSetName(name);
|
||||
return receiptRuleSetStore.get(receiptRuleSetKey(region, name))
|
||||
.orElseThrow(() -> ruleSetDoesNotExist(name));
|
||||
}
|
||||
|
||||
public List<ReceiptRuleSet> listReceiptRuleSets(String region) {
|
||||
String prefix = "receiptRuleSet::" + region + "::";
|
||||
List<ReceiptRuleSet> all = new ArrayList<>(receiptRuleSetStore.scan(k -> k.startsWith(prefix)));
|
||||
all.sort(Comparator.comparing(ReceiptRuleSet::getCreatedTimestamp,
|
||||
Comparator.nullsLast(Comparator.naturalOrder()))
|
||||
.thenComparing(ReceiptRuleSet::getName, Comparator.nullsLast(Comparator.naturalOrder())));
|
||||
return all;
|
||||
}
|
||||
|
||||
public void deleteReceiptRuleSet(String name, String region) {
|
||||
requireRuleSetName(name);
|
||||
// Hold the lock so the active-check-then-delete is atomic and a concurrent set-active/clear
|
||||
// (which scans and re-puts active sets) can't resurrect the rule set we just deleted.
|
||||
synchronized (receiptRuleSetLock) {
|
||||
ReceiptRuleSet existing = receiptRuleSetStore.get(receiptRuleSetKey(region, name)).orElse(null);
|
||||
if (existing != null && existing.isActive()) {
|
||||
// AWS rejects deleting the active rule set (verified: CannotDelete / 400).
|
||||
throw new AwsException("CannotDelete", "Cannot delete active rule set: " + name, 400);
|
||||
}
|
||||
// AWS is idempotent otherwise: deleting a non-existent rule set succeeds without error.
|
||||
receiptRuleSetStore.delete(receiptRuleSetKey(region, name));
|
||||
}
|
||||
LOG.infov("Deleted SES receipt rule set: {0} in region {1}", name, region);
|
||||
}
|
||||
|
||||
public void setActiveReceiptRuleSet(String name, String region) {
|
||||
// No RuleSetName clears the account's active rule set (matches AWS).
|
||||
boolean clearOnly = name == null || name.isBlank();
|
||||
if (!clearOnly) {
|
||||
requireRuleSetName(name);
|
||||
}
|
||||
synchronized (receiptRuleSetLock) {
|
||||
if (!clearOnly) {
|
||||
ReceiptRuleSet target = receiptRuleSetStore.get(receiptRuleSetKey(region, name))
|
||||
.orElseThrow(() -> ruleSetDoesNotExist(name));
|
||||
clearActiveReceiptRuleSet(region);
|
||||
target.setActive(true);
|
||||
receiptRuleSetStore.put(receiptRuleSetKey(region, name), target);
|
||||
} else {
|
||||
clearActiveReceiptRuleSet(region);
|
||||
}
|
||||
}
|
||||
if (clearOnly) {
|
||||
LOG.infov("Cleared active SES receipt rule set in region {0}", region);
|
||||
} else {
|
||||
LOG.infov("Set active SES receipt rule set: {0} in region {1}", name, region);
|
||||
}
|
||||
}
|
||||
|
||||
public ReceiptRuleSet describeActiveReceiptRuleSet(String region) {
|
||||
String prefix = "receiptRuleSet::" + region + "::";
|
||||
// Read under the lock so a concurrent set-active replacement (clear-then-set) can't expose its
|
||||
// intermediate no-active state — the reader sees either the old or the new active set.
|
||||
synchronized (receiptRuleSetLock) {
|
||||
return receiptRuleSetStore.scan(k -> k.startsWith(prefix)).stream()
|
||||
.filter(ReceiptRuleSet::isActive)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
}
|
||||
|
||||
private void clearActiveReceiptRuleSet(String region) {
|
||||
String prefix = "receiptRuleSet::" + region + "::";
|
||||
for (ReceiptRuleSet rs : receiptRuleSetStore.scan(k -> k.startsWith(prefix))) {
|
||||
if (rs.isActive()) {
|
||||
rs.setActive(false);
|
||||
receiptRuleSetStore.put(receiptRuleSetKey(region, rs.getName()), rs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireRuleSetName(String name) {
|
||||
if (name == null || name.isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", "RuleSetName is required.", 400);
|
||||
}
|
||||
if (!RULE_SET_NAME_CHARS.matcher(name).matches()) {
|
||||
throw new AwsException("ValidationError",
|
||||
"1 validation error detected: Value at 'ruleSetName' failed to satisfy constraint: "
|
||||
+ "Member must satisfy regular expression pattern: ^[a-zA-Z0-9_.-]+$", 400);
|
||||
}
|
||||
if (name.length() > 64
|
||||
|| !Character.isLetterOrDigit(name.charAt(0))
|
||||
|| !Character.isLetterOrDigit(name.charAt(name.length() - 1))) {
|
||||
throw new AwsException("InvalidParameterValue", "Not a valid ruleSetName: " + name, 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException ruleSetDoesNotExist(String name) {
|
||||
return new AwsException("RuleSetDoesNotExist", "Rule set does not exist: " + name, 400);
|
||||
}
|
||||
|
||||
private static String receiptRuleSetKey(String region, String name) {
|
||||
return "receiptRuleSet::" + region + "::" + name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package io.github.hectorvent.floci.services.ses;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.ses.model.SentEmail;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Sent-email records (the {@code emailStore}), extracted from {@link SesService} as part of the
|
||||
* store-based domain split. This is the send path's output sink: the facade's send methods keep the
|
||||
* whole send orchestration and only hand the finished record here through {@link #record}, while the
|
||||
* send-statistics and inspection endpoints read it back through {@link #countInRegion} /
|
||||
* {@link #listAll} / {@link #clear}. Nothing else reads the store, so it is a clean leaf.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class SesSentEmailService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(SesSentEmailService.class);
|
||||
|
||||
private final StorageBackend<String, SentEmail> emailStore;
|
||||
|
||||
@Inject
|
||||
public SesSentEmailService(StorageFactory storageFactory) {
|
||||
this.emailStore = storageFactory.create("ses", "ses-emails.json",
|
||||
new TypeReference<Map<String, SentEmail>>() {});
|
||||
}
|
||||
|
||||
SesSentEmailService(StorageBackend<String, SentEmail> emailStore) {
|
||||
this.emailStore = emailStore;
|
||||
}
|
||||
|
||||
public void record(String region, String messageId, SentEmail email) {
|
||||
emailStore.put(emailKey(region, messageId), email);
|
||||
}
|
||||
|
||||
public long countInRegion(String region) {
|
||||
String prefix = "email::" + region + "::";
|
||||
return emailStore.scan(k -> k.startsWith(prefix)).size();
|
||||
}
|
||||
|
||||
public List<SentEmail> listAll() {
|
||||
return emailStore.scan(k -> k.startsWith("email::"));
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
emailStore.clear();
|
||||
LOG.info("Cleared all SES emails");
|
||||
}
|
||||
|
||||
private static String emailKey(String region, String messageId) {
|
||||
return "email::" + region + "::" + messageId;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,236 @@
|
||||
package io.github.hectorvent.floci.services.ses;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.ses.model.AccountSuppressionAttributes;
|
||||
import io.github.hectorvent.floci.services.ses.model.SuppressedDestination;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Suppression: the account-level suppression attributes and the per-address suppression list,
|
||||
* extracted from {@link SesService} as the sixth step of the store-based domain split.
|
||||
*
|
||||
* <p>New facet: this resolves the shared-helper deferral called out in the account step. The
|
||||
* account-suppression and suppression-list sub-domains share {@code validateSuppressionReason}, so
|
||||
* rather than splitting one off, both stores move together into this service and the helper becomes
|
||||
* a private detail of it. The send path keeps its cross-domain orchestration
|
||||
* ({@code getEffectiveSuppressedReasons} reads a configuration set's options or falls back here;
|
||||
* {@code collectSuppressedReasons}/{@code resolveSuppressionReason} filter a send) in the
|
||||
* {@link SesService} facade, which reads entries back through {@link #findSuppressedDestination}.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class SesSuppressionService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(SesSuppressionService.class);
|
||||
|
||||
private final StorageBackend<String, SuppressedDestination> suppressionStore;
|
||||
private final StorageBackend<String, AccountSuppressionAttributes> accountSuppressionStore;
|
||||
|
||||
@Inject
|
||||
public SesSuppressionService(StorageFactory storageFactory) {
|
||||
this.suppressionStore = storageFactory.create("ses", "ses-suppression.json",
|
||||
new TypeReference<Map<String, SuppressedDestination>>() {});
|
||||
this.accountSuppressionStore = storageFactory.create("ses", "ses-account-suppression.json",
|
||||
new TypeReference<Map<String, AccountSuppressionAttributes>>() {});
|
||||
}
|
||||
|
||||
SesSuppressionService(StorageBackend<String, SuppressedDestination> suppressionStore,
|
||||
StorageBackend<String, AccountSuppressionAttributes> accountSuppressionStore) {
|
||||
this.suppressionStore = suppressionStore;
|
||||
this.accountSuppressionStore = accountSuppressionStore;
|
||||
}
|
||||
|
||||
// ──────────────────── Account-level suppression attributes ────────────────────
|
||||
|
||||
public AccountSuppressionAttributes getAccountSuppressionAttributes(String region) {
|
||||
return accountSuppressionStore.get(accountSuppressionKey(region))
|
||||
.orElseGet(SesSuppressionService::defaultAccountSuppressionAttributes);
|
||||
}
|
||||
|
||||
private static AccountSuppressionAttributes defaultAccountSuppressionAttributes() {
|
||||
// Fresh SES accounts default to auto-suppression on both BOUNCE and COMPLAINT;
|
||||
// an explicit PUT (including an empty list) overrides this.
|
||||
AccountSuppressionAttributes attrs = new AccountSuppressionAttributes();
|
||||
attrs.setSuppressedReasons(new ArrayList<>(List.of("BOUNCE", "COMPLAINT")));
|
||||
return attrs;
|
||||
}
|
||||
|
||||
public void putAccountSuppressionAttributes(String region, List<String> suppressedReasons) {
|
||||
List<String> sanitized = new ArrayList<>();
|
||||
if (suppressedReasons != null) {
|
||||
for (String r : suppressedReasons) {
|
||||
validateSuppressionReason(r, "suppressedReasons", true);
|
||||
sanitized.add(r);
|
||||
}
|
||||
}
|
||||
AccountSuppressionAttributes attrs = new AccountSuppressionAttributes();
|
||||
attrs.setSuppressedReasons(sanitized);
|
||||
accountSuppressionStore.put(accountSuppressionKey(region), attrs);
|
||||
LOG.infov("Updated account suppression attributes for region {0}: {1}", region, sanitized);
|
||||
}
|
||||
|
||||
private static String accountSuppressionKey(String region) {
|
||||
return "account-suppression::" + region;
|
||||
}
|
||||
|
||||
// ──────────────────────────── Suppression list ────────────────────────────
|
||||
|
||||
public void putSuppressedDestination(String region, String emailAddress, String reason) {
|
||||
String normalized = normalizeSuppressionEmail(emailAddress);
|
||||
validateSuppressionReason(reason, "reason", false);
|
||||
String key = suppressionKey(region, normalized);
|
||||
SuppressionMatch match = existingSuppressionMatch(region, emailAddress, normalized).orElse(null);
|
||||
SuppressedDestination entry = match != null ? match.entry() : new SuppressedDestination(normalized, reason);
|
||||
entry.setEmailAddress(normalized);
|
||||
entry.setReason(reason);
|
||||
entry.setLastUpdateTime(Instant.now());
|
||||
// Write the canonical key first, then drop a legacy key it migrated from,
|
||||
// so a failed write can't lose the entry. The legacy form was persisted by
|
||||
// a pre-canonicalization Floci (trim-only key); migrating it avoids leaving
|
||||
// a stuck duplicate after a re-PUT.
|
||||
suppressionStore.put(key, entry);
|
||||
if (match != null && !match.key().equals(key)) {
|
||||
suppressionStore.delete(match.key());
|
||||
}
|
||||
LOG.infov("Suppressed destination {0} in region {1} (reason={2})", normalized, region, reason);
|
||||
}
|
||||
|
||||
public SuppressedDestination getSuppressedDestination(String region, String emailAddress) {
|
||||
String normalized = normalizeSuppressionEmail(emailAddress);
|
||||
return existingSuppressionMatch(region, emailAddress, normalized)
|
||||
.map(SuppressionMatch::entry)
|
||||
.orElseThrow(() -> new AwsException("NotFoundException",
|
||||
"Email address " + normalized + " does not exist on your suppression list.",
|
||||
404));
|
||||
}
|
||||
|
||||
public void deleteSuppressedDestination(String region, String emailAddress) {
|
||||
String normalized = normalizeSuppressionEmail(emailAddress);
|
||||
SuppressionMatch match = existingSuppressionMatch(region, emailAddress, normalized)
|
||||
.orElseThrow(() -> new AwsException("NotFoundException",
|
||||
"Email address " + normalized + " does not exist on your suppression list.",
|
||||
404));
|
||||
suppressionStore.delete(match.key());
|
||||
LOG.infov("Removed suppression entry for {0} in region {1}", normalized, region);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a suppression entry without throwing, so the facade's send-path filters
|
||||
* ({@code collectSuppressedReasons} / {@code resolveSuppressionReason}) can look one up by raw
|
||||
* address and share this service's normalization and legacy-key fallback.
|
||||
*/
|
||||
public Optional<SuppressedDestination> findSuppressedDestination(String region, String rawEmail) {
|
||||
if (rawEmail == null || rawEmail.isBlank()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String normalized = normalizeSuppressionEmail(rawEmail);
|
||||
return existingSuppressionMatch(region, rawEmail, normalized).map(SuppressionMatch::entry);
|
||||
}
|
||||
|
||||
/** A suppression entry together with the storage key it currently lives under. */
|
||||
private record SuppressionMatch(String key, SuppressedDestination entry) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a suppression entry by its canonical (domain-lower-cased) key, falling
|
||||
* back to the legacy raw-trimmed key used by a pre-canonicalization Floci. Returns
|
||||
* the entry and the key it was found under in a single read per candidate, so
|
||||
* callers don't re-fetch the store.
|
||||
*/
|
||||
private Optional<SuppressionMatch> existingSuppressionMatch(String region, String rawEmail, String normalized) {
|
||||
String canonical = suppressionKey(region, normalized);
|
||||
Optional<SuppressedDestination> hit = suppressionStore.get(canonical);
|
||||
if (hit.isPresent()) {
|
||||
return Optional.of(new SuppressionMatch(canonical, hit.get()));
|
||||
}
|
||||
String legacy = suppressionKey(region, rawEmail.trim());
|
||||
if (!legacy.equals(canonical)) {
|
||||
Optional<SuppressedDestination> legacyHit = suppressionStore.get(legacy);
|
||||
if (legacyHit.isPresent()) {
|
||||
return Optional.of(new SuppressionMatch(legacy, legacyHit.get()));
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public List<SuppressedDestination> listSuppressedDestinations(String region, List<String> reasonFilters) {
|
||||
Set<String> filters = new HashSet<>();
|
||||
if (reasonFilters != null) {
|
||||
for (String r : reasonFilters) {
|
||||
if (r != null && !r.isBlank()) {
|
||||
validateSuppressionReason(r, "reasons", true);
|
||||
filters.add(r);
|
||||
}
|
||||
}
|
||||
}
|
||||
String prefix = "suppression::" + region + "::";
|
||||
List<SuppressedDestination> all = new ArrayList<>(suppressionStore.scan(k -> k.startsWith(prefix)));
|
||||
all.sort(Comparator.comparing(SuppressedDestination::getLastUpdateTime,
|
||||
Comparator.nullsLast(Comparator.naturalOrder()))
|
||||
.thenComparing(SuppressedDestination::getEmailAddress,
|
||||
Comparator.nullsLast(Comparator.naturalOrder())));
|
||||
if (filters.isEmpty()) {
|
||||
return all;
|
||||
}
|
||||
return all.stream()
|
||||
.filter(s -> filters.contains(s.getReason()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static String suppressionKey(String region, String emailAddress) {
|
||||
return "suppression::" + region + "::" + emailAddress;
|
||||
}
|
||||
|
||||
private static String normalizeSuppressionEmail(String emailAddress) {
|
||||
if (emailAddress == null || emailAddress.isBlank()) {
|
||||
throw new AwsException("BadRequestException", "EmailAddress is required.", 400);
|
||||
}
|
||||
// AWS trims the EmailAddress and canonicalizes only the domain to lower
|
||||
// case; the local-part keeps its case. Verified against real AWS SES V2
|
||||
// (2026-06-15): `Foo@Example.COM` and `Foo@example.com` collapse to one
|
||||
// suppression entry (`Foo@example.com`), but `Foo@x` and `foo@x` are two
|
||||
// distinct entries. Lower-casing the whole address would wrongly merge
|
||||
// local-part variants and alter the stored value on read-back.
|
||||
// Locale.ROOT avoids the JVM-locale Turkish-i pitfall.
|
||||
String trimmed = emailAddress.trim();
|
||||
int at = trimmed.lastIndexOf('@');
|
||||
if (at < 0) {
|
||||
return trimmed;
|
||||
}
|
||||
return trimmed.substring(0, at) + "@" + trimmed.substring(at + 1).toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validation message used by PutAccountSuppressionAttributes, PutSuppressedDestination, and
|
||||
* ListSuppressedDestinations — all three return the AWS "1 validation error detected: Value at
|
||||
* '<fieldName>' failed to satisfy constraint: ..." V1-style nested message verbatim. (Verified
|
||||
* against real AWS V2 SES on 2026-06-03.) The {@code nested} flag controls whether the inner enum
|
||||
* constraint is wrapped in {@code Member must satisfy constraint: [...]} — PutSuppressedDestination
|
||||
* (single Reason field) returns the unwrapped form; the two list-bearing APIs return the wrapped
|
||||
* form. Shared by the two sub-domains above, which is why they were extracted together.
|
||||
*/
|
||||
private static void validateSuppressionReason(String reason, String fieldName, boolean nested) {
|
||||
if (reason == null || (!"BOUNCE".equals(reason) && !"COMPLAINT".equals(reason))) {
|
||||
String constraint = nested
|
||||
? "Member must satisfy constraint: [Member must satisfy enum value set: [BOUNCE, COMPLAINT]]"
|
||||
: "Member must satisfy enum value set: [BOUNCE, COMPLAINT]";
|
||||
throw new AwsException("BadRequestException",
|
||||
"1 validation error detected: Value at '" + fieldName + "' failed to satisfy constraint: "
|
||||
+ constraint, 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package io.github.hectorvent.floci.services.ses;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.ses.model.Tag;
|
||||
|
||||
/**
|
||||
* Shared SES resource-tag validation. Lives outside the facade so the extracted domain services can
|
||||
* validate tags without depending back on {@link SesService}.
|
||||
*/
|
||||
final class SesTags {
|
||||
|
||||
private SesTags() {}
|
||||
|
||||
static void validate(Tag tag) {
|
||||
if (tag == null) {
|
||||
throw new AwsException("InvalidParameterValue", "Tag must not be null.", 400);
|
||||
}
|
||||
String key = tag.key();
|
||||
if (key == null || key.isEmpty()) {
|
||||
throw new AwsException("InvalidParameterValue", "Tag Key is required.", 400);
|
||||
}
|
||||
if (key.length() > 128) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Tag Key must be 1-128 characters.", 400);
|
||||
}
|
||||
String value = tag.value();
|
||||
if (value != null && value.length() > 256) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Tag Value must be 0-256 characters.", 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package io.github.hectorvent.floci.services.ses;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.ses.model.EmailTemplate;
|
||||
import io.github.hectorvent.floci.services.ses.model.Tag;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Email templates (the {@code templateStore}), extracted from {@link SesService} as part of the
|
||||
* store-based domain split. Reached through the {@code SesService} facade, which delegates the CRUD
|
||||
* here; the facade's templated-send path reads templates back through {@link #getTemplate}, and its
|
||||
* ARN-dispatched tagging reads/writes through {@link #find} / {@link #save}.
|
||||
*
|
||||
* <p>Tag validation is a shared cross-resource concern, so {@code createTemplate} calls
|
||||
* {@link SesTags#validate} rather than depending back on the facade. The template ARN parser
|
||||
* ({@code SesService.templateNameFromArn}) stays on the facade because external callers reference it
|
||||
* statically.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class SesTemplateService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(SesTemplateService.class);
|
||||
|
||||
private final StorageBackend<String, EmailTemplate> templateStore;
|
||||
|
||||
@Inject
|
||||
public SesTemplateService(StorageFactory storageFactory) {
|
||||
this.templateStore = storageFactory.create("ses", "ses-templates.json",
|
||||
new TypeReference<Map<String, EmailTemplate>>() {});
|
||||
}
|
||||
|
||||
SesTemplateService(StorageBackend<String, EmailTemplate> templateStore) {
|
||||
this.templateStore = templateStore;
|
||||
}
|
||||
|
||||
public EmailTemplate createTemplate(EmailTemplate template, String region) {
|
||||
validateTemplate(template);
|
||||
if (template.getTags() != null) {
|
||||
for (Tag tag : template.getTags()) {
|
||||
SesTags.validate(tag);
|
||||
}
|
||||
}
|
||||
String key = templateKey(region, template.getTemplateName());
|
||||
if (templateStore.get(key).isPresent()) {
|
||||
throw new AwsException("AlreadyExists",
|
||||
"Template " + template.getTemplateName() + " already exists.", 400);
|
||||
}
|
||||
Instant now = Instant.now();
|
||||
template.setCreatedTimestamp(now);
|
||||
template.setLastUpdatedTimestamp(now);
|
||||
templateStore.put(key, template);
|
||||
LOG.infov("Created SES template: {0} in region {1}", template.getTemplateName(), region);
|
||||
return template;
|
||||
}
|
||||
|
||||
public EmailTemplate getTemplate(String templateName, String region) {
|
||||
return templateStore.get(templateKey(region, templateName))
|
||||
.orElseThrow(() -> new AwsException("TemplateDoesNotExist",
|
||||
"Template " + templateName + " does not exist.", 400));
|
||||
}
|
||||
|
||||
public EmailTemplate updateTemplate(EmailTemplate template, String region) {
|
||||
validateTemplate(template);
|
||||
String key = templateKey(region, template.getTemplateName());
|
||||
EmailTemplate existing = templateStore.get(key)
|
||||
.orElseThrow(() -> new AwsException("TemplateDoesNotExist",
|
||||
"Template " + template.getTemplateName() + " does not exist.", 400));
|
||||
template.setCreatedTimestamp(existing.getCreatedTimestamp());
|
||||
template.setLastUpdatedTimestamp(Instant.now());
|
||||
// Tags are managed exclusively via Tag/UntagResource — preserve them on update.
|
||||
template.setTags(existing.getTags());
|
||||
templateStore.put(key, template);
|
||||
LOG.infov("Updated SES template: {0} in region {1}", template.getTemplateName(), region);
|
||||
return template;
|
||||
}
|
||||
|
||||
public void deleteTemplate(String templateName, String region) {
|
||||
String key = templateKey(region, templateName);
|
||||
if (templateStore.get(key).isEmpty()) {
|
||||
throw new AwsException("TemplateDoesNotExist",
|
||||
"Template " + templateName + " does not exist.", 400);
|
||||
}
|
||||
templateStore.delete(key);
|
||||
LOG.infov("Deleted SES template: {0} in region {1}", templateName, region);
|
||||
}
|
||||
|
||||
public List<EmailTemplate> listTemplates(String region) {
|
||||
String prefix = "template::" + region + "::";
|
||||
List<EmailTemplate> all = new ArrayList<>(templateStore.scan(k -> k.startsWith(prefix)));
|
||||
all.sort(Comparator.comparing(EmailTemplate::getCreatedTimestamp,
|
||||
Comparator.nullsLast(Comparator.naturalOrder()))
|
||||
.thenComparing(EmailTemplate::getTemplateName,
|
||||
Comparator.nullsLast(Comparator.naturalOrder())));
|
||||
return all;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a template without throwing, so the facade's ARN-dispatched tagging can look one up by
|
||||
* name and reuse this service's key derivation.
|
||||
*/
|
||||
public Optional<EmailTemplate> find(String templateName, String region) {
|
||||
return templateStore.get(templateKey(region, templateName));
|
||||
}
|
||||
|
||||
/**
|
||||
* Persists a template under its canonical key, so the facade's tagging can write the merged tags
|
||||
* back without owning the key derivation.
|
||||
*/
|
||||
public void save(EmailTemplate template, String region) {
|
||||
templateStore.put(templateKey(region, template.getTemplateName()), template);
|
||||
}
|
||||
|
||||
private static void validateTemplate(EmailTemplate template) {
|
||||
if (template == null) {
|
||||
throw new AwsException("InvalidTemplate", "Template is required.", 400);
|
||||
}
|
||||
validateTemplateName(template.getTemplateName());
|
||||
boolean hasSubject = template.getSubject() != null && !template.getSubject().isBlank();
|
||||
boolean hasText = template.getTextPart() != null && !template.getTextPart().isBlank();
|
||||
boolean hasHtml = template.getHtmlPart() != null && !template.getHtmlPart().isBlank();
|
||||
if (!hasSubject && !hasText && !hasHtml) {
|
||||
throw new AwsException("InvalidTemplate",
|
||||
"Template must have at least a subject, text, or html part.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateTemplateName(String templateName) {
|
||||
if (templateName == null || templateName.isBlank()) {
|
||||
throw new AwsException("InvalidTemplate", "TemplateName is required.", 400);
|
||||
}
|
||||
if (Character.isWhitespace(templateName.charAt(0))
|
||||
|| Character.isWhitespace(templateName.charAt(templateName.length() - 1))) {
|
||||
throw new AwsException("InvalidTemplate",
|
||||
"TemplateName must not contain leading or trailing whitespace.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static String templateKey(String region, String templateName) {
|
||||
validateTemplateName(templateName);
|
||||
return "template::" + region + "::" + templateName;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user