feat(ses): add v2 BatchGetMetricData (#4302)

Aggregates the per-recipient timelines already stored at send time, so the
batch metrics and GetMessageInsights cannot disagree about what a send
produced. Buckets are whole UTC days, the series is sparse rather than zero
filled, the end of the range is exclusive, and counting is per recipient.

SentEmail gains the configuration set the send resolved to, which the
CONFIGURATION_SET dimension filters on. The VDM gate moves into a shared
SesVdmGate so the two gated operations keep one copy of the probed message.

Metrics that need a real mailbox to act stay empty, as does TRANSIENT_BOUNCE,
since every bounce Floci derives is permanent.
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-09-24 08:34:15 -04:00
1 parent 55f9ff5a8b
commit 34be03b334
21 files changed
+1718 -82

No files matched your search

@@ -41,6 +41,7 @@ import io.github.hectorvent.floci.services.ses.SesDedicatedIpController;
import io.github.hectorvent.floci.services.ses.SesIdentityController;
import io.github.hectorvent.floci.services.ses.SesImportJobController;
import io.github.hectorvent.floci.services.ses.SesInsightsController;
import io.github.hectorvent.floci.services.ses.SesMetricsController;
import io.github.hectorvent.floci.services.ses.SesSendController;
import io.github.hectorvent.floci.services.ses.SesSuppressionController;
import io.github.hectorvent.floci.services.ses.SesTagController;
@@ -306,7 +307,8 @@ public class ResolvedServiceCatalog {
Set.of(SesAccountController.class, SesConfigurationSetController.class,
SesContactController.class, SesCvetController.class,
SesDedicatedIpController.class, SesIdentityController.class,
SesInsightsController.class, SesSendController.class,
SesInsightsController.class, SesMetricsController.class,
SesSendController.class,
SesSuppressionController.class, SesTagController.class,
SesTemplateController.class, SesImportJobController.class,
SesTenantController.class)),
@@ -79,6 +79,7 @@ public final class CognitoMessageDispatcher {
List.of(), // emailTags
List.of(), // additionalHeaders
null, // listManagement
null, // tenantName
DEFAULT_REGION
);
} else if ("SMS".equalsIgnoreCase(medium) && phone != null) {
@@ -85,6 +85,15 @@ public class SesAccountService {
LOG.infov("Updated account VDM attributes for region {0}: enabled={1}", region, vdm.vdmEnabled());
}
/** The probe-confirmed gate the VDM-only operations check before reading the request. */
public void requireVdmEnabled(String region) {
Optional<AccountVdmAttributes> vdm = findAccountVdmAttributes(region);
if (vdm.isEmpty() || !vdm.get().vdmEnabled()) {
throw new AwsException("NotFoundException",
"To use this feature you must enable Virtual Deliverability Manager", 404);
}
}
private static String accountVdmKey(String region) {
return "account-vdm::" + region;
}
@@ -5,7 +5,6 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.ses.model.AccountVdmAttributes;
import io.github.hectorvent.floci.services.ses.model.EmailInsights;
import io.github.hectorvent.floci.services.ses.model.InsightsBounce;
import io.github.hectorvent.floci.services.ses.model.InsightsComplaint;
@@ -25,7 +24,6 @@ import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.util.List;
import java.util.Optional;
/**
* SES V2 message insights ({@code /v2/email/insights/{MessageId}/}), the read side of the
@@ -41,9 +39,6 @@ import java.util.Optional;
@Consumes(MediaType.APPLICATION_JSON)
public class SesInsightsController {
private static final String VDM_DISABLED_MESSAGE =
"To use this feature you must enable Virtual Deliverability Manager";
private final SesSentEmailService sentEmailService;
private final SesAccountService accountService;
private final RegionResolver regionResolver;
@@ -63,7 +58,7 @@ public class SesInsightsController {
public Response getMessageInsights(@Context HttpHeaders headers,
@PathParam("messageId") String messageId) {
String region = regionResolver.resolveRegion(headers);
requireVdmEnabled(region);
accountService.requireVdmEnabled(region);
SentEmail email = sentEmailService.find(region, messageId)
.orElseThrow(() -> new AwsException("NotFoundException",
"Message <" + messageId + "> not found for account <"
@@ -71,13 +66,6 @@ public class SesInsightsController {
return Response.ok(render(email)).build();
}
private void requireVdmEnabled(String region) {
Optional<AccountVdmAttributes> vdm = accountService.findAccountVdmAttributes(region);
if (vdm.isEmpty() || !vdm.get().vdmEnabled()) {
throw new AwsException("NotFoundException", VDM_DISABLED_MESSAGE, 404);
}
}
private ObjectNode render(SentEmail email) {
ObjectNode result = objectMapper.createObjectNode();
result.put("MessageId", email.getMessageId());
@@ -0,0 +1,190 @@
package io.github.hectorvent.floci.services.ses;
import io.github.hectorvent.floci.services.ses.model.EmailInsights;
import io.github.hectorvent.floci.services.ses.model.InsightsBounce;
import io.github.hectorvent.floci.services.ses.model.InsightsEvent;
import io.github.hectorvent.floci.services.ses.model.InsightsEventDetails;
import io.github.hectorvent.floci.services.ses.model.SentEmail;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/**
* Aggregates the stored per-recipient timelines into the daily counts {@code BatchGetMetricData}
* serves. The timelines are the ones {@link SesMessageInsights} derives at send time, so the two
* operations cannot disagree about what a send produced.
*
* <p>Probe-confirmed against real SES (2026-09-23, us-east-1): buckets are whole UTC days, the
* series is sparse rather than zero filled (a day with no data is simply absent), and the end of
* the requested range is exclusive, so a range ending at midnight omits that day.
*
* <p>Floci reports only what a send without a real recipient can produce. OPEN, CLICK,
* DELIVERY_OPEN and DELIVERY_CLICK need a mailbox to act, so they always come back empty; the
* probed account returned empty series for those metrics too. Every bounce Floci derives is
* PERMANENT, so TRANSIENT_BOUNCE is likewise always empty.
*/
final class SesMetricData {
static final Set<String> METRICS = Set.of(
"SEND", "COMPLAINT", "PERMANENT_BOUNCE", "TRANSIENT_BOUNCE", "OPEN", "CLICK",
"DELIVERY", "DELIVERY_OPEN", "DELIVERY_CLICK", "DELIVERY_COMPLAINT");
static final Set<String> DIMENSION_NAMES =
Set.of("EMAIL_IDENTITY", "CONFIGURATION_SET", "ISP", "TENANT_NAME");
private static final String EMAIL_IDENTITY = "EMAIL_IDENTITY";
private static final String CONFIGURATION_SET = "CONFIGURATION_SET";
private static final String ISP = "ISP";
private static final String TENANT_NAME = "TENANT_NAME";
private SesMetricData() {}
/**
* One query from the batch, already validated by the controller.
*/
record Query(String id, String metric, Map<String, String> dimensions,
Instant startDate, Instant endDate) {
Query {
dimensions = dimensions == null ? Map.of() : Map.copyOf(dimensions);
}
}
/**
* The counts for one query, in ascending bucket order. Both lists have the same length, and
* both are empty when nothing matched.
*/
record Series(List<Instant> timestamps, List<Long> values) {
static final Series EMPTY = new Series(List.of(), List.of());
}
static Series aggregate(List<SentEmail> emails, Query query) {
Map<Instant, Long> buckets = new TreeMap<>();
for (SentEmail email : emails) {
if (!matchesMessageDimensions(email, query.dimensions())) {
continue;
}
for (EmailInsights recipient : orEmpty(email.getInsights())) {
if (!matchesIsp(recipient, query.dimensions())) {
continue;
}
countRecipient(recipient, query, buckets);
}
}
if (buckets.isEmpty()) {
return Series.EMPTY;
}
List<Instant> timestamps = new ArrayList<>(buckets.size());
List<Long> values = new ArrayList<>(buckets.size());
for (Map.Entry<Instant, Long> bucket : buckets.entrySet()) {
timestamps.add(bucket.getKey());
values.add(bucket.getValue());
}
return new Series(timestamps, values);
}
private static void countRecipient(EmailInsights recipient, Query query,
Map<Instant, Long> buckets) {
if ("DELIVERY_COMPLAINT".equals(query.metric())) {
countDeliveredComplaint(recipient, query, buckets);
return;
}
for (InsightsEvent event : orEmpty(recipient.events())) {
if (counts(event, query.metric())) {
add(buckets, event.timestamp(), query);
}
}
}
/**
* DELIVERY_COMPLAINT is a complaint about a message that was delivered, so it counts the
* recipient once, in the bucket the complaint itself falls in.
*/
private static void countDeliveredComplaint(EmailInsights recipient, Query query,
Map<Instant, Long> buckets) {
boolean delivered = false;
for (InsightsEvent event : orEmpty(recipient.events())) {
if ("DELIVERY".equals(event.type())) {
delivered = true;
} else if (delivered && "COMPLAINT".equals(event.type())) {
add(buckets, event.timestamp(), query);
return;
}
}
}
private static boolean counts(InsightsEvent event, String metric) {
String type = event.type();
if (type == null) {
return false;
}
return switch (metric) {
case "SEND", "DELIVERY", "COMPLAINT" -> type.equals(metric);
case "PERMANENT_BOUNCE" -> "BOUNCE".equals(type) && isBounceType(event, "PERMANENT");
case "TRANSIENT_BOUNCE" -> "BOUNCE".equals(type) && isBounceType(event, "TRANSIENT");
default -> false;
};
}
private static boolean isBounceType(InsightsEvent event, String bounceType) {
InsightsEventDetails details = event.details();
if (details == null) {
return false;
}
InsightsBounce bounce = details.bounce();
return bounce != null && bounceType.equals(bounce.bounceType());
}
private static void add(Map<Instant, Long> buckets, Instant timestamp, Query query) {
if (timestamp == null || timestamp.isBefore(query.startDate())
|| !timestamp.isBefore(query.endDate())) {
return;
}
buckets.merge(timestamp.truncatedTo(ChronoUnit.DAYS), 1L, Long::sum);
}
private static boolean matchesMessageDimensions(SentEmail email, Map<String, String> dimensions) {
String identity = dimensions.get(EMAIL_IDENTITY);
if (identity != null && !matchesIdentity(email.getSource(), identity)) {
return false;
}
String configurationSet = dimensions.get(CONFIGURATION_SET);
if (configurationSet != null && !configurationSet.equals(email.getConfigurationSetName())) {
return false;
}
String tenant = dimensions.get(TENANT_NAME);
return tenant == null || tenant.equals(email.getTenantName());
}
/**
* An identity dimension names either the sending address or its domain, the way the identity
* itself can be either; the probe filtered a domain and matched sends from an address in it.
*/
private static boolean matchesIdentity(String source, String identity) {
if (source == null) {
return false;
}
// A stored Source can carry display-name syntax, so compare the bare mailbox.
String address = SesService.extractEmailAddress(source);
if (address.equalsIgnoreCase(identity)) {
return true;
}
int at = address.lastIndexOf('@');
return at >= 0 && address.substring(at + 1).equalsIgnoreCase(identity);
}
private static boolean matchesIsp(EmailInsights recipient, Map<String, String> dimensions) {
String isp = dimensions.get(ISP);
return isp == null || isp.equals(recipient.isp());
}
private static <T> List<T> orEmpty(List<T> values) {
return values == null ? List.of() : values;
}
}
@@ -0,0 +1,388 @@
package io.github.hectorvent.floci.services.ses;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.ses.model.SentEmail;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.time.DateTimeException;
import java.time.Duration;
import java.time.Instant;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import static io.github.hectorvent.floci.services.ses.SesV2Json.readOptionBody;
import static io.github.hectorvent.floci.services.ses.SesV2Json.stringMemberOrAbsent;
/**
* SES V2 metric data ({@code POST /v2/email/metrics/batch}), the aggregate view of the same stored
* timelines {@code GetMessageInsights} serves one message at a time.
*
* <p>Probe-confirmed against real SES (2026-09-23, us-east-1). The operation is gated on Virtual
* Deliverability Manager, like message insights. Results come back in an unspecified order, both
* {@code Results} and {@code Errors} are always present, and a result always carries its three
* members even when the series is empty. {@link SesMetricData} documents the bucketing.
*
* <p>Validation order is probed, strongest first: the size of {@code Queries}, a duplicate
* {@code Id}, an unsupported dimension name, the aggregated member constraints, the dimension
* value, then the dates. Two orderings could not be observed and are noted in the service docs.
*/
@Path("/v2/email")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class SesMetricsController {
private static final int MAX_QUERIES = 10;
private static final int MAX_DIMENSIONS = 3;
private static final Pattern NAME_CHARSET = Pattern.compile("[A-Za-z0-9_-]+");
private static final Duration MAX_INTERVAL = Duration.ofDays(60);
private static final Duration WINDOW_SLACK = Duration.ofDays(1);
// The enum sets AWS spells out in its validation messages, in AWS's own order.
private static final String METRIC_ENUM =
"[DELIVERY_COMPLAINT, CLICK, SEND, OPEN, COMPLAINT, DELIVERY, DELIVERY_OPEN, "
+ "PERMANENT_BOUNCE, DELIVERY_CLICK, TRANSIENT_BOUNCE]";
private static final String NAMESPACE_ENUM = "[VDM]";
private final SesSentEmailService sentEmailService;
private final SesAccountService accountService;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
@Inject
public SesMetricsController(SesSentEmailService sentEmailService, SesAccountService accountService,
RegionResolver regionResolver, ObjectMapper objectMapper) {
this.sentEmailService = sentEmailService;
this.accountService = accountService;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
}
@POST
@Path("/metrics/batch")
public Response batchGetMetricData(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
accountService.requireVdmEnabled(region);
JsonNode request = readOptionBody(objectMapper, body);
List<JsonNode> queryNodes = requireQueries(request);
requireUniqueIds(queryNodes);
requireKnownDimensionNames(queryNodes);
requireMemberConstraints(queryNodes);
// Probe-confirmed request-wide: a blank identity in the second query outranks a reversed
// date range in the first, and the other way round too.
for (JsonNode query : queryNodes) {
requireDimensionValues(dimensionsOf(query));
}
List<SesMetricData.Query> queries = new ArrayList<>(queryNodes.size());
for (int i = 0; i < queryNodes.size(); i++) {
queries.add(parseQuery(queryNodes.get(i), i + 1));
}
List<SentEmail> emails = withinAnyWindow(sentEmailService.listInRegion(region), queries);
ObjectNode result = objectMapper.createObjectNode();
ArrayNode results = result.putArray("Results");
for (SesMetricData.Query query : queries) {
results.add(render(query, SesMetricData.aggregate(emails, query)));
}
// Never populated in any probe: a bad request fails the whole call rather than one query.
result.putArray("Errors");
return Response.ok(result).build();
}
/**
* Drops the messages no query in the batch can reach, so the per-query aggregation passes walk
* only the requested window rather than every message the region retains. The region's messages
* are already listed and held by then, so this bounds the repeated walks, not the initial scan.
* Events are derived at send time and sit within milliseconds of {@code sentAt}, so a day of
* slack on each side is far more than any timeline needs; the per-event range check in
* {@link SesMetricData} remains the authority.
*/
private static List<SentEmail> withinAnyWindow(List<SentEmail> emails,
List<SesMetricData.Query> queries) {
Instant earliest = null;
Instant latest = null;
for (SesMetricData.Query query : queries) {
if (earliest == null || query.startDate().isBefore(earliest)) {
earliest = query.startDate();
}
if (latest == null || query.endDate().isAfter(latest)) {
latest = query.endDate();
}
}
// A caller may legitimately name a timestamp within a day of Instant's own bounds, and the
// slack must not run off them and turn that into a server error.
Instant from = earliest.isBefore(Instant.MIN.plus(WINDOW_SLACK))
? Instant.MIN : earliest.minus(WINDOW_SLACK);
Instant to = latest.isAfter(Instant.MAX.minus(WINDOW_SLACK))
? Instant.MAX : latest.plus(WINDOW_SLACK);
List<SentEmail> kept = new ArrayList<>();
for (SentEmail email : emails) {
Instant sentAt = email.getSentAt();
if (sentAt == null || (!sentAt.isBefore(from) && sentAt.isBefore(to))) {
kept.add(email);
}
}
return kept;
}
private ObjectNode render(SesMetricData.Query query, SesMetricData.Series series) {
ObjectNode node = objectMapper.createObjectNode();
node.put("Id", query.id());
ArrayNode timestamps = node.putArray("Timestamps");
for (Instant timestamp : series.timestamps()) {
timestamps.add(timestamp.toEpochMilli() / 1000.0);
}
ArrayNode values = node.putArray("Values");
for (Long value : series.values()) {
values.add(value);
}
return node;
}
private static List<JsonNode> requireQueries(JsonNode request) {
JsonNode queries = request.path("Queries");
// Absent and null fail the list constraint, but a present value of the wrong shape is a
// deserialization failure, the same treatment the Dimensions map gets below.
if (!queries.isMissingNode() && !queries.isNull() && !queries.isArray()) {
throw SesV2Json.unexpectedStartError(queries);
}
if (!queries.isArray() || queries.isEmpty()) {
throw listConstraint("Member must have length greater than or equal to 1");
}
if (queries.size() > MAX_QUERIES) {
throw listConstraint("Member must have length less than or equal to " + MAX_QUERIES);
}
List<JsonNode> nodes = new ArrayList<>(queries.size());
for (JsonNode query : queries) {
if (!query.isObject()) {
throw SesV2Json.unexpectedStartError(query);
}
nodes.add(query);
}
return nodes;
}
private static void requireUniqueIds(List<JsonNode> queries) {
Set<String> seen = new LinkedHashSet<>();
for (JsonNode query : queries) {
String id = stringMemberOrAbsent(query, "Id");
if (id != null && !seen.add(id)) {
throw new AwsException("BadRequestException",
"All queries must have a unique identifier.", 400);
}
}
}
/**
* An unknown dimension name outranks the member constraints: a query carrying both an unknown
* dimension and an invalid Metric reports the dimension.
*/
private static void requireKnownDimensionNames(List<JsonNode> queries) {
for (JsonNode query : queries) {
JsonNode dimensions = query.path("Dimensions");
if (dimensions.isMissingNode() || dimensions.isNull()) {
continue;
}
// A map member has to be a JSON object: an array or a scalar is a deserialization
// failure, not an absent Dimensions that silently drops the filter.
if (!dimensions.isObject()) {
throw SesV2Json.unexpectedStartError(dimensions);
}
Iterator<String> names = dimensions.fieldNames();
while (names.hasNext()) {
if (!SesMetricData.DIMENSION_NAMES.contains(names.next())) {
throw new AwsException("BadRequestException",
"Unsupported dimension provided.", 400);
}
}
}
}
/**
* The Smithy member constraints, aggregated into one message the way AWS reports them. The
* probed order is metric, namespace, id; the position of an empty Dimensions map among them was
* not observed.
*/
private static void requireMemberConstraints(List<JsonNode> queries) {
List<String> violations = new ArrayList<>();
for (int i = 0; i < queries.size(); i++) {
JsonNode query = queries.get(i);
int position = i + 1;
String metric = stringMemberOrAbsent(query, "Metric");
if (metric == null || !SesMetricData.METRICS.contains(metric)) {
violations.add(memberConstraint(position, "metric",
"Member must satisfy enum value set: " + METRIC_ENUM));
}
String namespace = stringMemberOrAbsent(query, "Namespace");
if (namespace == null || !"VDM".equals(namespace)) {
violations.add(memberConstraint(position, "namespace",
"Member must satisfy enum value set: " + NAMESPACE_ENUM));
}
String id = stringMemberOrAbsent(query, "Id");
if (id == null || id.isEmpty()) {
violations.add(memberConstraint(position, "id",
"Member must have length greater than or equal to 1"));
} else if (id.length() > 255) {
violations.add(memberConstraint(position, "id",
"Member must have length less than or equal to 255"));
}
JsonNode dimensions = query.path("Dimensions");
if (dimensions.isObject() && dimensions.isEmpty()) {
violations.add(memberConstraint(position, "dimensions",
"Member must have length greater than or equal to 1"));
}
// Reachable only since TENANT_NAME made a fourth key possible; probe-confirmed.
if (dimensions.isObject() && dimensions.size() > MAX_DIMENSIONS) {
violations.add(memberConstraint(position, "dimensions",
"Member must have length less than or equal to " + MAX_DIMENSIONS));
}
}
if (!violations.isEmpty()) {
throw aggregated(violations);
}
}
private static Map<String, String> dimensionsOf(JsonNode query) {
Map<String, String> dimensions = new LinkedHashMap<>();
JsonNode node = query.path("Dimensions");
if (node.isObject()) {
Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> field = fields.next();
if (!field.getValue().isTextual()) {
throw new AwsException("SerializationException", null, 400);
}
dimensions.put(field.getKey(), field.getValue().textValue());
}
}
return dimensions;
}
private SesMetricData.Query parseQuery(JsonNode query, int position) {
Map<String, String> dimensions = dimensionsOf(query);
Instant startDate = requireTimestamp(query, "StartDate", "startDate", position);
Instant endDate = requireTimestamp(query, "EndDate", "endDate", position);
if (!startDate.isBefore(endDate)) {
throw new AwsException("BadRequestException",
"Expected start date to be before the end date.", 400);
}
if (Duration.between(startDate, endDate).compareTo(MAX_INTERVAL) > 0) {
throw new AwsException("BadRequestException",
"Invalid interval, can request at most 60 days. Please partition your "
+ "requested interval.", 400);
}
return new SesMetricData.Query(stringMemberOrAbsent(query, "Id"),
stringMemberOrAbsent(query, "Metric"), dimensions, startDate, endDate);
}
/**
* Each dimension validates its own value, probe-confirmed 2026-09-24 against real SES. ISP,
* the configuration set and the tenant share one charset, ASCII alphanumerics plus underscore
* and hyphen, which is the rule AWS spells out in its own two messages. An identity is either
* a bare name or {@code local@domain} with both halves present. The order in which two bad
* values in one query are reported was not observed and is Floci's choice.
*/
private static void requireDimensionValues(Map<String, String> dimensions) {
String identity = dimensions.get("EMAIL_IDENTITY");
if (identity != null && !isIdentity(identity)) {
throw new AwsException("BadRequestException", "Invalid email identity provided.", 400);
}
String isp = dimensions.get("ISP");
if (isp != null && !NAME_CHARSET.matcher(isp).matches()) {
throw new AwsException("BadRequestException", "Invalid ISP name provided.", 400);
}
requireName(dimensions.get("CONFIGURATION_SET"), "configuration set name",
"The configuration set name must be specified.");
requireName(dimensions.get("TENANT_NAME"), "tenant name", "TenantName cannot be empty");
}
private static void requireName(String value, String noun, String blankMessage) {
if (value == null) {
return;
}
if (value.isEmpty()) {
throw new AwsException("BadRequestException", blankMessage, 400);
}
if (!NAME_CHARSET.matcher(value).matches()) {
throw new AwsException("BadRequestException", "Invalid " + noun + " <" + value
+ ">: only alphanumeric ASCII characters, '_', and '-' are allowed.", 400);
}
}
/**
* Accepts every identity the probe accepted (a bare label, a domain, and local@domain in any
* case) and rejects every one it refused (blank, a missing half, a space, a star).
*/
private static boolean isIdentity(String value) {
if (value.isEmpty() || value.chars().anyMatch(c -> c == '*' || Character.isWhitespace(c))) {
return false;
}
int at = value.indexOf('@');
if (at < 0) {
return true;
}
return at > 0 && at < value.length() - 1 && value.indexOf('@', at + 1) < 0;
}
private static Instant requireTimestamp(JsonNode query, String field, String member, int position) {
JsonNode node = query.path(field);
if (node.isMissingNode() || node.isNull()) {
throw aggregated(List.of(memberConstraint(position, member, "Member must not be null")));
}
if (node.isNumber()) {
try {
return Instant.ofEpochMilli(Math.round(node.doubleValue() * 1000.0));
} catch (DateTimeException e) {
// A value outside Instant's range is the caller's, so it is a 400, not a 500.
throw new AwsException("SerializationException", e.getMessage(), 400);
}
}
if (node.isTextual()) {
try {
return Instant.parse(node.asText());
} catch (DateTimeParseException e) {
throw new AwsException("SerializationException", e.getMessage(), 400);
}
}
throw SesV2Json.unexpectedStartError(node);
}
private static String memberConstraint(int position, String member, String constraint) {
return "Value at 'queries." + position + ".member." + member
+ "' failed to satisfy constraint: " + constraint;
}
private static AwsException listConstraint(String constraint) {
return aggregated(List.of("Value at 'queries' failed to satisfy constraint: " + constraint));
}
private static AwsException aggregated(List<String> violations) {
String header = violations.size() == 1
? "1 validation error detected: "
: violations.size() + " validation errors detected: ";
return new AwsException("BadRequestException",
header + String.join("; ", violations), 400);
}
}
@@ -254,7 +254,7 @@ public class SesQueryHandler {
// ListManagementOptions is a v2-only SendEmail field; the v1 Query API has no equivalent.
String messageId = sesService.sendEmail(source, toAddresses, ccAddresses, bccAddresses,
replyToAddresses, returnPath, subject, bodyText, bodyHtml, configurationSetName,
emailTags, List.of(), null, region);
emailTags, List.of(), null, null, region);
String result = new XmlBuilder().elem("MessageId", messageId).build();
return Response.ok(AwsQueryResponse.envelope("SendEmail", AwsNamespaces.SES, result)).build();
@@ -272,7 +272,7 @@ public class SesQueryHandler {
List<MessageTag> emailTags = extractMessageTags(params, "Tags");
String messageId = sesService.sendRawEmail(source, destinations, rawMessage,
null, configurationSetName, emailTags, null, region);
null, configurationSetName, emailTags, null, null, region);
String result = new XmlBuilder().elem("MessageId", messageId).build();
return Response.ok(AwsQueryResponse.envelope("SendRawEmail", AwsNamespaces.SES, result)).build();
@@ -606,7 +606,7 @@ public class SesQueryHandler {
List<MessageTag> emailTags = extractMessageTags(params, "Tags");
String messageId = sesService.sendTemplatedEmail(source, toAddresses, ccAddresses,
bccAddresses, replyToAddresses, returnPath, resolvedName, templateData,
configurationSetName, emailTags, List.of(), null, region);
configurationSetName, emailTags, List.of(), null, null, region);
String result = new XmlBuilder().elem("MessageId", messageId).build();
return Response.ok(AwsQueryResponse.envelope("SendTemplatedEmail", AwsNamespaces.SES, result)).build();
@@ -753,7 +753,7 @@ public class SesQueryHandler {
List<BulkEmailEntryResult> results = sesService.sendBulkTemplatedEmail(source, replyToAddresses,
returnPath, template.getSubject(), template.getTextPart(), template.getHtmlPart(),
defaultTemplateData, entries, configurationSetName,
defaultEmailTags, List.of(), region);
defaultEmailTags, List.of(), null, region);
XmlBuilder xml = new XmlBuilder().start("Status");
for (BulkEmailEntryResult result : results) {
@@ -125,7 +125,7 @@ public class SesSendController {
configurationSetName, regionResolver.getAccountId(), region);
messageId = sesService.sendRawEmail(fromEmailAddress, allDestinations, rawData,
feedbackForwardingAddress, configurationSetName, emailTags, listManagement,
region);
tenantName, region);
} else if (content.has("Simple")) {
if (fromEmailAddress == null || fromEmailAddress.isBlank()) {
// AWS returns BadRequestException with a null message body here.
@@ -142,7 +142,8 @@ public class SesSendController {
messageId = sesService.sendEmail(fromEmailAddress, toAddresses, ccAddresses,
bccAddresses, replyToAddresses, feedbackForwardingAddress,
subject, bodyText, bodyHtml,
configurationSetName, emailTags, additionalHeaders, listManagement, region);
configurationSetName, emailTags, additionalHeaders, listManagement,
tenantName, region);
} else if (content.has("Template")) {
if (fromEmailAddress == null || fromEmailAddress.isBlank()) {
throw new AwsException("BadRequestException", "Source cannot be empty", 400);
@@ -175,7 +176,7 @@ public class SesSendController {
messageId = sesService.sendTemplatedEmail(fromEmailAddress, toAddresses, ccAddresses,
bccAddresses, replyToAddresses, feedbackForwardingAddress,
resolvedName, templateData,
configurationSetName, emailTags, additionalHeaders, listManagement, region);
configurationSetName, emailTags, additionalHeaders, listManagement, tenantName, region);
} else {
JsonNode inline = template.path("TemplateContent");
String subject = inline.path("Subject").asText(null);
@@ -190,7 +191,7 @@ public class SesSendController {
messageId = sesService.sendInlineTemplatedEmail(fromEmailAddress, toAddresses,
ccAddresses, bccAddresses, replyToAddresses, feedbackForwardingAddress,
subject, text, html, templateData,
configurationSetName, emailTags, additionalHeaders, listManagement, region);
configurationSetName, emailTags, additionalHeaders, listManagement, tenantName, region);
}
} else {
throw new AwsException("BadRequestException",
@@ -318,7 +319,7 @@ public class SesSendController {
List<BulkEmailEntryResult> results = sesService.sendBulkTemplatedEmail(fromEmailAddress,
replyToAddresses, feedbackForwardingAddress, subject, text, html,
defaultTemplateData, entries, configurationSetName,
defaultEmailTags, defaultHeaders, region);
defaultEmailTags, defaultHeaders, tenantName, region);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode arr = response.putArray("BulkEmailEntryResults");
@@ -56,6 +56,14 @@ public class SesSentEmailService {
return emailStore.scan(k -> k.startsWith(prefix)).size();
}
/**
* Every stored message for one region, for the metric aggregation behind BatchGetMetricData.
*/
public List<SentEmail> listInRegion(String region) {
String prefix = "email::" + region + "::";
return emailStore.scan(k -> k.startsWith(prefix));
}
public List<SentEmail> listAll() {
return emailStore.scan(k -> k.startsWith("email::"));
}
@@ -216,7 +216,7 @@ public class SesService {
String subject, String bodyText, String bodyHtml,
String configurationSetName, List<MessageTag> emailTags,
List<MessageHeader> additionalHeaders, ListManagementOptions listManagement,
String region) {
String tenantName, String region) {
if (source == null || source.isBlank()) {
throw new AwsException("InvalidParameterValue", "Source email is required.", 400);
}
@@ -266,6 +266,8 @@ public class SesService {
SentEmail email = new SentEmail(messageId, region, source, toAddresses, ccAddresses,
bccAddresses, replyToAddresses, subject, bodyText, bodyHtml);
email.setReturnPath(effectiveReturnPath);
email.setConfigurationSetName(firstNonBlank(effectiveConfigSet));
email.setTenantName(firstNonBlank(tenantName));
if (additionalHeaders != null && !additionalHeaders.isEmpty()) {
email.setHeaders(additionalHeaders);
}
@@ -310,7 +312,7 @@ public class SesService {
public String sendRawEmail(String source, List<String> destinations, String rawMessage,
String returnPath, String configurationSetName, List<MessageTag> emailTags,
ListManagementOptions listManagement, String region) {
ListManagementOptions listManagement, String tenantName, String region) {
if (rawMessage == null || rawMessage.isBlank()) {
throw new AwsException("InvalidParameterValue", "RawMessage.Data is required.", 400);
}
@@ -384,6 +386,8 @@ public class SesService {
: firstNonBlank(headers.returnPath(), returnPath, effectiveSource);
SentEmail email = new SentEmail(messageId, region, effectiveSource, effectiveDestinations, rawMessage);
email.setReturnPath(effectiveReturnPath);
email.setConfigurationSetName(firstNonBlank(effectiveConfigSet));
email.setTenantName(firstNonBlank(tenantName));
// The MIME subject is already parsed for the published events; store it too so
// GetMessageInsights reports it for a raw send as it does for a simple one. The parser
// yields "" for a missing header, and an absent subject must stay absent.
@@ -550,7 +554,9 @@ public class SesService {
private record IdentityNotificationTarget(String topicArn, boolean includeHeaders) {}
private static String extractEmailAddress(String source) {
// Package-private: the metric aggregation normalizes a stored Source the same way the
// send path does, so "Name <addr>" still matches an EMAIL_IDENTITY dimension.
static String extractEmailAddress(String source) {
int open = source.indexOf('<');
int close = source.indexOf('>', open + 1);
if (open >= 0 && close > open) {
@@ -717,6 +723,7 @@ public class SesService {
List.of(emailAddress), List.of(), List.of(), List.of(),
template.getTemplateSubject(), null, renderedHtml);
email.setReturnPath(template.getFromEmailAddress());
email.setConfigurationSetName(firstNonBlank(effectiveConfigSet));
email.setInsights(SesMessageInsights.build(List.of(emailAddress),
SesRecipientEvents.classify(List.of(emailAddress), suppressedReasons, rejected),
email.getSentAt()));
@@ -1426,12 +1433,13 @@ public class SesService {
String returnPath, String templateName, JsonNode templateData,
String configurationSetName, List<MessageTag> emailTags,
List<MessageHeader> additionalHeaders,
ListManagementOptions listManagement, String region) {
ListManagementOptions listManagement, String tenantName, String region) {
EmailTemplate template = templateService.getTemplate(templateName, region);
return sendInlineTemplatedEmail(source, toAddresses, ccAddresses, bccAddresses,
replyToAddresses, returnPath, template.getSubject(), template.getTextPart(),
template.getHtmlPart(), templateData,
configurationSetName, emailTags, additionalHeaders, listManagement, region);
configurationSetName, emailTags, additionalHeaders, listManagement,
tenantName, region);
}
/**
@@ -1456,13 +1464,14 @@ public class SesService {
JsonNode templateData,
String configurationSetName, List<MessageTag> emailTags,
List<MessageHeader> additionalHeaders,
ListManagementOptions listManagement, String region) {
ListManagementOptions listManagement, String tenantName, String region) {
requireInlineTemplateContent(subject, textPart, htmlPart);
return sendEmail(source, toAddresses, ccAddresses, bccAddresses, replyToAddresses, returnPath,
SesTemplateService.applyTemplateData(subject, templateData),
SesTemplateService.applyTemplateData(textPart, templateData),
SesTemplateService.applyTemplateData(htmlPart, templateData),
configurationSetName, emailTags, additionalHeaders, listManagement, region);
configurationSetName, emailTags, additionalHeaders, listManagement,
tenantName, region);
}
public List<BulkEmailEntryResult> sendBulkTemplatedEmail(String source,
@@ -1474,7 +1483,7 @@ public class SesService {
String configurationSetName,
List<MessageTag> defaultEmailTags,
List<MessageHeader> defaultHeaders,
String region) {
String tenantName, String region) {
if (source == null || source.isBlank()) {
throw new AwsException("InvalidParameterValue", "Source email is required.", 400);
}
@@ -1514,7 +1523,7 @@ public class SesService {
SesTemplateService.applyTemplateData(subject, merged),
SesTemplateService.applyTemplateData(textPart, merged),
SesTemplateService.applyTemplateData(htmlPart, merged),
configurationSetName, mergedTags, mergedHeaders, null, region);
configurationSetName, mergedTags, mergedHeaders, null, tenantName, region);
results.add(BulkEmailEntryResult.success(messageId));
} catch (AwsException e) {
results.add(BulkEmailEntryResult.failure(
@@ -66,6 +66,20 @@ public class SentEmail {
@JsonProperty("EmailTags")
private List<MessageTag> emailTags;
/**
* The configuration set the send resolved to, which BatchGetMetricData filters on. Absent when
* the send named none and no default applied.
*/
@JsonProperty("ConfigurationSetName")
private String configurationSetName;
/**
* The tenant the send named, which the TENANT_NAME metric dimension filters on. Absent for a
* send that named none, and always absent on the v1 surface, which has no tenants.
*/
@JsonProperty("TenantName")
private String tenantName;
/**
* Per-recipient event timelines, derived at send time and served by {@code GetMessageInsights}.
*/
@@ -167,6 +181,14 @@ public class SentEmail {
public List<MessageTag> getEmailTags() { return emailTags; }
public void setEmailTags(List<MessageTag> emailTags) { this.emailTags = emailTags; }
public String getTenantName() { return tenantName; }
public void setTenantName(String tenantName) { this.tenantName = tenantName; }
public String getConfigurationSetName() { return configurationSetName; }
public void setConfigurationSetName(String configurationSetName) {
this.configurationSetName = configurationSetName;
}
public List<EmailInsights> getInsights() { return insights; }
public void setInsights(List<EmailInsights> insights) { this.insights = insights; }
}