feat(ses): publish events to Firehose, EventBridge, CloudWatch (#1188)

* feat(ses): publish events to Firehose, EventBridge, and CloudWatch destinations

Extend SES V2 configuration set event publishing so destinations beyond
SnsDestination actually deliver. Previously KinesisFirehoseDestination,
EventBridgeDestination, and CloudWatchDestination were stored but the
publisher logged a warning and skipped. PinpointDestination still skips.

- KinesisFirehoseDestination → single Firehose PutRecord per event;
  S3-backed streams flush accumulated records as NDJSON once the default
  count threshold is reached.
- EventBridgeDestination → PutEvents entry with Source=aws.ses,
  DetailType="Email <EventTypeLabel>", payload as Detail. Region is
  stamped on the entry (so matchesPattern + envelope agree on a
  non-default region) and Resources is always present (empty when
  sourceArn is null — matchesPattern's resources-filter branch casts
  entry.get("Resources") unconditionally).
- CloudWatchDestination → MetricDatum to AWS/SES with Unit=Count.
  Dimensions resolved from DimensionConfigurations against EmailTags
  (MESSAGE_TAG / messageTag), email headers (EMAIL_HEADER / emailHeader),
  or ses:configuration-set, falling back to DefaultDimensionValue.
  Timestamp left to putMetricData's epoch-seconds default.

Tests
- SesEventPublishingV2IntegrationTest @Order 14-28: per-destination
  setup → send → assert, plus a cross-region (eu-west-1) EventBridge
  case pinning region propagation end-to-end.
- SesEventPublisherTest (Mockito ArgumentCaptor): the EB PutEvents
  entry always carries Resources as an ArrayNode — integration tests
  cannot pin this because EventBridgeService.buildEventEnvelope
  defaults a missing key via getOrDefault.

Docs
- docs/services/ses.md: replace the SNS-only claim with the four
  supported destination types.

* fix(ses): use AWS past-tense detail-type for EventBridge SES events

The EventBridge publisher was emitting "Email Send", "Email Delivery",
etc — derived from the SNS notification eventType vocabulary by
prepending "Email ". AWS uses a separate past-tense vocabulary on
EventBridge: "Email Sent", "Email Delivered", "Email Bounced", "Email
Complaint Received", "Email Rejected", "Email Opened", "Email Clicked",
"Email Rendering Failed", "Email Delivery Delayed", "Email Subscribed"
(see https://docs.aws.amazon.com/eventbridge/latest/ref/events-ref-ses.html).

A customer rule pattern keyed on the AWS value
({"source":["aws.ses"],"detail-type":["Email Delivered"]}) would
silently fail to match Floci events.

Changes:
- Add SesEventPayload.eventBridgeDetailType returning the past-tense
  EventBridge vocabulary. Kept separate from eventTypeLabel (which
  remains correct for SNS notifications and CloudWatch metric names).
- SesEventPublisher.publishEventBridge uses the new mapping.

Tests
- SesEventPayloadTest.eventBridgeDetailType_matchesAwsPastTenseVocabulary:
  pins all 10 mappings against AWS docs.
- SesEventPublishingV2IntegrationTest @Order 29
  (eventBridge_detailTypePattern_keyedOnAwsSentValue_matches):
  structural pin — creates a rule with EventPattern
  {"source":["aws.ses"],"detail-type":["Email Sent"]} and asserts the
  SQS target receives the SEND envelope. A regression to "Email Send"
  would cause the rule to silently drop the event, failing the test
  without relying on any hard-coded assertion string.
- Existing tests updated to assert the AWS values:
  SesEventPublishingV2IntegrationTest 4 assertions; sdk-test-java
  SesEventPublishingTest 3 assertions.

* fix(ses): emit CloudWatch metric name "RenderingFailure" without space

AWS CloudWatch metric publishing for SES uses "RenderingFailure" (no
space) for the RENDERING_FAILURE event type — verified against real
AWS by configuring a CW event destination on a configuration set,
sending a templated email with a missing TemplateData key to trigger
the rendering failure path, and capturing the new metric name from
`aws cloudwatch list-metrics --namespace AWS/SES`.

Floci's publisher was previously sourcing the CW MetricName from
SesEventPayload.eventTypeLabel, which returns "Rendering Failure" (with
space). That spelling is correct for the SNS notification's eventType
field but wrong for CloudWatch — customer dashboards / alarms keyed on
the AWS-correct "RenderingFailure" never see Floci's metric.

Changes:
- Add SesEventPayload.cloudWatchMetricName returning the CW spelling.
  Mirrors eventTypeLabel for every other case so the two stay aligned
  in shape; only RENDERING_FAILURE differs.
- SesEventPublisher.publishCloudWatch uses the new mapping.
- SesEventPayloadTest.cloudWatchMetricName_matchesAwsCwSpelling pins
  all 10 mappings; RENDERING_FAILURE expectation comes from the live
  AWS capture rather than an AWS docs guess.

DELIVERY_DELAY remains as "DeliveryDelay" in this commit — it could
not be triggered conveniently from the SES sandbox (needs genuine SES
backoff), so leaving the existing value rather than guessing. Flagged
in code comments as needing future verification.

The other simple metric names (Send, Delivery, Bounce, Complaint) were
also verified against the same AWS capture and match Floci's existing
spelling byte-for-byte — no change needed for those.
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-06-09 00:36:28 -05:00
1 parent 3065774e80
commit 35f597addd
7 files changed
+1893 -31

No files matched your search

@@ -219,7 +219,7 @@ final class SesEventPayload {
}
}
private static String eventTypeLabel(String eventType) {
static String eventTypeLabel(String eventType) {
return switch (eventType) {
case "SEND" -> "Send";
case "REJECT" -> "Reject";
@@ -235,6 +235,58 @@ final class SesEventPayload {
};
}
/**
* Returns the CloudWatch {@code MetricName} value AWS SES uses for an event.
* Mostly matches {@link #eventTypeLabel}, but at least one event type has a
* different spelling on CloudWatch than on the SNS payload's {@code eventType}
* field, and they must not be unified through {@code eventTypeLabel} or the SNS
* payload regresses to a non-AWS value:
* - {@code RENDERING_FAILURE} → CW {@code "RenderingFailure"} (no space)
* vs SNS {@code "Rendering Failure"} (with space) — verified against real
* AWS via a CW event destination + a templated send with a missing
* {@code TemplateData} key.
* {@code DELIVERY_DELAY} is not directly observed yet (sandbox cannot easily
* trigger SES backoff); kept as {@code "DeliveryDelay"} pending verification.
*/
static String cloudWatchMetricName(String eventType) {
return switch (eventType) {
case "SEND" -> "Send";
case "REJECT" -> "Reject";
case "BOUNCE" -> "Bounce";
case "COMPLAINT" -> "Complaint";
case "DELIVERY" -> "Delivery";
case "OPEN" -> "Open";
case "CLICK" -> "Click";
case "RENDERING_FAILURE" -> "RenderingFailure";
case "DELIVERY_DELAY" -> "DeliveryDelay";
case "SUBSCRIPTION" -> "Subscription";
default -> eventType;
};
}
/**
* Returns the EventBridge {@code detail-type} value for a SES event. AWS uses a
* separate past-tense vocabulary on EventBridge (e.g. {@code Email Sent}) that
* differs from the SNS notification {@code eventType} value (e.g. {@code Send})
* — a rule pattern keyed on the EventBridge value will not match the SNS value.
* Reference: https://docs.aws.amazon.com/eventbridge/latest/ref/events-ref-ses.html
*/
static String eventBridgeDetailType(String eventType) {
return switch (eventType) {
case "SEND" -> "Email Sent";
case "REJECT" -> "Email Rejected";
case "BOUNCE" -> "Email Bounced";
case "COMPLAINT" -> "Email Complaint Received";
case "DELIVERY" -> "Email Delivered";
case "OPEN" -> "Email Opened";
case "CLICK" -> "Email Clicked";
case "RENDERING_FAILURE" -> "Email Rendering Failed";
case "DELIVERY_DELAY" -> "Email Delivery Delayed";
case "SUBSCRIPTION" -> "Email Subscribed";
default -> "Email " + eventType;
};
}
private static String blockName(String eventType) {
return switch (eventType) {
case "SEND" -> "send";
@@ -1,9 +1,18 @@
package io.github.hectorvent.floci.services.ses;
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.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
import io.github.hectorvent.floci.services.firehose.FirehoseService;
import io.github.hectorvent.floci.services.firehose.model.Record;
import io.github.hectorvent.floci.services.ses.model.CloudWatchDestination;
import io.github.hectorvent.floci.services.ses.model.CloudWatchDimensionConfiguration;
import io.github.hectorvent.floci.services.ses.model.ConfigurationSet;
import io.github.hectorvent.floci.services.ses.model.EventDestination;
import io.github.hectorvent.floci.services.ses.model.MessageHeader;
@@ -13,25 +22,42 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Publishes SES event-publishing notifications to the event destinations attached
* to a {@link ConfigurationSet}. This MVP only delivers to {@code SnsDestination};
* Firehose, EventBridge, CloudWatch, and Pinpoint destinations are logged and skipped.
* to a {@link ConfigurationSet}. {@code SnsDestination},
* {@code KinesisFirehoseDestination}, {@code EventBridgeDestination}, and
* {@code CloudWatchDestination} are delivered live; Pinpoint destinations are
* logged and skipped.
*/
@ApplicationScoped
public class SesEventPublisher {
private static final Logger LOG = Logger.getLogger(SesEventPublisher.class);
private static final String SES_METRIC_NAMESPACE = "AWS/SES";
private final SnsService snsService;
private final FirehoseService firehoseService;
private final EventBridgeService eventBridgeService;
private final CloudWatchMetricsService cloudWatchMetricsService;
private final ObjectMapper objectMapper;
@Inject
public SesEventPublisher(SnsService snsService, ObjectMapper objectMapper) {
public SesEventPublisher(SnsService snsService, FirehoseService firehoseService,
EventBridgeService eventBridgeService,
CloudWatchMetricsService cloudWatchMetricsService,
ObjectMapper objectMapper) {
this.snsService = snsService;
this.firehoseService = firehoseService;
this.eventBridgeService = eventBridgeService;
this.cloudWatchMetricsService = cloudWatchMetricsService;
this.objectMapper = objectMapper;
}
@@ -61,7 +87,8 @@ public class SesEventPublisher {
continue;
}
try {
dispatch(ed, eventType, payloadJson, defaultRegion);
dispatch(ed, eventType, payloadJson, sourceArn, configurationSet.getName(),
emailTags, additionalHeaders, defaultRegion);
} catch (Exception e) {
LOG.warnf(e, "Failed to publish SES event %s to destination %s",
eventType, ed.getName());
@@ -69,7 +96,10 @@ public class SesEventPublisher {
}
}
private void dispatch(EventDestination ed, String eventType, String payloadJson, String defaultRegion) {
private void dispatch(EventDestination ed, String eventType, String payloadJson,
String sourceArn, String configurationSetName,
List<MessageTag> emailTags, List<MessageHeader> additionalHeaders,
String defaultRegion) {
if (ed.getSnsDestination() != null) {
String topicArn = ed.getSnsDestination().getTopicArn();
if (topicArn == null || topicArn.isBlank()) {
@@ -85,11 +115,29 @@ public class SesEventPublisher {
ed.getName(), eventType);
return;
}
if (ed.getKinesisFirehoseDestination() != null
|| ed.getEventBridgeDestination() != null
|| ed.getCloudWatchDestination() != null) {
LOG.warnf("SES destination %s: event %s not delivered (only SNS publishing is implemented).",
ed.getName(), eventType);
if (ed.getKinesisFirehoseDestination() != null) {
String streamArn = ed.getKinesisFirehoseDestination().getDeliveryStreamArn();
if (streamArn == null || streamArn.isBlank()) {
LOG.warnf("SES Firehose destination %s: event %s not delivered (DeliveryStreamArn is missing).",
ed.getName(), eventType);
return;
}
publishFirehose(streamArn, payloadJson, ed.getName(), eventType);
return;
}
if (ed.getEventBridgeDestination() != null) {
String busArn = ed.getEventBridgeDestination().getEventBusArn();
if (busArn == null || busArn.isBlank()) {
LOG.warnf("SES EventBridge destination %s: event %s not delivered (EventBusArn is missing).",
ed.getName(), eventType);
return;
}
publishEventBridge(busArn, payloadJson, eventType, sourceArn, ed.getName(), defaultRegion);
return;
}
if (ed.getCloudWatchDestination() != null) {
publishCloudWatch(ed.getCloudWatchDestination(), eventType, configurationSetName,
emailTags, additionalHeaders, defaultRegion);
return;
}
LOG.warnf("SES destination %s: event %s not delivered (no destination target configured).",
@@ -104,4 +152,173 @@ public class SesEventPublisher {
LOG.warnf(e, "SES event publish to SNS topic %s skipped", topicArn);
}
}
private void publishFirehose(String streamArn, String payloadJson,
String destinationName, String eventType) {
String streamName = extractArnResourceName(streamArn);
if (streamName == null) {
LOG.warnf("SES Firehose destination %s: event %s not delivered "
+ "(DeliveryStreamArn %s is malformed).",
destinationName, eventType, streamArn);
return;
}
try {
Record record = new Record();
record.setData(payloadJson.getBytes(StandardCharsets.UTF_8));
firehoseService.putRecord(streamName, record);
} catch (Exception e) {
LOG.warnf(e, "SES event publish to Firehose stream %s skipped", streamName);
}
}
private void publishEventBridge(String busArn, String payloadJson, String eventType,
String sourceArn, String destinationName, String defaultRegion) {
String busName = extractArnResourceName(busArn);
if (busName == null) {
LOG.warnf("SES EventBridge destination %s: event %s not delivered "
+ "(EventBusArn %s is malformed).",
destinationName, eventType, busArn);
return;
}
String region = AwsArnUtils.regionOrDefault(busArn, defaultRegion);
try {
Map<String, Object> entry = new HashMap<>();
entry.put("Source", "aws.ses");
entry.put("DetailType", SesEventPayload.eventBridgeDetailType(eventType));
entry.put("Detail", payloadJson);
entry.put("EventBusName", busName);
entry.put("Region", region);
// Always emit Resources (possibly empty) — EventBridgeService.matchesPattern
// casts entry.get("Resources") to ArrayNode unconditionally for any rule with
// a "resources" filter; an absent key NPEs and silently turns the rule into
// a no-match.
ArrayNode resources = objectMapper.createArrayNode();
if (sourceArn != null && !sourceArn.isBlank()) {
resources.add(sourceArn);
}
entry.put("Resources", resources);
EventBridgeService.PutEventsResult result =
eventBridgeService.putEvents(List.of(entry), region);
if (result.failedCount() > 0) {
LOG.warnf("SES event publish to EventBridge bus %s skipped: %s",
busName, result.entries());
}
} catch (Exception e) {
LOG.warnf(e, "SES event publish to EventBridge bus %s skipped", busName);
}
}
private void publishCloudWatch(CloudWatchDestination dest, String eventType,
String configurationSetName,
List<MessageTag> emailTags,
List<MessageHeader> additionalHeaders,
String defaultRegion) {
List<Dimension> dimensions = new ArrayList<>();
if (dest.getDimensionConfigurations() != null) {
for (CloudWatchDimensionConfiguration cfg : dest.getDimensionConfigurations()) {
if (cfg == null || cfg.getDimensionName() == null
|| cfg.getDimensionName().isBlank()) {
continue;
}
String value = resolveCloudWatchDimensionValue(cfg, configurationSetName,
emailTags, additionalHeaders);
if (value == null || value.isBlank()) {
continue;
}
dimensions.add(new Dimension(cfg.getDimensionName(), value));
}
}
MetricDatum datum = new MetricDatum();
datum.setNamespace(SES_METRIC_NAMESPACE);
datum.setMetricName(SesEventPayload.cloudWatchMetricName(eventType));
datum.setValue(1.0);
datum.setUnit("Count");
datum.setDimensions(dimensions);
// Leave timestamp unset: CloudWatchMetricsService.putMetricData defaults a zero
// timestamp to Instant.now().getEpochSecond() (epoch seconds, not milliseconds).
try {
cloudWatchMetricsService.putMetricData(SES_METRIC_NAMESPACE, List.of(datum),
defaultRegion);
} catch (Exception e) {
LOG.warnf(e, "SES event publish to CloudWatch (event %s) skipped", eventType);
}
}
/**
* Resolves the value of a CloudWatch dimension for a given SES event according to
* {@code DimensionValueSource}. {@code messageTag} consults the user-supplied
* {@code emailTags} plus the auto-added {@code ses:configuration-set} tag;
* {@code emailHeader} consults the email's additional headers (case-insensitive
* lookup per RFC 5322). When the source can't yield a value, falls back to
* {@code DefaultDimensionValue}. {@code linkTag} and unknown sources are not
* resolved against any real input here and immediately fall back to the default.
*
* <p>The V1 SES API documents these enum values as camelCase
* ({@code messageTag} / {@code emailHeader} / {@code linkTag}); the V2 SES API
* documents the same values as SCREAMING_SNAKE
* ({@code MESSAGE_TAG} / {@code EMAIL_HEADER} / {@code LINK_TAG}) and the AWS SDK
* for Java v2 marshals exactly those constant names on the wire. Both forms are
* accepted here so callers on either protocol land on the same resolution path.
*/
private static String resolveCloudWatchDimensionValue(CloudWatchDimensionConfiguration cfg,
String configurationSetName,
List<MessageTag> emailTags,
List<MessageHeader> additionalHeaders) {
String source = cfg.getDimensionValueSource();
String name = cfg.getDimensionName();
String defaultValue = cfg.getDefaultDimensionValue();
if (isMessageTagSource(source)) {
if ("ses:configuration-set".equals(name)) {
return configurationSetName;
}
if (emailTags != null) {
for (MessageTag t : emailTags) {
if (t != null && name.equals(t.name())
&& t.value() != null && !t.value().isBlank()) {
return t.value();
}
}
}
return defaultValue;
}
if (isEmailHeaderSource(source)) {
if (additionalHeaders != null) {
for (MessageHeader h : additionalHeaders) {
if (h != null && name.equalsIgnoreCase(h.name())
&& h.value() != null && !h.value().isBlank()) {
return h.value();
}
}
}
return defaultValue;
}
return defaultValue;
}
private static boolean isMessageTagSource(String source) {
return "messageTag".equalsIgnoreCase(source) || "MESSAGE_TAG".equalsIgnoreCase(source);
}
private static boolean isEmailHeaderSource(String source) {
return "emailHeader".equalsIgnoreCase(source) || "EMAIL_HEADER".equalsIgnoreCase(source);
}
/**
* Extracts the resource name from an AWS ARN's resource segment that follows the
* {@code <type>/<name>} convention (e.g., {@code deliverystream/my-stream},
* {@code event-bus/my-bus}). Returns {@code null} for a malformed ARN or a
* resource segment with no slash or an empty name after the slash.
*/
private static String extractArnResourceName(String arn) {
try {
String resource = AwsArnUtils.parse(arn).resource();
int slash = resource.indexOf('/');
if (slash < 0 || slash == resource.length() - 1) {
return null;
}
return resource.substring(slash + 1);
} catch (IllegalArgumentException e) {
return null;
}
}
}